From 6769363d96cfa10b17804cb786388ceddfb7398c Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Mon, 11 Mar 2024 21:09:38 +0000 Subject: [PATCH] Use RetroFuturaBootstrap instead of LaunchWrapper, significant compatibility improvements (#113) * Start work on RFB bundling/support * Use the first RFB release * Upgrade GSON, RFB, migrate lwjglx redirector to an rfb plugin * Update rfb again * Update to RFB 0.3 APIs * Migrate LCL transformers to RFB * Update release workflow * Fix server main class name * Update RFB with the server fix * Forgot Spotless... * Fix maven publishing of snapshots * Prism: Use included forgePatches jar instead of downloading from Nexus * Fix crash when config/ doesn't already exist * Change server entry point to a custom class, remove SLW forge patch. * Move ASM upgrade to a batch transformer in RFB * Bump RFB * Update Apache Commons Compress * Start work on the relauncher coremod * Update bs&rfb * Fix latest GTNHGradle compat * Update dep versions * Kotlinify buildscript * Fix some more kts bugs, make it easier to run with GT * Fix coremod not loading * Fix remaining LCL.getSources issues that caused e.g. broken NEI handlers * RIP forge patches, you won't be missed * Start on parsing version.json in the relauncher * WIP library downloader * Skip downloading existing files, exit without tripping the SecurityManager * Add missing relauncher libraries, fix jvm arg order * Fix lwjgl3ify not loading itself as a mod, not downloading the main client jar * Progress bar dialog for library downloads * Start work on relauncher guis * Working java detection and selection on Linux * Fix use of some library functions not present in a lwjgl3ify-less instance * Include the ServerMain class in the forgepatches jar * Relauncher stub + graphical console for the new instance * Add a fallback $VALUES search loop * Switch from Rhino to Nashorn for JS * Update rfb and apache commons-lang3 * Fix ItemStackHolder setting, simplify both object holders Closes #93 * Add missing lwjgl.util subpackages Closes #92 * Bump RFB with more asm fixes Closes #37 * Update RFB with the dragonapi fix * Exclude nashorn from LCL to avoid coremods complaining about it * Add proxy lwjglx calls to lwjgl dummy Keyboard/Mouse classes for reflection * Add InputEvents API, handle Minecraft keybindings with it to fix dead key support * Update RFB * Fix some warnings * Add OSX and Windows JVM installation scanning * Start work on translatable strings in the relauncher GUI * Spotless, fix being able to walk with inventory screen open Closes #123 * Update rfb with the java.lang.Compiler fix * Finish rest of gui translations, allow any whitespace to split args, assign very little ram to the bootstrapper process * Add a manifest attribute to more conveniently opt-out of lwjgl3ify transformers * Update RFB, commons-compress, shade in newer commons-io too * Remove the server jar name from java9argx.txt * Update RFB with the #127 fix * Add LiteLoader compatibility, tested with Voxelmap Closes #67 * GL tweaks: move glGetString safety check into bindings, fix GL debug log notification spam * Implement custom OpenGL context version&profile settings via the LWJGL2 Display API * Simple sharedDrawable implementation * Downgrade the servlet api to fix journeymap's new webmap crash * Add sun.awt opens * README updates * RFB 1.0.0 (no changes from 0.4.1) --- .github/workflows/release-tags.yml | 41 +- README.MD | 38 +- addon.gradle | 221 --- addon.late.gradle | 4 - build.gradle | 5 - build.gradle.kts | 345 ++++ dependencies.gradle | 59 +- gradle.properties | 3 + java9args.txt | 10 +- launcher-metadata/version.json | 29 +- .../forgepatches-for-dev-work.json | 34 - prism-libraries/mmc-pack.json | 11 +- .../me.eigenraven.lwjgl3ify.forgepatches.json | 4 +- .../me.eigenraven.lwjgl3ify.launchargs.json | 8 + prism-libraries/patches/net.minecraft.json | 30 +- .../patches/net.minecraftforge.json | 2 +- repositories.gradle | 13 +- settings.gradle | 4 +- .../mods/fml/common/TracingPrintStream.java | 55 - .../EventSubscriptionTransformer.java | 200 --- .../asm/transformers/TerminalTransformer.java | 149 -- .../fml/common/patcher/ClassPatchManager.java | 222 --- .../mods/fml/relauncher/CoreModManager.java | 688 -------- .../java/org/lwjgl/input/Keyboard.java | 38 +- src/generated/java/org/lwjgl/input/Mouse.java | 64 +- .../java/org/lwjglx/opengl/GL11.java | 15 +- .../TransformHelper.java | 1 + .../common/fakelwjgl3ify/SafeRuntimeExit.java | 22 + .../me/eigenraven/lwjgl3ify}/EnumHelper.java | 18 +- .../me/eigenraven/lwjgl3ify/Lwjgl3ify.java | 4 +- .../eigenraven/lwjgl3ify/api/InputEvents.java | 138 ++ .../lwjgl3ify/{ => client}/ClientProxy.java | 54 +- .../lwjgl3ify/client/GLDebugLog.java | 64 +- .../lwjgl3ify/client/GLInfoCrashCallable.java | 42 - .../me/eigenraven/lwjgl3ify/core/Config.java | 61 +- ...xConstantPoolInterfaceMethodRefHelper.java | 93 - .../eigenraven/lwjgl3ify/core/LateInit.java | 34 + .../lwjgl3ify/core/Lwjgl3ifyCoremod.java | 51 +- .../core/LwjglRedirectTransformer.java | 102 -- .../core/PostMixinTransformInjector.java | 41 - .../UnfinalizeObjectHoldersTransformer.java | 121 -- .../mixins/fml/ItemStackHolderRef.java | 8 +- .../mixins/fml/ModVisitorAsmVersion.java | 22 - .../lwjgl3ify/mixins/fml/ObjectHolderRef.java | 24 +- .../mixins/game/MixinMinecraftKeyBinding.java | 23 + .../redirects/InvalidActivityException.java | 22 + .../LiteLoaderClassPathUtilities.java | 154 ++ .../lwjgl3ify/redirects/Pack200.java | 79 + .../lwjgl3ify/relauncher/Downloader.java | 405 +++++ .../lwjgl3ify/relauncher/JvmLocator.java | 222 +++ .../Lwjgl3ifyRelauncherTweaker.java | 127 ++ .../lwjgl3ify/relauncher/ProgressDialog.form | 64 + .../lwjgl3ify/relauncher/ProgressDialog.java | 107 ++ .../lwjgl3ify/relauncher/Relauncher.java | 292 ++++ .../relauncher/RelauncherConfig.java | 184 ++ .../relauncher/RelauncherUserInterface.java | 347 ++++ .../lwjgl3ify/relauncher/SettingsDialog.form | 330 ++++ .../lwjgl3ify/relauncher/SettingsDialog.java | 436 +++++ .../relauncher/TranslationsBundle.java | 77 + .../relauncher/TranslationsBundle_pl_PL.java | 41 + .../eigenraven/lwjgl3ify/rfb/EarlyConfig.java | 106 ++ .../lwjgl3ify/rfb/Lwjgl3ifyRfbPlugin.java} | 70 +- .../lwjgl3ify/rfb/entry/ServerMain.java} | 29 +- .../ExtensibleEnumTransformer.java} | 77 +- .../transformers/ForgePatchTransformer.java | 204 +++ .../LwjglRedirectTransformer.java | 160 ++ .../UnfinalizeObjectHoldersTransformer.java | 109 ++ src/main/java/org/lwjglx/PointerBuffer.java | 14 + .../org/lwjglx/opengl/ContextAttribs.java | 427 ++++- src/main/java/org/lwjglx/opengl/Display.java | 70 +- src/main/java/org/lwjglx/opengl/Drawable.java | 4 + .../java/org/lwjglx/opengl/DrawableGL.java | 7 + .../java/org/lwjglx/opengl/PixelFormat.java | 30 +- .../lwjglx/util/input/ControllerAdapter.java | 326 ++++ .../java/org/lwjglx/util/jinput/KeyMap.java | 290 ++++ .../util/jinput/LWJGLEnvironmentPlugin.java | 51 + .../org/lwjglx/util/jinput/LWJGLKeyboard.java | 119 ++ .../org/lwjglx/util/jinput/LWJGLMouse.java | 182 ++ .../org/lwjglx/util/mapped/CacheLinePad.java | 61 + .../org/lwjglx/util/mapped/CacheLineSize.java | 146 ++ .../org/lwjglx/util/mapped/CacheUtil.java | 195 +++ .../org/lwjglx/util/mapped/MappedField.java | 60 + .../org/lwjglx/util/mapped/MappedForeach.java | 66 + .../org/lwjglx/util/mapped/MappedHelper.java | 385 +++++ .../org/lwjglx/util/mapped/MappedObject.java | 286 +++ .../util/mapped/MappedObjectClassLoader.java | 185 ++ .../util/mapped/MappedObjectTransformer.java | 1530 +++++++++++++++++ .../util/mapped/MappedObjectUnsafe.java | 103 ++ .../org/lwjglx/util/mapped/MappedSet.java | 64 + .../org/lwjglx/util/mapped/MappedSet2.java | 51 + .../org/lwjglx/util/mapped/MappedSet3.java | 54 + .../org/lwjglx/util/mapped/MappedSet4.java | 56 + .../org/lwjglx/util/mapped/MappedType.java | 98 ++ .../java/org/lwjglx/util/mapped/Pointer.java | 45 + .../META-INF/rfb-plugin/lwjgl3ify.properties | 9 + .../relauncherstub/GraphicalConsole.java | 201 +++ .../relauncherstub/RelauncherStubMain.java | 72 + 97 files changed, 9560 insertions(+), 2484 deletions(-) delete mode 100644 addon.gradle delete mode 100644 addon.late.gradle delete mode 100644 build.gradle create mode 100644 build.gradle.kts delete mode 100644 prism-libraries/forgepatches-for-dev-work.json create mode 100644 prism-libraries/patches/me.eigenraven.lwjgl3ify.launchargs.json delete mode 100644 src/forgePatches/java/cpw/mods/fml/common/TracingPrintStream.java delete mode 100644 src/forgePatches/java/cpw/mods/fml/common/asm/transformers/EventSubscriptionTransformer.java delete mode 100644 src/forgePatches/java/cpw/mods/fml/common/asm/transformers/TerminalTransformer.java delete mode 100644 src/forgePatches/java/cpw/mods/fml/common/patcher/ClassPatchManager.java delete mode 100644 src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java create mode 100644 src/main/java/cpw/mods/fml/common/fakelwjgl3ify/SafeRuntimeExit.java rename src/{forgePatches/java/net/minecraftforge/common/util => main/java/me/eigenraven/lwjgl3ify}/EnumHelper.java (93%) create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/api/InputEvents.java rename src/main/java/me/eigenraven/lwjgl3ify/{ => client}/ClientProxy.java (58%) delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/client/GLInfoCrashCallable.java delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/core/FixConstantPoolInterfaceMethodRefHelper.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/core/LateInit.java delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/core/LwjglRedirectTransformer.java delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/core/UnfinalizeObjectHoldersTransformer.java delete mode 100644 src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ModVisitorAsmVersion.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/mixins/game/MixinMinecraftKeyBinding.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/redirects/InvalidActivityException.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/redirects/LiteLoaderClassPathUtilities.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/redirects/Pack200.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/Downloader.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/JvmLocator.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/Lwjgl3ifyRelauncherTweaker.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.form create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/Relauncher.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherConfig.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherUserInterface.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.form create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle_pl_PL.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/rfb/EarlyConfig.java rename src/{forgePatches/java/cpw/mods/fml/relauncher/FMLSecurityManager.java => main/java/me/eigenraven/lwjgl3ify/rfb/Lwjgl3ifyRfbPlugin.java} (61%) rename src/{forgePatches/java/cpw/mods/fml/relauncher/ServerLaunchWrapper.java => main/java/me/eigenraven/lwjgl3ify/rfb/entry/ServerMain.java} (61%) rename src/main/java/me/eigenraven/lwjgl3ify/{core/ExtensibleEnumTransformerHelper.java => rfb/transformers/ExtensibleEnumTransformer.java} (82%) create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ForgePatchTransformer.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/LwjglRedirectTransformer.java create mode 100644 src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/UnfinalizeObjectHoldersTransformer.java create mode 100644 src/main/java/org/lwjglx/util/input/ControllerAdapter.java create mode 100644 src/main/java/org/lwjglx/util/jinput/KeyMap.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java create mode 100644 src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheLinePad.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheLineSize.java create mode 100644 src/main/java/org/lwjglx/util/mapped/CacheUtil.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedField.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedForeach.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedHelper.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObject.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet2.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet3.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedSet4.java create mode 100644 src/main/java/org/lwjglx/util/mapped/MappedType.java create mode 100644 src/main/java/org/lwjglx/util/mapped/Pointer.java create mode 100644 src/main/resources/META-INF/rfb-plugin/lwjgl3ify.properties create mode 100644 src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/GraphicalConsole.java create mode 100644 src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/RelauncherStubMain.java diff --git a/.github/workflows/release-tags.yml b/.github/workflows/release-tags.yml index 3d2169d..c0f44ca 100644 --- a/.github/workflows/release-tags.yml +++ b/.github/workflows/release-tags.yml @@ -9,34 +9,39 @@ permissions: contents: write jobs: - release-tags: + build: runs-on: ubuntu-latest + env: + VERSION: ${{ github.ref_name }} + RELEASE_VERSION: ${{ github.ref_name }} + SNAPSHOT: ${{ contains(github.ref_name, 'snapshot') || contains(github.event.head_commit.message, '[snapshot]') }} + MAVEN_PUBLISHING_URL: ${{ vars.MAVEN_PUBLISHING_URL || 'https://nexus.gtnewhorizons.com/repository/releases/' }} steps: - name: Checkout mod repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 32 - - name: Set release version - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + - name: Validate gradle wrapper checksum + uses: gradle/wrapper-validation-action@v1 - - name: Set up JDK 8 - uses: actions/setup-java@v3 + - name: Set up JDK 8 and 17 + uses: actions/setup-java@v4 with: java-version: | 8 17 - distribution: 'temurin' + distribution: 'zulu' cache: gradle - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Setup the workspace - run: ./gradlew --info --stacktrace ${{ inputs.workspace }} + run: ./gradlew --build-cache --info --stacktrace -PmavenPublishUrl='${{ env.MAVEN_PUBLISHING_URL }}' ${{ inputs.workspace }} - name: Build the mod - run: ./gradlew --info --stacktrace build + run: ./gradlew --build-cache --info --stacktrace -PmavenPublishUrl='${{ env.MAVEN_PUBLISHING_URL }}' build # Continue on error in the following steps to make sure releases still get made even if one of the methods fails @@ -48,6 +53,10 @@ jobs: - name: Release under current tag run: | + PRERELEASE="" + if [[ "$SNAPSHOT" == "true" ]]; then + PRERELEASE="--prerelease" + fi export "CHANGELOG_FILE=$(mktemp --suffix=.md)" echo "CHANGELOG_FILE=${CHANGELOG_FILE}" >> $GITHUB_ENV gh api --method POST -H "Accept: application/vnd.github+json" \ @@ -55,18 +64,24 @@ jobs: -f tag_name="${RELEASE_VERSION}" \ --jq ".body" > "${CHANGELOG_FILE}" cat "${CHANGELOG_FILE}" - gh release create "${RELEASE_VERSION}" -F "${CHANGELOG_FILE}" ./build/libs/*.jar ./build/libs/*.json ./build/distributions/*.zip + gh release create "${RELEASE_VERSION}" -F "${CHANGELOG_FILE}" $PRERELEASE ./build/libs/*.jar ./build/libs/*.json ./build/distributions/*.zip shell: bash continue-on-error: true env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Publish to Maven, Modrinth and CurseForge - run: ./gradlew --info --stacktrace build publish + - name: Publish to Maven + run: ./gradlew --build-cache --info --stacktrace -PmavenPublishUrl='${{ env.MAVEN_PUBLISHING_URL }}' build publish continue-on-error: true env: MAVEN_USER: ${{ secrets.MAVEN_USER }} MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + if: ${{ env.MAVEN_USER != '' }} + + - name: Publish to Modrinth and CurseForge + run: ./gradlew --build-cache --info --stacktrace -PmavenPublishUrl='${{ env.MAVEN_PUBLISHING_URL }}' build publish + continue-on-error: true + env: MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} - if: ${{ env.MAVEN_USER != '' }} + if: ${{ env.SNAPSHOT != 'true' }} diff --git a/README.MD b/README.MD index a8b4af3..83b24a2 100644 --- a/README.MD +++ b/README.MD @@ -1,6 +1,7 @@ # LWJGL3ify Brings LWJGL3 and modern Java versions to Minecraft 1.7.10. +Bundles [RetroFuturaBootstrap](https://github.com/GTNewHorizons/RetroFuturaBootstrap) as a flexible early load plugin system. # Usage @@ -26,9 +27,14 @@ You can also use Java 11 if you remove the `-Djava.security.manager=allow` argum ### MultiMC setup (GTNH and non-GTNH) For MultiMC, you need to manually put in extra java arguments, prismlauncher can load them from the patches json files automatically: ``` ---illegal-access=warn -Djava.security.manager=allow -Dfile.encoding=UTF-8 --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming --add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-modules jdk.dynalink --add-opens jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED --add-modules java.sql.rowset --add-opens java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED +-Dfile.encoding=UTF-8 -Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader -Djava.security.manager=allow --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming --add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-opens jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED --add-opens java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED ``` +### (Experimental) Relauncher installation + +To install in any client launcher, just drop the `lwjgl3ify-VERSION.jar` mod jar in the `mods/` directory and configure to launch with Java 8 as usual. +On startup, a window should appear prompting you to select a modern Java version to relaunch with, and the JVM settings for that Java installation. + ### Tweaking configs If you want to tweak your default window size, OpenGL context properties or other more advanced settings, check out the config file in `config/lwjgl3ify.cfg` after the first startup. @@ -38,18 +44,21 @@ Then, install the mod jar (and unimixins, hodgepodge and gtnhlib as needed) in ` **Thermos/Crucible/Hybrid servers are not supported!**. Lwjgl3ify also depends on Unimixins (), use at least version 0.1.7. Rename the forgePatches jar to just `lwjgl3ify-forgePatches.jar`. Create a file named `java9args.txt` with the contents of [the file in this repository](java9args.txt). -You can now launch the server with a command like the following, assuming the first java executable on your PATH is java 11/17/19: +You can now launch the server with a command like the following, assuming the first java executable on your PATH is java 11/17/newer: ``` -java -Xmx6G -Xms6G @java9args.txt nogui +java -Xmx6G -Xms6G @java9args.txt -jar lwjgl3ify-forgePatches.jar nogui ``` +# LiteLoader compatibility +If you install LiteLoader via MultiMC or a fork like PrismLauncher, make sure to move the "LiteLoader" entry above the "LWJGL3ify Launch Args" entry, otherwise the launch will fail. + # How does it work? There are a few components to enabling modern java and lwjgl usage on old minecraft versions, lwjgl3ify implements these for 1.7.10 specifically: - - A modified launcher profile (templates are in `prism-libraries`) to modify the library list loaded into the java classpath - to install LWJGL3, ASM 9.4, new Apache Commons and our forgePatches jar. + - A modified launcher profile (templates are in `prism-libraries`) to modify the library list loaded into the java classpath - to install LWJGL3, and our forgePatches jar that includes libraries such as ASM 9 or new Apache Commons. - A custom server launcher jar with the modified `Class-Path` META-INF manifest entry (integrated into our forgePatches jar) - - An updated launchwrapper with a java 9+-compatible classpath discovery mechanism at . This might be replaced in the future with a java instrumentation agent to transform those classes at runtime instead due to unclear licensing. + - A FOSS replacement for launchwrapper with a java 9+-compatible classpath discovery mechanism and wider-reaching transformer capabilities at . - A lot of add-opens flags for the JVM to allow reflection into JVM internals. Unfortunately a lot of libraries and mods depend on this to work, even weird ones like `java.text` or `nio` internals in case of Netty. - A partially auto-generated compatibility shim redirecting lwjgl2 api calls into the matching lwjgl3 calls (in `src/main/java/org/lwjglx`, `src/generated/java/org/lwjglx`), the generator is in `src/util/java` - Dummy `org/lwjgl/*` classes matching the classes removed from lwjgl3 (e.g. Display) for mods that rely on finding them under that location in the classpath - e.g. for mixin metadata @@ -81,7 +90,9 @@ There are a few components to enabling modern java and lwjgl usage on old minecr This mod is not enough to make modpacks work in Java 9+, mods had to be updated. Here's a potentially incomplete list of breaking changes that needed code changes in mods, or mixins to fix non-open-source mods: -#### System class loader is no longer a URLClassLoader +#### (NOT IN lwjgl3ify) System class loader is no longer a URLClassLoader + +Lwjgl3ify replaces the system classloader with its own URLClassLoader-derived class that supports addURL and getURLs via public method calls that are compatible with the old reflection access for them. To get the classpath, simply split `System.getProperty("java.class.path")` by `File.pathSeparator`. @@ -141,21 +152,12 @@ public static void setField(Field data, Object object, Object value) { } ``` +This is likely to be removed from a 2025 Java release though, I'll probably build a JNI-based alternative built into lwjgl3ify by then. + **Beware**, the Java JIT compiler will assume that final fields don't change value at runtime, so the value you write there using Unsafe might not actually be read back by some code. This can lead to inconsistent states, where some methods might see the old value while other ones will see the new value, especially if you change the value down a callchain that already read the value earlier. ### Development First, do `./gradlew build` and use the zip in `./build/distributions/lwjgl3ify-VERSION-multimc.zip` to install lwjgl3ify into a 1.7.10 forge instance in Prism. - -Then, for developing locally, in the `patches/me.eigenraven.lwjgl3ify.forgepatches.json` file replace: -```json -"url": "https://nexus.gtnewhorizons.com/repository/public/" -``` -with: -```json -"MMC-hint": "local" -``` -Inside the libraries array. - -Thanks to `MMC-hint` you can now put the locally built forgePatches jar into `instances/My Modpack/libraries/lwjgl3ify-VERSION-forgePatches.jar`. +Install the mod jar from `./build/libs/` as usual. diff --git a/addon.gradle b/addon.gradle deleted file mode 100644 index 42b1ea2..0000000 --- a/addon.gradle +++ /dev/null @@ -1,221 +0,0 @@ -import org.apache.tools.ant.filters.ReplaceTokens -import org.gradle.jvm.toolchain.internal.DefaultToolchainSpec - -def newJavaToolchainSpec = new DefaultToolchainSpec(objects) -newJavaToolchainSpec.vendor.set(JvmVendorSpec.AZUL) -newJavaToolchainSpec.languageVersion.set(JavaLanguageVersion.of(17)) - -def extraJavaArgs = [ - "--illegal-access=warn", - "-Djava.security.manager=allow", - "-Dfile.encoding=UTF-8", - "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", - "--add-opens", "java.base/java.net=ALL-UNNAMED", - "--add-opens", "java.base/java.nio=ALL-UNNAMED", - "--add-opens", "java.base/java.io=ALL-UNNAMED", - "--add-opens", "java.base/java.lang=ALL-UNNAMED", - "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", - "--add-opens", "java.base/java.text=ALL-UNNAMED", - "--add-opens", "java.base/java.util=ALL-UNNAMED", - "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED", - "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", - "--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming", - "--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED", - "--add-opens", "java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED", - "--add-modules", "jdk.dynalink", - "--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", - "--add-modules", "java.sql.rowset", - "--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED", -] - -SourceSet forgePatchesSet -SourceSet hotswapSet - -sourceSets { - create("util") { - java {} - } - forgePatchesSet = create("forgePatches") { - java { - compileClasspath += mcpTasks.patchedMcSources.output - compileClasspath += mcpTasks.patchedConfiguration - } - } - hotswapSet = create("hotswap") { - java {} - } - named("main").configure { - java { - srcDirs += ["src/generated/java"] - compileClasspath = forgePatchesSet.output + compileClasspath - runtimeClasspath = forgePatchesSet.output + runtimeClasspath - } - } -} - -configurations { - def forgePatchesEmbedded = create("forgePatchesEmbedded") { - canBeConsumed = false - canBeResolved = true - } - def versionJsonElements = create("versionJsonElements") { - canBeConsumed = false - canBeResolved = false - } - forgePatchesImplementation.extendsFrom(forgePatchesEmbedded) - patchedMinecraft.extendsFrom(forgePatchesEmbedded) -} - -tasks.named("shadowJar", Jar) { - from(hotswapSet.output) -} - -tasks.named("compileHotswapJava", JavaCompile).configure { - javaCompiler = javaToolchains.compilerFor(newJavaToolchainSpec) - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 -} - -repositories { - mavenCentral() -} - -dependencies { - utilImplementation("org.ow2.asm:asm:9.5") - utilImplementation("org.ow2.asm:asm-tree:9.5") - utilImplementation("org.apache.commons:commons-lang3:3.12.0") - utilImplementation("commons-io:commons-io:2.11.0") - utilImplementation("commons-collections:commons-collections:3.2.2") - utilImplementation("com.google.guava:guava:31.1-jre") - - hotswapCompileOnly("org.hotswapagent:hotswap-agent-core:1.4.1") - hotswapCompileOnly("net.minecraft:launchwrapper:1.15") -} - -def forgePatchesJar = tasks.register(forgePatchesSet.jarTaskName, Jar) { - from(forgePatchesSet.output) - // Bootleg shadow jar - configurations.forgePatchesEmbedded.resolve().each {dep -> - from(zipTree(dep)) { - filesMatching("META-INF/*") { fcd -> - fcd.name = "${dep.name}-${fcd.name}" - } - } - } - exclude("module-info.class") - exclude("log4j2.xml") - archiveClassifier.set("forgePatches") - manifest { - def libraryList = [ - "libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar", - "libraries/com/typesafe/config/1.2.1/config-1.2.1.jar", - "libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar", - "libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar", - "libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar", - "libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar", - "libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar", - "libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar", - "libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar", - "libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar", - "libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar", - "libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar", - "libraries/net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar", - "libraries/com/google/guava/guava/17.0/guava-17.0.jar", - "forge-1.7.10-10.13.4.1614-1.7.10-universal.jar", - "minecraft_server.1.7.10.jar" - ] - attributes( - "Class-Path": libraryList.join(" "), - "Main-Class": "cpw.mods.fml.relauncher.ServerLaunchWrapper" - ) - } -} - -def mmcInstanceFilesZip = tasks.register("mmcInstanceFiles", Zip) { - archiveClassifier.set("multimc") - from(new File(projectDir, "prism-libraries/")) - exclude("forgepatches-for-dev-work.json", "META-INF", "META-INF/**") - filesMatching(["mmc-pack.json", "patches/me.eigenraven.lwjgl3ify.forgepatches.json"]) { - expand "version": project.version, - "jvmArgs": extraJavaArgs.collect { '"' + it + '"' }.join(", ") - } -} - -def versionJsonPath = layout.buildDirectory.file('libs/version.json').get().asFile - -def versionJsonFile = tasks.register("versionJson") { - dependsOn("reobfJar") - it.inputs.file('launcher-metadata/version.json') - it.inputs.property('version', project.version) - it.inputs.property('jvmArgs', extraJavaArgs) - it.outputs.file(versionJsonPath) - doLast { - versionJsonPath.parentFile.mkdirs() - copy { - from 'launcher-metadata/version.json' - into versionJsonPath.parentFile - filter(ReplaceTokens, tokens: [version: project.version, - jvmArgs: extraJavaArgs.collect { '"' + it + '"' }.join(", "), - time : new Date().format("yyyy-MM-dd'T'HH:mm:ssXXX")]) - } - } -} - -def versionJsonArtifact = artifacts.add('versionJsonElements', versionJsonPath) { - type 'json' - classifier 'version' - builtBy versionJsonFile -} - -tasks.named("assemble").configure { - dependsOn(forgePatchesSet.jarTaskName) - dependsOn(mmcInstanceFilesZip) - dependsOn(versionJsonFile) -} - -tasks.register("runComparisonTool", JavaExec) { - classpath(sourceSets.util.runtimeClasspath) - dependsOn("jar") - mainClass.set("me.eigenraven.lwjgl3ify.ComparisonTool") - minHeapSize = "2G" - maxHeapSize = "2G" -} - -afterEvaluate { - publishing.publications.named("maven", MavenPublication) { - artifact forgePatchesJar - artifact mmcInstanceFilesZip - artifact versionJsonArtifact - } - - def lwjgl2Zips = configurations.named("lwjgl2Classpath").get().resolve().findAll {!it.name.contains("natives") && !it.path.contains("net.java.j")} - def lwjgl3Zips = configurations.named("lwjgl3Classpath").get().resolve().findAll {!it.name.contains("natives")} - def lwjgl2Args = lwjgl2Zips.collect {"--2:" + it} - def lwjgl3Args = lwjgl3Zips.collect {"--3:" + it} - def allArgs = lwjgl2Args + lwjgl3Args + ["--M:" + tasks.jar.archiveFile.get().asFile.path] - tasks.named("runComparisonTool", JavaExec).configure { - args(allArgs) - } -} - -def newJavaLauncher = javaToolchains.launcherFor(newJavaToolchainSpec) - -minecraft.extraRunJvmArguments.addAll(extraJavaArgs) - -for (runTask in ["runClient", "runServer"]) { - tasks.named(runTask, JavaExec).configure { - classpath = forgePatchesSet.output + classpath - javaLauncher.set(newJavaLauncher) - } -} - -for (runTask in ["runObfClient", "runObfServer"]) { - tasks.named(runTask, JavaExec).configure { - classpath = files(forgePatchesJar) + classpath - javaLauncher.set(newJavaLauncher) - } -} - -tasks.named("runObfServer", JavaExec) { - tweakClasses.set([]) -} diff --git a/addon.late.gradle b/addon.late.gradle deleted file mode 100644 index c593c13..0000000 --- a/addon.late.gradle +++ /dev/null @@ -1,4 +0,0 @@ - -// Regular runClient/runServer tasks run in Java 17 in this project. -tasks.named("runClient17") { enabled = false } -tasks.named("runServer17") { enabled = false } diff --git a/build.gradle b/build.gradle deleted file mode 100644 index e57a16f..0000000 --- a/build.gradle +++ /dev/null @@ -1,5 +0,0 @@ -//version: 1707058017 - -plugins { - id 'com.gtnewhorizons.gtnhconvention' -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2a50bd8 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,345 @@ +import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask +import com.gtnewhorizons.retrofuturagradle.util.Distribution +import org.apache.tools.ant.filters.ReplaceTokens +import java.time.OffsetDateTime +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter + +plugins { + id("com.gtnewhorizons.gtnhconvention") +} + +val taskGroup = "lwjgl3ify" + +val newJavaToolchainSpec: JavaToolchainSpec.() -> Unit = { + vendor = JvmVendorSpec.AZUL + languageVersion = JavaLanguageVersion.of(17) +} + +val addOpens = listOf( + "java.base/jdk.internal.loader=ALL-UNNAMED", + "java.base/java.net=ALL-UNNAMED", + "java.base/java.nio=ALL-UNNAMED", + "java.base/java.io=ALL-UNNAMED", + "java.base/java.lang=ALL-UNNAMED", + "java.base/java.lang.reflect=ALL-UNNAMED", + "java.base/java.text=ALL-UNNAMED", + "java.base/java.util=ALL-UNNAMED", + "java.base/jdk.internal.reflect=ALL-UNNAMED", + "java.base/sun.nio.ch=ALL-UNNAMED", + "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming", + "java.desktop/sun.awt=ALL-UNNAMED", + "java.desktop/sun.awt.image=ALL-UNNAMED", + "java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED", + "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", + "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED", +) + +val extraJavaArgs = mutableListOf( + "-Dfile.encoding=UTF-8", + "-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader", + "-Djava.security.manager=allow", +) +for (openSpec in addOpens) { + extraJavaArgs += listOf("--add-opens", openSpec) +} + +minecraft { + injectedTags.put("RECOMMENDED_JAVA_ARGS", extraJavaArgs.joinToString("\t")) +} + +lateinit var forgePatchesEmbedded: Configuration +lateinit var versionJsonElements: Configuration + +configurations { + forgePatchesEmbedded = create("forgePatchesEmbedded") { + isCanBeConsumed = false + isCanBeResolved = true + } + versionJsonElements = create("versionJsonElements") { + isCanBeConsumed = false + isCanBeResolved = false + } + patchedMinecraft { extendsFrom(forgePatchesEmbedded) } +} + +lateinit var hotswapSet: SourceSet +lateinit var relauncherStubSet: SourceSet + +sourceSets { + create("util") + hotswapSet = create("hotswap") + relauncherStubSet = create("relauncherStub") { + compileClasspath += forgePatchesEmbedded + configurations.shadowImplementation.get() + } + main { + java { + srcDir("src/generated/java") + } + } +} + +tasks.named(hotswapSet.compileJavaTaskName).configure { + javaCompiler = javaToolchains.compilerFor(newJavaToolchainSpec) + sourceCompatibility = JavaVersion.VERSION_17.majorVersion + targetCompatibility = JavaVersion.VERSION_17.majorVersion +} + +tasks.named(relauncherStubSet.compileJavaTaskName).configure { + javaCompiler = javaToolchains.compilerFor(newJavaToolchainSpec) + sourceCompatibility = JavaVersion.VERSION_17.majorVersion + targetCompatibility = JavaVersion.VERSION_17.majorVersion + options.release = 17 +} + +tasks.createMcLauncherFiles { + // Override main class + replacementTokens.put("@@BOUNCERCLIENT@@", "com.gtnewhorizons.retrofuturabootstrap.Main") + replacementTokens.put("@@BOUNCERSERVER@@", "com.gtnewhorizons.retrofuturabootstrap.Main") +} + +val forgePatchesJar = tasks.register("forgePatchesJar") { + dependsOn(tasks.compileJava) + group = taskGroup + description = "Packages the forgePatches jar" + isReproducibleFileOrder = true + isPreserveFileTimestamps = false + // Bootleg shadow jar + forgePatchesEmbedded.resolve().forEach { dep -> + from(zipTree(dep)) { + filesMatching("META-INF/*") { + this.name = "${dep.name}-${this.name}" + } + } + } + exclude("module-info.class") + exclude("META-INF/versions/9/module-info.class") + exclude("log4j2.xml") + from(sourceSets.main.map { it.output.classesDirs }) { + include("me/eigenraven/lwjgl3ify/rfb/entry/ServerMain.class") + } + from(relauncherStubSet.output) + archiveClassifier.set("forgePatches") + manifest { + val libraryList = listOf( + "libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar", + "libraries/com/typesafe/config/1.2.1/config-1.2.1.jar", + "libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar", + "libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar", + "libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar", + "libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar", + "libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar", + "libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar", + "libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar", + "libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar", + "libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar", + "libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar", + "libraries/net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar", + "libraries/com/google/guava/guava/17.0/guava-17.0.jar", + "forge-1.7.10-10.13.4.1614-1.7.10-universal.jar", + "minecraft_server.1.7.10.jar" + ) + attributes( + mapOf( + "Class-Path" to libraryList.joinToString(" "), + "Main-Class" to "me.eigenraven.lwjgl3ify.rfb.entry.ServerMain" + ) + ) + } +} + +val mmcInstanceFilesZip = tasks.register("mmcInstanceFiles") { + group = taskGroup + description = "Packages the MultiMC patches" + dependsOn(forgePatchesJar) + archiveClassifier.set("multimc") + from(project.file("prism-libraries/")) + from(forgePatchesJar) { + into("libraries/") + } + exclude("META-INF", "META-INF/**") + filesMatching(listOf("mmc-pack.json", "patches/me.eigenraven.lwjgl3ify.forgepatches.json", "patches/me.eigenraven.lwjgl3ify.launchargs.json")) { + expand( + mapOf( + "version" to project.version, + "jvmArgs" to extraJavaArgs.map { '"' + it + '"' }.joinToString(", ") + ) + ) + } +} + +val versionJsonPath = layout.buildDirectory.file("libs/version.json").get().asFile + +val versionJsonFile = tasks.register("versionJson") { + group = taskGroup + description = "Generates the vanilla launcher version.json file" + inputs.file("launcher-metadata/version.json") + inputs.property("version", project.version) + inputs.property("jvmArgs", extraJavaArgs) + outputs.file(versionJsonPath) + doLast { + versionJsonPath.parentFile.mkdirs() + copy { + from("launcher-metadata/version.json") + into(versionJsonPath.parentFile) + filter( + ReplaceTokens::class, "tokens" to mapOf( + "version" to project.version, + "jvmArgs" to extraJavaArgs.map { '"' + it + '"' }.joinToString(", "), + "time" to DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.now(ZoneOffset.UTC)) + ) + ) + } + } +} + +tasks.shadowJar { + dependsOn(forgePatchesJar, versionJsonFile) + from(hotswapSet.output) + // Use .zip because shadow unpacks .jar archives into the parent jar + from(forgePatchesJar) { + rename { "me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip" } + } + from(versionJsonFile) { + rename { "me/eigenraven/lwjgl3ify/relauncher/version.json" } + } +} + +val versionJsonArtifact = artifacts.add("versionJsonElements", versionJsonPath) { + type = "json" + classifier = "version" + builtBy(versionJsonFile) +} + +tasks.named("assemble").configure { + dependsOn(forgePatchesJar) + dependsOn(mmcInstanceFilesZip) + dependsOn(versionJsonFile) +} + +val runComparisonTool = tasks.register("runComparisonTool") { + group = taskGroup + description = "Runs the 2<->3 mapping generation" + classpath(sourceSets.named("util").map { it.runtimeClasspath }) + dependsOn("jar") + mainClass.set("me.eigenraven.lwjgl3ify.ComparisonTool") + minHeapSize = "2G" + maxHeapSize = "2G" +} + +tasks.processResources { + inputs.property("version", project.version.toString()) + filesMatching("META-INF/rfb-plugin/*") { + expand("version" to project.version.toString()) + } +} + +publishing.publications.named("maven") { + artifact(forgePatchesJar) + artifact(mmcInstanceFilesZip) + artifact(versionJsonArtifact) +} + +runComparisonTool.configure { + val lwjgl2Zips = configurations.lwjgl2Classpath.get().resolve() + .filter { !it.name.contains("natives") && !it.path.contains("net.java.j") } + val lwjgl3Zips = configurations.lwjgl3Classpath.get().resolve().filter { !it.name.contains("natives") } + val lwjgl2Args = lwjgl2Zips.map { "--2:" + it } + val lwjgl3Args = lwjgl3Zips.map { "--3:" + it } + val allArgs = lwjgl2Args + lwjgl3Args + listOf("--M:" + tasks.jar.get().archiveFile.get().asFile.path) + args(allArgs) +} + +val veryNewJavaToolchainSpec: JavaToolchainSpec.() -> Unit = { + vendor = JvmVendorSpec.AZUL + languageVersion = JavaLanguageVersion.of(21) +} + +val newJavaLauncher = javaToolchains.launcherFor(veryNewJavaToolchainSpec) + +for (jarTask in listOf("jar", "shadowJar", "forgePatchesJar")) { + tasks.named(jarTask).configure { + manifest { + attributes("Multi-Release" to true) + } + } +} + +for (runTask in listOf(tasks.runClient, tasks.runServer)) { + runTask.configure { + classpath = files(forgePatchesJar) + classpath + extraJvmArgs = extraJavaArgs + javaLauncher.set(newJavaLauncher) + } +} + +for (runTask in listOf(tasks.runObfClient, tasks.runObfServer)) { + runTask.configure { + classpath = files(forgePatchesJar) + classpath + extraJvmArgs = extraJavaArgs + javaLauncher.set(newJavaLauncher) + } +} + +val originalLaunchWrapperPath = project.layout.buildDirectory.file("launchwrapper-1.12.jar").get().asFile + +val runWithRelauncher = tasks.register("runClientWithRelauncher", Distribution.CLIENT, gradle) +runWithRelauncher.configure { + setup(project) + group = "lwjgl3ify" + description = "Runs the deobfuscated client while triggering the relauncher" + dependsOn( + sourceSets.mcLauncher.map { it.classesTaskName }, + tasks.downloadVanillaAssets, + tasks.packagePatchedMc, + tasks.reobfJar, + "jar" + ) + + username = minecraft.username + userUUID = minecraft.userUUID + lwjglVersion = 2 + + systemProperty("gradlestart.bouncerClient", "net.minecraft.launchwrapper.Launch") + + classpath(tasks.packageMcLauncher) + classpath(tasks.packagePatchedMc) + classpath(originalLaunchWrapperPath) + classpath(configurations.patchedMinecraft) + classpath(tasks.reobfJar) + classpath(configurations.runtimeClasspath) + mainClass = "GradleStart" + + doFirst { + download.run { + src("https://libraries.minecraft.net/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar") + dest(originalLaunchWrapperPath) + overwrite(false) + } + } +} + +tasks.runObfClient { + mainClass.set("com.gtnewhorizons.retrofuturabootstrap.Main") +} + +tasks.runObfServer { + tweakClasses.set(listOf()) +} + +// Regular runClient/runServer tasks run in Java 17 in this project. +tasks.runClient17 { enabled = false } +tasks.runClient21 { enabled = false } +tasks.runServer17 { enabled = false } +tasks.runServer21 { enabled = false } + +tasks.jar { + manifest.attributes.put("TweakClass", "me.eigenraven.lwjgl3ify.relauncher.Lwjgl3ifyRelauncherTweaker") +} + +tasks.shadowJar { + manifest.attributes.put("TweakClass", "me.eigenraven.lwjgl3ify.relauncher.Lwjgl3ifyRelauncherTweaker") +} + +apply(from = "repositories.gradle") +apply(from = "dependencies.gradle") diff --git a/dependencies.gradle b/dependencies.gradle index f45d5b6..f5873c2 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,53 +1,80 @@ minecraft { mainLwjglVersion = 3 - lwjgl3Version = "3.3.2" + lwjgl3Version = "3.3.3" } -def addGtForTesting = false -def addReikaModsForTesting = false +def addGtForTesting = Boolean.parseBoolean(project.getProperties().getOrDefault("withGregtech", "false").toString()) +def addReikaModsForTesting = Boolean.parseBoolean(project.getProperties().getOrDefault("withReikaMods", "false").toString()) -def asmVersion = '9.5' +def asmVersion = '9.6' +def rfbVersion = '1.0.0' +// 100% binary compatible, 1 minor source compatibility issue (removed a throws IOException clause) +def gsonVersion = '2.10.1' + +configurations.configureEach { + resolutionStrategy.dependencySubstitution { + substitute module('net.minecraft:launchwrapper') using module("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") because("LW replacement") + } +} dependencies { // Resolve newer versions of LaunchWrapper to allow java 9+ compat - vanilla_minecraft('net.minecraft:launchwrapper:1.17.4') { transitive = false } - forgePatchesEmbedded('net.minecraft:launchwrapper:1.17.4') { transitive = false } + vanilla_minecraft("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") { transitive = false } + forgePatchesEmbedded("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") { transitive = false } + vanilla_minecraft("com.google.code.gson:gson:${gsonVersion}") + forgePatchesEmbedded("com.google.code.gson:gson:${gsonVersion}") + + utilImplementation("org.ow2.asm:asm:${asmVersion}") + utilImplementation("org.ow2.asm:asm-tree:${asmVersion}") + utilImplementation("org.apache.commons:commons-lang3:3.14.0") + utilImplementation("commons-io:commons-io:2.11.0") + utilImplementation("commons-collections:commons-collections:3.2.2") + utilImplementation("com.google.guava:guava:31.1-jre") + + hotswapCompileOnly("org.hotswapagent:hotswap-agent-core:1.4.1") + hotswapCompileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") forgePatchesEmbedded("org.ow2.asm:asm:${asmVersion}") forgePatchesEmbedded("org.ow2.asm:asm-commons:${asmVersion}") forgePatchesEmbedded("org.ow2.asm:asm-tree:${asmVersion}") forgePatchesEmbedded("org.ow2.asm:asm-analysis:${asmVersion}") forgePatchesEmbedded("org.ow2.asm:asm-util:${asmVersion}") - forgePatchesEmbedded('org.ow2.asm:asm-deprecated:7.1') - forgePatchesEmbedded("org.apache.commons:commons-lang3:3.12.0") + forgePatchesEmbedded("org.apache.commons:commons-lang3:3.14.0") + forgePatchesEmbedded("org.apache.commons:commons-compress:1.26.0") + forgePatchesEmbedded("commons-io:commons-io:2.15.1") - forgePatchesEmbedded("org.apache.commons:commons-compress:1.21") + compileOnly("org.jetbrains:annotations:24.1.0") // Allow using Unsafe with newer javac versions compileOnly('me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0') + api("com.google.code.gson:gson:${gsonVersion}") + + compileOnly("com.mumfrey:liteloader:1.7.10_04:mcpnames") shadowImplementation("jakarta.xml.bind:jakarta.xml.bind-api:3.0.1") - shadowImplementation("jakarta.servlet:jakarta.servlet-api:6.0.0") + shadowImplementation("javax.servlet:javax.servlet-api:4.0.1") shadowImplementation("com.sun.xml.bind:jaxb-impl:3.0.2") - shadowImplementation("org.mozilla:rhino-engine:1.7.14") + shadowImplementation("org.openjdk.nashorn:nashorn-core:15.4") - runtimeOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev') + shadowImplementation("com.github.weisj:darklaf-core:3.0.2") + + runtimeOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.5.17-GTNH:dev') // runtimeOnlyNonPublishable('com.github.GTNewHorizons:inventory-tweaks:1.6.2:dev') if (addGtForTesting) { - runtimeOnlyNonPublishable('com.github.GTNewHorizons:GT5-Unofficial:5.09.45.38:dev') - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-312-GTNH:dev") + runtimeOnlyNonPublishable('com.github.GTNewHorizons:GT5-Unofficial:5.09.45.61:dev') + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-317-GTNH:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:Chisel:2.13.4-GTNH:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:ForestryMC:4.8.2:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:Railcraft:9.15.5:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:EnderIO:2.6.3:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:EnderIO:2.6.4:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:ProjectRed:4.9.3-GTNH:dev") { transitive = false } runtimeOnlyNonPublishable("com.github.GTNewHorizons:MrTJPCore:1.1.6:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:ForgeMultipart:1.4.7:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:ForgeRelocation:0.1.0:dev") reobfJarConfiguration group: 'curse.maven', name: 'cofh-core-69162', version: '2388750' runtimeOnlyNonPublishable("com.github.GTNewHorizons:AppleCore:3.3.0:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.4.9:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.4.20:dev") } if (addReikaModsForTesting) { // DragonAPI diff --git a/gradle.properties b/gradle.properties index b285c0c..89bb6db 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,6 +2,9 @@ # LOCAL to test local config updates. gtnh.settings.blowdryerTag = 0.2.2 +# Standard script loading, like addon.gradle. +gtnh.modules.standardScripts = false + # Human-readable mod name, available for mcmod.info population. modName = lwjgl3ify diff --git a/java9args.txt b/java9args.txt index d635434..9e18013 100644 --- a/java9args.txt +++ b/java9args.txt @@ -1,6 +1,6 @@ ---illegal-access=warn --Djava.security.manager=allow -Dfile.encoding=UTF-8 +-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader +-Djava.security.manager=allow --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens @@ -24,14 +24,12 @@ java.base/sun.nio.ch=ALL-UNNAMED --add-opens jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming --add-opens +java.desktop/sun.awt=ALL-UNNAMED +--add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-opens java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED ---add-modules jdk.dynalink --add-opens jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED ---add-modules java.sql.rowset --add-opens java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED --jar -lwjgl3ify-forgePatches.jar diff --git a/launcher-metadata/version.json b/launcher-metadata/version.json index 87abad2..3739a74 100644 --- a/launcher-metadata/version.json +++ b/launcher-metadata/version.json @@ -285,17 +285,6 @@ }, "name": "io.netty:netty-all:4.0.10.Final" }, - { - "downloads": { - "artifact": { - "path": "commons-io/commons-io/2.4/commons-io-2.4.jar", - "sha1": "b1b6ea3b7e4aa4f492509a4952029cd8e48019ad", - "size": 185140, - "url": "https://libraries.minecraft.net/commons-io/commons-io/2.4/commons-io-2.4.jar" - } - }, - "name": "commons-io:commons-io:2.4" - }, { "downloads": { "artifact": { @@ -332,13 +321,13 @@ { "downloads": { "artifact": { - "path": "com/google/code/gson/gson/2.2.4/gson-2.2.4.jar", - "sha1": "a60a5e993c98c864010053cb901b7eab25306568", - "size": 190432, - "url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.2.4/gson-2.2.4.jar" + "path": "com/google/code/gson/gson/2.10.1/gson-2.10.1.jar", + "sha1": "b3add478d4382b78ea20b1671390a858002feb6c", + "size": 283367, + "url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.10.1/gson-2.10.1.jar" } }, - "name": "com.google.code.gson:gson:2.2.4" + "name": "com.google.code.gson:gson:2.10.1" }, { "downloads": { @@ -1715,10 +1704,12 @@ "url": "https://maven.minecraftforge.net/" }, { - "name": "lzma:lzma:0.0.1" + "name": "lzma:lzma:0.0.1", + "url": "https://libraries.minecraft.net/" }, { - "name": "com.google.guava:guava:17.0" + "name": "com.google.guava:guava:17.0", + "url": "https://libraries.minecraft.net/" } ], "logging": { @@ -1733,7 +1724,7 @@ "type": "log4j2-xml" } }, - "mainClass": "net.minecraft.launchwrapper.Launch", + "mainClass": "com.gtnewhorizons.retrofuturabootstrap.Main", "minimumLauncherVersion": 21, "releaseTime": "@time@", "time": "@time@", diff --git a/prism-libraries/forgepatches-for-dev-work.json b/prism-libraries/forgepatches-for-dev-work.json deleted file mode 100644 index 974c0ae..0000000 --- a/prism-libraries/forgepatches-for-dev-work.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "formatVersion": 1, - "name": "Forge-J9-Patches", - "uid": "me.eigenraven.lwjgl3ify.forgepatches", - "version": "1", - "order": 3, - "+jvmArgs": [ - "--illegal-access=warn", - "-Djava.security.manager=allow", - "-Dfile.encoding=UTF-8", - "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", - "--add-opens", "java.base/java.net=ALL-UNNAMED", - "--add-opens", "java.base/java.nio=ALL-UNNAMED", - "--add-opens", "java.base/java.io=ALL-UNNAMED", - "--add-opens", "java.base/java.lang=ALL-UNNAMED", - "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", - "--add-opens", "java.base/java.text=ALL-UNNAMED", - "--add-opens", "java.base/java.util=ALL-UNNAMED", - "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED", - "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", - "--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming", - "--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED", - "--add-modules", "jdk.dynalink", - "--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", - "--add-modules", "java.sql.rowset", - "--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED" - ], - "libraries": [ - { - "name": "com.gtnewhorizons:lwjgl3ify:1.1.36:forgePatches", - "MMC-hint": "local" - } - ] -} diff --git a/prism-libraries/mmc-pack.json b/prism-libraries/mmc-pack.json index 516e05d..c9e689c 100644 --- a/prism-libraries/mmc-pack.json +++ b/prism-libraries/mmc-pack.json @@ -6,13 +6,13 @@ "cachedVolatile": true, "dependencyOnly": true, "uid": "org.lwjgl3", - "version": "3.3.1" + "version": "3.3.2" }, { "cachedName": "Minecraft with LWJGL3", "cachedRequires": [ { - "suggests": "3.3.1", + "suggests": "3.3.2", "uid": "org.lwjgl3" } ], @@ -22,7 +22,7 @@ "version": "1.7.10" }, { - "cachedName": "Forge-lwjgl3ify-Patches", + "cachedName": "LWJGL3ify Early Classpath", "cachedVersion": "${version}", "uid": "me.eigenraven.lwjgl3ify.forgepatches" }, @@ -37,6 +37,11 @@ "cachedVersion": "10.13.4.1614", "uid": "net.minecraftforge", "version": "10.13.4.1614" + }, + { + "cachedName": "LWJGL3ify launch args", + "cachedVersion": "${version}", + "uid": "me.eigenraven.lwjgl3ify.launchargs" } ], "formatVersion": 1 diff --git a/prism-libraries/patches/me.eigenraven.lwjgl3ify.forgepatches.json b/prism-libraries/patches/me.eigenraven.lwjgl3ify.forgepatches.json index dea08b0..a3ed4c2 100644 --- a/prism-libraries/patches/me.eigenraven.lwjgl3ify.forgepatches.json +++ b/prism-libraries/patches/me.eigenraven.lwjgl3ify.forgepatches.json @@ -1,6 +1,6 @@ { "formatVersion": 1, - "name": "Forge-lwjgl3ify-Patches", + "name": "LWJGL3ify Early Classpath", "uid": "me.eigenraven.lwjgl3ify.forgepatches", "version": "${version}", "order": 3, @@ -10,7 +10,7 @@ "libraries": [ { "name": "com.github.GTNewHorizons:lwjgl3ify:${version}:forgePatches", - "url": "https://nexus.gtnewhorizons.com/repository/public/" + "MMC-hint": "local" } ] } diff --git a/prism-libraries/patches/me.eigenraven.lwjgl3ify.launchargs.json b/prism-libraries/patches/me.eigenraven.lwjgl3ify.launchargs.json new file mode 100644 index 0000000..0bab91e --- /dev/null +++ b/prism-libraries/patches/me.eigenraven.lwjgl3ify.launchargs.json @@ -0,0 +1,8 @@ +{ + "formatVersion": 1, + "name": "LWJGL3ify launch args", + "uid": "me.eigenraven.lwjgl3ify.launchargs", + "version": "${version}", + "order": 100, + "mainClass": "com.gtnewhorizons.retrofuturabootstrap.Main" +} diff --git a/prism-libraries/patches/net.minecraft.json b/prism-libraries/patches/net.minecraft.json index afbfe0c..5940361 100644 --- a/prism-libraries/patches/net.minecraft.json +++ b/prism-libraries/patches/net.minecraft.json @@ -35,16 +35,6 @@ }, "name": "com.mojang:realms:1.3.5" }, - { - "downloads": { - "artifact": { - "sha1": "a698750c16740fd5b3871425f4cb3bbaa87f529d", - "size": 365552, - "url": "https://libraries.minecraft.net/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar" - } - }, - "name": "org.apache.commons:commons-compress:1.8.1" - }, { "downloads": { "artifact": { @@ -185,16 +175,6 @@ }, "name": "com.google.guava:guava:15.0" }, - { - "downloads": { - "artifact": { - "sha1": "b1b6ea3b7e4aa4f492509a4952029cd8e48019ad", - "size": 185140, - "url": "https://libraries.minecraft.net/commons-io/commons-io/2.4/commons-io-2.4.jar" - } - }, - "name": "commons-io:commons-io:2.4" - }, { "downloads": { "artifact": { @@ -208,12 +188,12 @@ { "downloads": { "artifact": { - "sha1": "a60a5e993c98c864010053cb901b7eab25306568", - "size": 190432, - "url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.2.4/gson-2.2.4.jar" + "sha1": "b3add478d4382b78ea20b1671390a858002feb6c", + "size": 283367, + "url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.10.1/gson-2.10.1.jar" } }, - "name": "com.google.code.gson:gson:2.2.4" + "name": "com.google.code.gson:gson:2.10.1" }, { "downloads": { @@ -419,7 +399,7 @@ "releaseTime": "2014-05-14T17:29:23+00:00", "requires": [ { - "suggests": "3.3.1", + "suggests": "3.3.2", "uid": "org.lwjgl3" } ], diff --git a/prism-libraries/patches/net.minecraftforge.json b/prism-libraries/patches/net.minecraftforge.json index adfd81b..95f10a5 100644 --- a/prism-libraries/patches/net.minecraftforge.json +++ b/prism-libraries/patches/net.minecraftforge.json @@ -59,7 +59,7 @@ "name": "com.google.guava:guava:17.0" } ], - "mainClass": "net.minecraft.launchwrapper.Launch", + "mainClass": "com.gtnewhorizons.retrofuturabootstrap.Main", "name": "Forge-LWJGL3", "order": 5, "releaseTime": "2015-12-10T00:05:37-05:00", diff --git a/repositories.gradle b/repositories.gradle index d0c6f8b..81e9fe1 100644 --- a/repositories.gradle +++ b/repositories.gradle @@ -1,8 +1,13 @@ repositories { - // LWJGL3 Snapshots - maven { - name 'sonatype' - url 'https://oss.sonatype.org/content/repositories/snapshots/' + ivy { + name "LiteLoader" + artifactPattern "https://dl.liteloader.com/versions/com/mumfrey/[module]/1.7.10/[module]-[revision](-[classifier]).[ext]" + metadataSources { + artifact() + } + content { + includeGroup("com.mumfrey") + } } } diff --git a/settings.gradle b/settings.gradle index 46765c9..37dbdb1 100644 --- a/settings.gradle +++ b/settings.gradle @@ -17,9 +17,7 @@ pluginManagement { } plugins { - id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.11' + id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.17' } - - rootProject.name = "lwjgl3ify" diff --git a/src/forgePatches/java/cpw/mods/fml/common/TracingPrintStream.java b/src/forgePatches/java/cpw/mods/fml/common/TracingPrintStream.java deleted file mode 100644 index d45f0bd..0000000 --- a/src/forgePatches/java/cpw/mods/fml/common/TracingPrintStream.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Forge Mod Loader Copyright (c) 2012-2013 cpw. All rights reserved. This program and the accompanying materials are - * made available under the terms of the GNU Lesser Public License v2.1 which accompanies this distribution, and is - * available at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - */ - -package cpw.mods.fml.common; - -import java.io.PrintStream; - -import org.apache.logging.log4j.Logger; - -/** - * PrintStream which redirects it's output to a given logger. - * - * @author Arkan - */ -public class TracingPrintStream extends PrintStream { - - private Logger logger; - private int BASE_DEPTH = 3; - - public TracingPrintStream(Logger logger, PrintStream original) { - super(original); - this.logger = logger; - } - - @Override - public void println(Object o) { - logger.info(getPrefix() + o); - } - - @Override - public void println(String s) { - logger.info(getPrefix() + s); - } - - private String getPrefix() { - StackTraceElement[] elems = Thread.currentThread() - .getStackTrace(); - StackTraceElement elem = elems[BASE_DEPTH]; // The caller is always at BASE_DEPTH, including this call. - if (elem.getClassName() - .startsWith("kotlin.io.")) { - elem = elems[BASE_DEPTH + 2]; // Kotlins IoPackage masks origins 2 deeper in the stack. - } - return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: "; - } - - @Override - public void close() { - // no-op - println("Something tried to close the main output stream"); - new Throwable().printStackTrace(); - } -} diff --git a/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/EventSubscriptionTransformer.java b/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/EventSubscriptionTransformer.java deleted file mode 100644 index 71136a0..0000000 --- a/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/EventSubscriptionTransformer.java +++ /dev/null @@ -1,200 +0,0 @@ -package cpw.mods.fml.common.asm.transformers; - -import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; -import static org.objectweb.asm.Opcodes.ACC_PRIVATE; -import static org.objectweb.asm.Opcodes.ACC_PROTECTED; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_STATIC; -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.DUP; -import static org.objectweb.asm.Opcodes.F_SAME; -import static org.objectweb.asm.Opcodes.GETSTATIC; -import static org.objectweb.asm.Opcodes.ICONST_1; -import static org.objectweb.asm.Opcodes.IFNULL; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.IRETURN; -import static org.objectweb.asm.Opcodes.NEW; -import static org.objectweb.asm.Opcodes.PUTSTATIC; -import static org.objectweb.asm.Opcodes.RETURN; -import static org.objectweb.asm.Type.BOOLEAN_TYPE; -import static org.objectweb.asm.Type.VOID_TYPE; -import static org.objectweb.asm.Type.getMethodDescriptor; - -import java.util.List; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.FieldNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TypeInsnNode; -import org.objectweb.asm.tree.VarInsnNode; - -import cpw.mods.fml.common.eventhandler.Event; - -public class EventSubscriptionTransformer implements IClassTransformer { - - public EventSubscriptionTransformer() {} - - @Override - public byte[] transform(String name, String transformedName, byte[] bytes) { - if (bytes == null || name.equals("cpw.mods.fml.common.eventhandler.Event") - || name.startsWith("net.minecraft.") - || name.indexOf('.') == -1) { - return bytes; - } - ClassReader cr = new ClassReader(bytes); - ClassNode classNode = new ClassNode(); - cr.accept(classNode, 0); - - try { - if (buildEvents(classNode)) { - ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); - classNode.accept(cw); - return cw.toByteArray(); - } - return bytes; - } catch (ClassNotFoundException ex) { - // Discard silently- it's just noise - } catch (Exception e) { - e.printStackTrace(); - } - - return bytes; - } - - private boolean buildEvents(ClassNode classNode) throws Exception { - // Yes, this recursively loads classes until we get this base class. THIS IS NOT A ISSUE. Coremods should handle - // re-entry just fine. - // If they do not this a COREMOD issue NOT a Forge/LaunchWrapper issue. - Class parent = this.getClass() - .getClassLoader() - .loadClass(classNode.superName.replace('/', '.')); - if (!Event.class.isAssignableFrom(parent)) { - return false; - } - - // Class listenerListClazz = Class.forName("cpw.mods.fml.common.eventhandler.ListenerList", false, - // getClass().getClassLoader()); - Type tList = Type.getType("Lcpw/mods/fml/common/eventhandler/ListenerList;"); - - boolean edited = false; - boolean hasSetup = false; - boolean hasGetListenerList = false; - boolean hasDefaultCtr = false; - boolean hasCancelable = false; - boolean hasResult = false; - String voidDesc = Type.getMethodDescriptor(VOID_TYPE); - String boolDesc = Type.getMethodDescriptor(BOOLEAN_TYPE); - String listDesc = tList.getDescriptor(); - String listDescM = Type.getMethodDescriptor(tList); - - for (MethodNode method : (List) classNode.methods) { - if (method.name.equals("setup") && method.desc.equals(voidDesc) - && (method.access & ACC_PROTECTED) == ACC_PROTECTED) hasSetup = true; - if ((method.access & ACC_PUBLIC) == ACC_PUBLIC) { - if (method.name.equals("getListenerList") && method.desc.equals(listDescM)) hasGetListenerList = true; - if (method.name.equals("isCancelable") && method.desc.equals(boolDesc)) hasCancelable = true; - if (method.name.equals("hasResult") && method.desc.equals(boolDesc)) hasResult = true; - } - if (method.name.equals("") && method.desc.equals(voidDesc)) hasDefaultCtr = true; - } - - if (classNode.visibleAnnotations != null) { - for (AnnotationNode node : classNode.visibleAnnotations) { - if (!hasResult && node.desc.replace('$', '/') - .equals("Lcpw/mods/fml/common/eventhandler/Event/HasResult;")) { - /* - * Add: public boolean hasResult() { return true; } - */ - MethodNode method = new MethodNode(ACC_PUBLIC, "hasResult", boolDesc, null, null); - method.instructions.add(new InsnNode(ICONST_1)); - method.instructions.add(new InsnNode(IRETURN)); - classNode.methods.add(method); - edited = true; - } else if (!hasCancelable && node.desc.equals("Lcpw/mods/fml/common/eventhandler/Cancelable;")) { - /* - * Add: public boolean isCancelable() { return true; } - */ - MethodNode method = new MethodNode(ACC_PUBLIC, "isCancelable", boolDesc, null, null); - method.instructions.add(new InsnNode(ICONST_1)); - method.instructions.add(new InsnNode(IRETURN)); - classNode.methods.add(method); - edited = true; - } - } - } - - if (hasSetup) { - if (!hasGetListenerList) throw new RuntimeException( - "Event class defines setup() but does not define getListenerList! " + classNode.name); - else return edited; - } - - Type tSuper = Type.getObjectType(classNode.superName); - - // Add private static ListenerList LISTENER_LIST - classNode.fields.add(new FieldNode(ACC_PRIVATE | ACC_STATIC, "LISTENER_LIST", listDesc, null, null)); - - /* - * Add: public () { super(); } - */ - if (!hasDefaultCtr) { - MethodNode method = new MethodNode(ACC_PUBLIC, "", voidDesc, null, null); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions - .add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "", voidDesc, false)); - method.instructions.add(new InsnNode(RETURN)); - classNode.methods.add(method); - } - - /* - * Add: protected void setup() { super.setup(); if (LISTENER_LIST != NULL) { return; } LISTENER_LIST = new - * ListenerList(super.getListenerList()); } - */ - MethodNode method = new MethodNode(ACC_PROTECTED, "setup", voidDesc, null, null); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "setup", voidDesc, false)); - method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - LabelNode initLisitener = new LabelNode(); - method.instructions.add(new JumpInsnNode(IFNULL, initLisitener)); - method.instructions.add(new InsnNode(RETURN)); - method.instructions.add(initLisitener); - method.instructions.add(new FrameNode(F_SAME, 0, null, 0, null)); - method.instructions.add(new TypeInsnNode(NEW, tList.getInternalName())); - method.instructions.add(new InsnNode(DUP)); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions - .add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "getListenerList", listDescM, false)); - method.instructions.add( - new MethodInsnNode( - INVOKESPECIAL, - tList.getInternalName(), - "", - getMethodDescriptor(VOID_TYPE, tList), - false)); - method.instructions.add(new FieldInsnNode(PUTSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - method.instructions.add(new InsnNode(RETURN)); - classNode.methods.add(method); - - /* - * Add: public ListenerList getListenerList() { return this.LISTENER_LIST; } - */ - method = new MethodNode(ACC_PUBLIC, "getListenerList", listDescM, null, null); - method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - method.instructions.add(new InsnNode(ARETURN)); - classNode.methods.add(method); - return true; - } -} diff --git a/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/TerminalTransformer.java b/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/TerminalTransformer.java deleted file mode 100644 index 4ee3049..0000000 --- a/src/forgePatches/java/cpw/mods/fml/common/asm/transformers/TerminalTransformer.java +++ /dev/null @@ -1,149 +0,0 @@ -package cpw.mods.fml.common.asm.transformers; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import cpw.mods.fml.relauncher.FMLRelaunchLog; -import cpw.mods.fml.relauncher.FMLSecurityManager.ExitTrappedException; - -public class TerminalTransformer implements IClassTransformer { - - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { - if (basicClass == null) return null; - ClassReader reader = new ClassReader(basicClass); - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - - ClassVisitor visitor = writer; - visitor = new ExitVisitor(visitor); - - reader.accept(visitor, 0); - return writer.toByteArray(); - } - - public static class ExitVisitor extends ClassVisitor { - - private String clsName = null; - private static final String callbackOwner = org.objectweb.asm.Type.getInternalName(ExitVisitor.class); - - private ExitVisitor(ClassVisitor cv) { - // LWJGL3ify patch: ASM5->ASM9 - super(Opcodes.ASM9, cv); - } - - @Override - public void visit(int version, int access, String name, String signature, String superName, - String[] interfaces) { - super.visit(version, access, name, signature, superName, interfaces); - this.clsName = name; - } - - @Override - public MethodVisitor visitMethod(int mAccess, final String mName, final String mDesc, String mSignature, - String[] mExceptions) { - final boolean warn = !(clsName.equals("net/minecraft/client/Minecraft") - || clsName.equals("net/minecraft/server/dedicated/DedicatedServer") - || clsName.equals("cpw/mods/fml/common/FMLCommonHandler") - || clsName.startsWith("com/jcraft/jogg/") - || clsName.startsWith("scala/sys/")); - - // LWJGL3ify patch: ASM5->ASM9 - return new MethodVisitor(Opcodes.ASM9, super.visitMethod(mAccess, mName, mDesc, mSignature, mExceptions)) { - - @Override - public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean isIntf) { - if (opcode == Opcodes.INVOKESTATIC && owner.equals("java/lang/System") - && name.equals("exit") - && desc.equals("(I)V")) { - if (warn) { - FMLRelaunchLog.warning("============================================================="); - FMLRelaunchLog.warning( - "MOD HAS DIRECT REFERENCE System.exit() THIS IS NOT ALLOWED REROUTING TO FML!"); - FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc); - FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead"); - FMLRelaunchLog.warning("============================================================="); - } - owner = ExitVisitor.callbackOwner; - name = "systemExitCalled"; - } else if (opcode == Opcodes.INVOKEVIRTUAL && owner.equals("java/lang/Runtime") - && name.equals("exit") - && desc.equals("(I)V")) { - if (warn) { - FMLRelaunchLog.warning("============================================================="); - FMLRelaunchLog.warning( - "MOD HAS DIRECT REFERENCE Runtime.exit() THIS IS NOT ALLOWED REROUTING TO FML!"); - FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc); - FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead"); - FMLRelaunchLog.warning("============================================================="); - } - opcode = Opcodes.INVOKESTATIC; - owner = ExitVisitor.callbackOwner; - name = "runtimeExitCalled"; - desc = "(Ljava/lang/Runtime;I)V"; - } else if (opcode == Opcodes.INVOKEVIRTUAL && owner.equals("java/lang/Runtime") - && name.equals("halt") - && desc.equals("(I)V")) { - if (warn) { - FMLRelaunchLog - .warning("============================================================="); - FMLRelaunchLog.warning( - "MOD HAS DIRECT REFERENCE Runtime.halt() THIS IS NOT ALLOWED REROUTING TO FML!"); - FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc); - FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead"); - FMLRelaunchLog - .warning("============================================================="); - } - opcode = Opcodes.INVOKESTATIC; - owner = ExitVisitor.callbackOwner; - name = "runtimeHaltCalled"; - desc = "(Ljava/lang/Runtime;I)V"; - } - - super.visitMethodInsn(opcode, owner, name, desc, isIntf); - } - }; - } - - // Intercept System.exit, and check if the caller is allowed to use it, if not wrap it in a ExitTrappedException - public static void systemExitCalled(int status) { - ExitVisitor.checkAccess(); - System.exit(status); - } - - // Intercept Runtime.getRuntime().exit, and check if the caller is allowed to use it, if not wrap it in a - // ExitTrappedException - public static void runtimeExitCalled(Runtime runtime, int status) { - ExitVisitor.checkAccess(); - runtime.exit(status); - } - - // Intercept Runtime.getRuntime().halt, and check if the caller is allowed to use it, if not wrap it in a - // ExitTrappedException - public static void runtimeHaltCalled(Runtime runtime, int status) { - ExitVisitor.checkAccess(); - runtime.halt(status); - } - - private static void checkAccess() { - StackTraceElement[] cause = Thread.currentThread() - .getStackTrace(); - - String callingClass = cause.length > 2 ? cause[3].getClassName() : "none"; - String callingParent = cause.length > 3 ? cause[4].getClassName() : "none"; - // FML is allowed to call system exit and the Minecraft applet (from the quit button), and the dedicated - // server (from itself) - if (!(callingClass.startsWith("cpw.mods.fml.") - || ("net.minecraft.client.Minecraft".equals(callingClass) - && "net.minecraft.client.Minecraft".equals(callingParent)) - || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) - && "net.minecraft.server.MinecraftServer".equals(callingParent)))) { - throw new ExitTrappedException(); - } - } - } -} diff --git a/src/forgePatches/java/cpw/mods/fml/common/patcher/ClassPatchManager.java b/src/forgePatches/java/cpw/mods/fml/common/patcher/ClassPatchManager.java deleted file mode 100644 index da42e63..0000000 --- a/src/forgePatches/java/cpw/mods/fml/common/patcher/ClassPatchManager.java +++ /dev/null @@ -1,222 +0,0 @@ -package cpw.mods.fml.common.patcher; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import java.util.jar.JarOutputStream; -import java.util.regex.Pattern; - -import net.minecraft.launchwrapper.LaunchClassLoader; - -import org.apache.commons.compress.harmony.unpack200.Pack200UnpackerAdapter; -import org.apache.logging.log4j.Level; - -import com.google.common.base.Joiner; -import com.google.common.base.Throwables; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Maps; -import com.google.common.hash.Hashing; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteStreams; -import com.google.common.io.Files; - -import LZMA.LzmaInputStream; -import cpw.mods.fml.relauncher.FMLRelaunchLog; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.repackage.com.nothome.delta.GDiffPatcher; - -public class ClassPatchManager { - - public static final ClassPatchManager INSTANCE = new ClassPatchManager(); - - public static final boolean dumpPatched = Boolean - .parseBoolean(System.getProperty("fml.dumpPatchedClasses", "false")); - public static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("fml.debugClassPatchManager", "false")); - - private GDiffPatcher patcher = new GDiffPatcher(); - private ListMultimap patches; - - private Map patchedClasses = Maps.newHashMap(); - private File tempDir; - - private ClassPatchManager() { - if (dumpPatched) { - tempDir = Files.createTempDir(); - FMLRelaunchLog.info("Dumping patched classes to %s", tempDir.getAbsolutePath()); - } - } - - public byte[] getPatchedResource(String name, String mappedName, LaunchClassLoader loader) throws IOException { - byte[] rawClassBytes = loader.getClassBytes(name); - return applyPatch(name, mappedName, rawClassBytes); - } - - public byte[] applyPatch(String name, String mappedName, byte[] inputData) { - if (patches == null) { - return inputData; - } - if (patchedClasses.containsKey(name)) { - return patchedClasses.get(name); - } - List list = patches.get(name); - if (list.isEmpty()) { - return inputData; - } - boolean ignoredError = false; - if (DEBUG) FMLRelaunchLog.fine( - "Runtime patching class %s (input size %d), found %d patch%s", - mappedName, - (inputData == null ? 0 : inputData.length), - list.size(), - list.size() != 1 ? "es" : ""); - for (ClassPatch patch : list) { - if (!patch.targetClassName.equals(mappedName) && !patch.sourceClassName.equals(name)) { - FMLRelaunchLog.warning("Binary patch found %s for wrong class %s", patch.targetClassName, mappedName); - } - if (!patch.existsAtTarget && (inputData == null || inputData.length == 0)) { - inputData = new byte[0]; - } else if (!patch.existsAtTarget) { - FMLRelaunchLog.warning( - "Patcher expecting empty class data file for %s, but received non-empty", - patch.targetClassName); - } else { - int inputChecksum = Hashing.adler32() - .hashBytes(inputData) - .asInt(); - if (patch.inputChecksum != inputChecksum) { - FMLRelaunchLog.severe( - "There is a binary discrepency between the expected input class %s (%s) and the actual class. Checksum on disk is %x, in patch %x. Things are probably about to go very wrong. Did you put something into the jar file?", - mappedName, - name, - inputChecksum, - patch.inputChecksum); - if (!Boolean.parseBoolean(System.getProperty("fml.ignorePatchDiscrepancies", "false"))) { - FMLRelaunchLog.severe( - "The game is going to exit, because this is a critical error, and it is very improbable that the modded game will work, please obtain clean jar files."); - System.exit(1); - } else { - FMLRelaunchLog.severe( - "FML is going to ignore this error, note that the patch will not be applied, and there is likely to be a malfunctioning behaviour, including not running at all"); - ignoredError = true; - continue; - } - } - } - synchronized (patcher) { - try { - inputData = patcher.patch(inputData, patch.patch); - } catch (IOException e) { - FMLRelaunchLog.log(Level.ERROR, e, "Encountered problem runtime patching class %s", name); - e.printStackTrace(); - continue; - } - } - } - if (!ignoredError && DEBUG) { - FMLRelaunchLog - .fine("Successfully applied runtime patches for %s (new size %d)", mappedName, inputData.length); - } - if (dumpPatched) { - try { - Files.write(inputData, new File(tempDir, mappedName)); - } catch (IOException e) { - FMLRelaunchLog.log(Level.ERROR, e, "Failed to write %s to %s", mappedName, tempDir.getAbsolutePath()); - e.printStackTrace(); - } - } - patchedClasses.put(name, inputData); - return inputData; - } - - public void setup(Side side) { - Pattern binpatchMatcher = Pattern.compile( - String.format( - "binpatch/%s/.*.binpatch", - side.toString() - .toLowerCase(Locale.ENGLISH))); - JarInputStream jis; - try { - InputStream binpatchesCompressed = getClass().getResourceAsStream("/binpatches.pack.lzma"); - if (binpatchesCompressed == null) { - FMLRelaunchLog.log( - Level.ERROR, - "The binary patch set is missing. Either you are in a development environment, or things are not going to work!"); - return; - } - LzmaInputStream binpatchesDecompressedLzma = new LzmaInputStream(binpatchesCompressed); - // The Apache pack200 stream chokes on a lzmainputstream for some reason - byte[] decompressed = ByteStreams.toByteArray(binpatchesDecompressedLzma); - binpatchesDecompressedLzma.close(); - ByteArrayInputStream binpatchesDecompressed = new ByteArrayInputStream(decompressed); - ByteArrayOutputStream jarBytes = new ByteArrayOutputStream(); - JarOutputStream jos = new JarOutputStream(jarBytes); - new Pack200UnpackerAdapter().unpack(binpatchesDecompressed, jos); - jis = new JarInputStream(new ByteArrayInputStream(jarBytes.toByteArray())); - } catch (Exception e) { - FMLRelaunchLog.log(Level.ERROR, e, "Error occurred reading binary patches. Expect severe problems!"); - e.printStackTrace(); - throw Throwables.propagate(e); - } - - patches = ArrayListMultimap.create(); - - do { - try { - JarEntry entry = jis.getNextJarEntry(); - if (entry == null) { - break; - } - if (binpatchMatcher.matcher(entry.getName()) - .matches()) { - ClassPatch cp = readPatch(entry, jis); - if (cp != null) { - patches.put(cp.sourceClassName, cp); - } - } else { - jis.closeEntry(); - } - } catch (IOException e) {} - } while (true); - FMLRelaunchLog.fine("Read %d binary patches", patches.size()); - if (DEBUG) FMLRelaunchLog.fine( - "Patch list :\n\t%s", - Joiner.on("\t\n") - .join( - patches.asMap() - .entrySet())); - patchedClasses.clear(); - } - - private ClassPatch readPatch(JarEntry patchEntry, JarInputStream jis) { - if (DEBUG) FMLRelaunchLog.finer("Reading patch data from %s", patchEntry.getName()); - ByteArrayDataInput input; - try { - input = ByteStreams.newDataInput(ByteStreams.toByteArray(jis)); - } catch (IOException e) { - FMLRelaunchLog.log(Level.WARN, e, "Unable to read binpatch file %s - ignoring", patchEntry.getName()); - e.printStackTrace(); - return null; - } - String name = input.readUTF(); - String sourceClassName = input.readUTF(); - String targetClassName = input.readUTF(); - boolean exists = input.readBoolean(); - int inputChecksum = 0; - if (exists) { - inputChecksum = input.readInt(); - } - int patchLength = input.readInt(); - byte[] patchBytes = new byte[patchLength]; - input.readFully(patchBytes); - - return new ClassPatch(name, sourceClassName, targetClassName, exists, inputChecksum, patchBytes); - } -} diff --git a/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java b/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java deleted file mode 100644 index f5a2874..0000000 --- a/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java +++ /dev/null @@ -1,688 +0,0 @@ -/* - * Forge Mod Loader Copyright (c) 2012-2013 cpw. All rights reserved. This program and the accompanying materials are - * made available under the terms of the GNU Lesser Public License v2.1 which accompanies this distribution, and is - * available at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Contributors: cpw - implementation eigenraven - - * java 9 compatibility - */ - -package cpw.mods.fml.relauncher; - -import java.io.File; -import java.io.FileFilter; -import java.io.FilenameFilter; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.jar.Attributes; -import java.util.jar.JarFile; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; - -import org.apache.logging.log4j.Level; - -import com.google.common.base.Strings; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.ObjectArrays; -import com.google.common.primitives.Ints; - -import cpw.mods.fml.common.FMLLog; -import cpw.mods.fml.common.asm.transformers.ModAccessTransformer; -import cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker; -import cpw.mods.fml.common.launcher.FMLTweaker; -import cpw.mods.fml.common.toposort.TopologicalSort; -import cpw.mods.fml.relauncher.IFMLLoadingPlugin.DependsOn; -import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; -import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name; -import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; -import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions; - -public class CoreModManager { - - private static final Attributes.Name COREMODCONTAINSFMLMOD = new Attributes.Name("FMLCorePluginContainsFMLMod"); - private static final Attributes.Name MODTYPE = new Attributes.Name("ModType"); - private static final Attributes.Name MODSIDE = new Attributes.Name("ModSide"); - private static String[] rootPlugins = { "cpw.mods.fml.relauncher.FMLCorePlugin", - "net.minecraftforge.classloading.FMLForgePlugin" }; - private static List loadedCoremods = Lists.newArrayList(); - private static List loadPlugins; - private static boolean deobfuscatedEnvironment; - private static FMLTweaker tweaker; - private static File mcDir; - private static List reparsedCoremods = Lists.newArrayList(); - private static List accessTransformers = Lists.newArrayList(); - - private static class FMLPluginWrapper implements ITweaker { - - public final String name; - public final IFMLLoadingPlugin coreModInstance; - public final List predepends; - public final File location; - public final int sortIndex; - - public FMLPluginWrapper(String name, IFMLLoadingPlugin coreModInstance, File location, int sortIndex, - String... predepends) { - super(); - this.name = name; - this.coreModInstance = coreModInstance; - this.location = location; - this.sortIndex = sortIndex; - this.predepends = Lists.newArrayList(predepends); - } - - @Override - public String toString() { - return String.format("%s {%s}", this.name, this.predepends); - } - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - // NO OP - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) { - FMLRelaunchLog.info( - "Injecting coremod %s {%s} class transformers", - name, - coreModInstance.getClass() - .getName()); - if (coreModInstance.getASMTransformerClass() != null) - for (String transformer : coreModInstance.getASMTransformerClass()) { - FMLRelaunchLog.finer("Registering transformer %s", transformer); - classLoader.registerTransformer(transformer); - } - FMLRelaunchLog.fine("Injection complete"); - - FMLRelaunchLog.fine( - "Running coremod plugin for %s {%s}", - name, - coreModInstance.getClass() - .getName()); - Map data = new HashMap(); - data.put("mcLocation", mcDir); - data.put("coremodList", loadPlugins); - data.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); - FMLRelaunchLog.fine("Running coremod plugin %s", name); - data.put("coremodLocation", location); - coreModInstance.injectData(data); - String setupClass = coreModInstance.getSetupClass(); - if (setupClass != null) { - try { - IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader) - .newInstance(); - Map callData = new HashMap(); - callData.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); - callData.put("mcLocation", mcDir); - callData.put("classLoader", classLoader); - callData.put("coremodLocation", location); - callData.put("deobfuscationFileName", FMLInjectionData.debfuscationDataName()); - call.injectData(callData); - call.call(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - FMLRelaunchLog.fine( - "Coremod plugin class %s run successfully", - coreModInstance.getClass() - .getSimpleName()); - - String modContainer = coreModInstance.getModContainerClass(); - if (modContainer != null) { - FMLInjectionData.containers.add(modContainer); - } - } - - @Override - public String getLaunchTarget() { - return ""; - } - - @Override - public String[] getLaunchArguments() { - return new String[0]; - } - } - - public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker) { - CoreModManager.mcDir = mcDir; - CoreModManager.tweaker = tweaker; - try { - // Are we in a 'decompiled' environment? - byte[] bs = classLoader.getClassBytes("net.minecraft.world.World"); - if (bs != null) { - FMLRelaunchLog.info( - "Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation"); - deobfuscatedEnvironment = true; - } - } catch (IOException e1) {} - - if (!deobfuscatedEnvironment) { - FMLRelaunchLog.fine("Enabling runtime deobfuscation"); - } - - tweaker.injectCascadingTweak("cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker"); - try { - classLoader.registerTransformer("cpw.mods.fml.common.asm.transformers.PatchingTransformer"); - } catch (Exception e) { - FMLRelaunchLog.log( - Level.ERROR, - e, - "The patch transformer failed to load! This is critical, loading cannot continue!"); - e.printStackTrace(); - throw Throwables.propagate(e); - } - - loadPlugins = new ArrayList(); - for (String rootPluginName : rootPlugins) { - loadCoreMod(classLoader, rootPluginName, new File(FMLTweaker.getJarLocation())); - } - - if (loadPlugins.isEmpty()) { - throw new RuntimeException( - "A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation."); - } - - FMLRelaunchLog.fine("All fundamental core mods are successfully located"); - // Now that we have the root plugins loaded - lets see what else might - // be around - String commandLineCoremods = System.getProperty("fml.coreMods.load", ""); - for (String coreModClassName : commandLineCoremods.split(",")) { - if (coreModClassName.isEmpty()) { - continue; - } - FMLRelaunchLog.info("Found a command line coremod : %s", coreModClassName); - loadCoreMod(classLoader, coreModClassName, null); - } - discoverCoreMods(mcDir, classLoader); - } - - private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) { - ModListHelper.parseModList(mcDir); - FMLRelaunchLog.fine("Discovering coremods"); - File coreMods = setupCoreModDir(mcDir); - FilenameFilter ff = new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".jar"); - } - }; - FilenameFilter derpfilter = new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".jar.zip"); - } - }; - File[] derplist = coreMods.listFiles(derpfilter); - if (derplist != null && derplist.length > 0) { - FMLRelaunchLog.severe( - "FML has detected several badly downloaded jar files, which have been named as zip files. You probably need to download them again, or they may not work properly"); - for (File f : derplist) { - FMLRelaunchLog.severe("Problem file : %s", f.getName()); - } - } - FileFilter derpdirfilter = new FileFilter() { - - @Override - public boolean accept(File pathname) { - return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory(); - } - }; - File[] derpdirlist = coreMods.listFiles(derpdirfilter); - if (derpdirlist != null && derpdirlist.length > 0) { - FMLRelaunchLog.log.getLogger() - .log( - Level.FATAL, - "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL"); - FMLRelaunchLog.log.getLogger() - .log( - Level.FATAL, - "You should place original jars only in the mods directory. NEVER extract them to the mods directory."); - FMLRelaunchLog.log.getLogger() - .log( - Level.FATAL, - "The directories below appear to be extracted jar files. Fix this before you continue."); - - for (File f : derpdirlist) { - FMLRelaunchLog.log.getLogger() - .log( - Level.FATAL, - "Directory {} contains {}", - f.getName(), - Arrays.asList(new File(f, "META-INF").list())); - } - - RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue"); - // We're generating a crash report for the launcher to show to the user here - try { - Class crashreportclass = classLoader.loadClass("b"); - Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class) - .invoke( - null, - re, - "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided."); - File crashreportfile = new File( - new File(coreMods.getParentFile(), "crash-reports"), - String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance())); - crashreportclass.getMethod("a", File.class) - .invoke(crashreport, crashreportfile); - System.out.println( - "#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# " - + crashreportfile.getAbsolutePath()); - } catch (Exception e) { - e.printStackTrace(); - // NOOP - hopefully - } - throw re; - } - File[] coreModList = coreMods.listFiles(ff); - File versionedModDir = new File(coreMods, FMLInjectionData.mccversion); - if (versionedModDir.isDirectory()) { - File[] versionedCoreMods = versionedModDir.listFiles(ff); - coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class); - } - - coreModList = ObjectArrays.concat( - coreModList, - ModListHelper.additionalMods.values() - .toArray(new File[0]), - File.class); - - coreModList = FileListHelper.sortFileList(coreModList); - - for (File coreMod : coreModList) { - FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName()); - JarFile jar = null; - Attributes mfAttributes; - try { - jar = new JarFile(coreMod); - if (jar.getManifest() == null) { - // Not a coremod and no access transformer list - continue; - } - ModAccessTransformer.addJar(jar); - mfAttributes = jar.getManifest() - .getMainAttributes(); - } catch (IOException ioe) { - FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring", coreMod.getName()); - ioe.printStackTrace(); - continue; - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException e) { - // Noise - } - } - } - String cascadedTweaker = mfAttributes.getValue("TweakClass"); - if (cascadedTweaker != null) { - FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName()); - Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder"))); - sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder); - handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder); - loadedCoremods.add(coreMod.getName()); - continue; - } - List modTypes = mfAttributes.containsKey(MODTYPE) ? Arrays.asList( - mfAttributes.getValue(MODTYPE) - .split(",")) - : ImmutableList.of("FML"); - - if (!modTypes.contains("FML")) { - FMLRelaunchLog.fine( - "Adding %s to the list of things to skip. It is not an FML mod, it has types %s", - coreMod.getName(), - modTypes); - loadedCoremods.add(coreMod.getName()); - continue; - } - String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH"; - if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name() - .equals(modSide))) { - FMLRelaunchLog.fine( - "Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored", - coreMod.getName(), - modSide, - FMLLaunchHandler.side.name()); - loadedCoremods.add(coreMod.getName()); - continue; - } - String fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin"); - if (fmlCorePlugin == null) { - // Not a coremod - FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName()); - continue; - } - // Support things that are mod jars, but not FML mod jars - try { - classLoader.addURL( - coreMod.toURI() - .toURL()); - if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) { - FMLRelaunchLog.finer( - "Adding %s to the list of known coremods, it will not be examined again", - coreMod.getName()); - loadedCoremods.add(coreMod.getName()); - } else { - FMLRelaunchLog.finer( - "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances", - coreMod.getName()); - reparsedCoremods.add(coreMod.getName()); - } - } catch (MalformedURLException e) { - FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird"); - e.printStackTrace(); - continue; - } - loadCoreMod(classLoader, fmlCorePlugin, coreMod); - } - } - - private static Method ADDURL; - - private static void addUrlToClassloader(ClassLoader loader, URL coreModUrl) { - try { - if (loader instanceof URLClassLoader) { - if (ADDURL == null) { - ADDURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - ADDURL.setAccessible(true); - } - ADDURL.invoke(loader, coreModUrl); - } else { - Field ucpField; - try { - // Java 8-11 - ucpField = loader.getClass() - .getDeclaredField("ucp"); - } catch (NoSuchFieldException e) { - // Java 17 - ucpField = loader.getClass() - .getSuperclass() - .getDeclaredField("ucp"); - } - ucpField.setAccessible(true); - final Object ucp = ucpField.get(loader); - final Method urlAdder = ucp.getClass() - .getDeclaredMethod("addURL", URL.class); - urlAdder.invoke(ucp, coreModUrl); - } - } catch (ReflectiveOperationException e) { - throw new RuntimeException("Couldn't add url to classpath in loader " + loader.getClass(), e); - } - } - - private static void handleCascadingTweak(File coreMod, JarFile jar, String cascadedTweaker, - LaunchClassLoader classLoader, Integer sortingOrder) { - try { - // Have to manually stuff the tweaker into the parent classloader - // PATCHED BEGIN - URL coreModUrl = coreMod.toURI() - .toURL(); - ClassLoader myLoader = classLoader.getClass() - .getClassLoader(); - addUrlToClassloader(myLoader, coreModUrl); - classLoader.addURL(coreModUrl); - // PATCHED END - CoreModManager.tweaker.injectCascadingTweak(cascadedTweaker); - tweakSorting.put(cascadedTweaker, sortingOrder); - } catch (Exception e) { - FMLRelaunchLog.log( - Level.INFO, - e, - "There was a problem trying to load the mod dir tweaker %s", - coreMod.getAbsolutePath()); - e.printStackTrace(); - } - } - - /** - * @param mcDir the minecraft home directory - * @return the coremod directory - */ - private static File setupCoreModDir(File mcDir) { - File coreModDir = new File(mcDir, "mods"); - try { - coreModDir = coreModDir.getCanonicalFile(); - } catch (IOException e) { - throw new RuntimeException( - String.format("Unable to canonicalize the coremod dir at %s", mcDir.getName()), - e); - } - if (!coreModDir.exists()) { - coreModDir.mkdir(); - } else if (coreModDir.exists() && !coreModDir.isDirectory()) { - throw new RuntimeException( - String.format("Found a coremod file in %s that's not a directory", mcDir.getName())); - } - return coreModDir; - } - - public static List getLoadedCoremods() { - return loadedCoremods; - } - - public static List getReparseableCoremods() { - return reparsedCoremods; - } - - private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) { - String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1); - try { - FMLRelaunchLog.fine("Instantiating coremod class %s", coreModName); - classLoader.addTransformerExclusion(coreModClass); - Class coreModClazz = Class.forName(coreModClass, true, classLoader); - Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class); - if (coreModNameAnn != null && !Strings.isNullOrEmpty(coreModNameAnn.value())) { - coreModName = coreModNameAnn.value(); - FMLRelaunchLog.finer("coremod named %s is loading", coreModName); - } - MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class); - if (!Arrays.asList(rootPlugins) - .contains(coreModClass) - && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value()))) { - FMLRelaunchLog.log( - Level.WARN, - "The coremod %s does not have a MCVersion annotation, it may cause issues with this version of Minecraft", - coreModClass); - } else if (requiredMCVersion != null && !FMLInjectionData.mccversion.equals(requiredMCVersion.value())) { - FMLRelaunchLog.log( - Level.ERROR, - "The coremod %s is requesting minecraft version %s and minecraft is %s. It will be ignored.", - coreModClass, - requiredMCVersion.value(), - FMLInjectionData.mccversion); - return null; - } else if (requiredMCVersion != null) { - FMLRelaunchLog.log( - Level.DEBUG, - "The coremod %s requested minecraft version %s and minecraft is %s. It will be loaded.", - coreModClass, - requiredMCVersion.value(), - FMLInjectionData.mccversion); - } - TransformerExclusions trExclusions = coreModClazz - .getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class); - if (trExclusions != null) { - for (String st : trExclusions.value()) { - classLoader.addTransformerExclusion(st); - } - } - DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class); - String[] dependencies = new String[0]; - if (deplist != null) { - dependencies = deplist.value(); - } - SortingIndex index = coreModClazz.getAnnotation(IFMLLoadingPlugin.SortingIndex.class); - int sortIndex = index != null ? index.value() : 0; - - IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance(); - String accessTransformerClass = plugin.getAccessTransformerClass(); - if (accessTransformerClass != null) { - FMLRelaunchLog.log( - Level.DEBUG, - "Added access transformer class %s to enqueued access transformers", - accessTransformerClass); - accessTransformers.add(accessTransformerClass); - } - FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, sortIndex, dependencies); - loadPlugins.add(wrap); - FMLRelaunchLog.fine("Enqueued coremod %s", coreModName); - return wrap; - } catch (ClassNotFoundException cnfe) { - if (!Lists.newArrayList(rootPlugins) - .contains(coreModClass)) - FMLRelaunchLog.log( - Level.ERROR, - cnfe, - "Coremod %s: Unable to class load the plugin %s", - coreModName, - coreModClass); - else FMLRelaunchLog.fine("Skipping root plugin %s", coreModClass); - } catch (ClassCastException cce) { - FMLRelaunchLog.log( - Level.ERROR, - cce, - "Coremod %s: The plugin %s is not an implementor of IFMLLoadingPlugin", - coreModName, - coreModClass); - cce.printStackTrace(); - } catch (InstantiationException ie) { - FMLRelaunchLog.log( - Level.ERROR, - ie, - "Coremod %s: The plugin class %s was not instantiable", - coreModName, - coreModClass); - ie.printStackTrace(); - } catch (IllegalAccessException iae) { - FMLRelaunchLog - .log(Level.ERROR, iae, "Coremod %s: The plugin class %s was not accessible", coreModName, coreModClass); - iae.printStackTrace(); - } - return null; - } - - @SuppressWarnings("unused") - private static void sortCoreMods() { - TopologicalSort.DirectedGraph sortGraph = new TopologicalSort.DirectedGraph(); - Map pluginMap = Maps.newHashMap(); - for (FMLPluginWrapper plug : loadPlugins) { - sortGraph.addNode(plug); - pluginMap.put(plug.name, plug); - } - - for (FMLPluginWrapper plug : loadPlugins) { - for (String dep : plug.predepends) { - if (!pluginMap.containsKey(dep)) { - FMLRelaunchLog.log( - Level.ERROR, - "Missing coremod dependency - the coremod %s depends on coremod %s which isn't present.", - plug.name, - dep); - throw new RuntimeException(); - } - sortGraph.addEdge(plug, pluginMap.get(dep)); - } - } - try { - loadPlugins = TopologicalSort.topologicalSort(sortGraph); - FMLRelaunchLog.fine("Sorted coremod list %s", loadPlugins); - } catch (Exception e) { - FMLLog.log(Level.ERROR, e, "There was a problem performing the coremod sort"); - e.printStackTrace(); - throw Throwables.propagate(e); - } - } - - public static void injectTransformers(LaunchClassLoader classLoader) { - - Launch.blackboard.put("fml.deobfuscatedEnvironment", deobfuscatedEnvironment); - tweaker.injectCascadingTweak("cpw.mods.fml.common.launcher.FMLDeobfTweaker"); - tweakSorting.put("cpw.mods.fml.common.launcher.FMLDeobfTweaker", Integer.valueOf(1000)); - } - - public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectionAndSortingTweaker) { - @SuppressWarnings("unchecked") - List tweakers = (List) Launch.blackboard.get("Tweaks"); - // Add the sorting tweaker first- it'll appear twice in the list - tweakers.add(0, fmlInjectionAndSortingTweaker); - for (FMLPluginWrapper wrapper : loadPlugins) { - tweakers.add(wrapper); - } - } - - private static Map tweakSorting = Maps.newHashMap(); - - public static void sortTweakList() { - @SuppressWarnings("unchecked") - List tweakers = (List) Launch.blackboard.get("Tweaks"); - // Basically a copy of Collections.sort pre 8u20, optimized as we know we're an array list. - // Thanks unhelpful fixer of http://bugs.java.com/view_bug.do?bug_id=8032636 - ITweaker[] toSort = tweakers.toArray(new ITweaker[tweakers.size()]); - Arrays.sort(toSort, new Comparator() { - - @Override - public int compare(ITweaker o1, ITweaker o2) { - Integer first = null; - Integer second = null; - if (o1 instanceof FMLInjectionAndSortingTweaker) { - first = Integer.MIN_VALUE; - } - if (o2 instanceof FMLInjectionAndSortingTweaker) { - second = Integer.MIN_VALUE; - } - - if (o1 instanceof FMLPluginWrapper) { - first = ((FMLPluginWrapper) o1).sortIndex; - } else if (first == null) { - first = tweakSorting.get( - o1.getClass() - .getName()); - } - if (o2 instanceof FMLPluginWrapper) { - second = ((FMLPluginWrapper) o2).sortIndex; - } else if (second == null) { - second = tweakSorting.get( - o2.getClass() - .getName()); - } - if (first == null) { - first = 0; - } - if (second == null) { - second = 0; - } - - return Ints.saturatedCast((long) first - (long) second); - } - }); - // Basically a copy of Collections.sort, optimized as we know we're an array list. - // Thanks unhelpful fixer of http://bugs.java.com/view_bug.do?bug_id=8032636 - for (int j = 0; j < toSort.length; j++) { - tweakers.set(j, toSort[j]); - } - } - - public static List getAccessTransformers() { - return accessTransformers; - } -} diff --git a/src/generated/java/org/lwjgl/input/Keyboard.java b/src/generated/java/org/lwjgl/input/Keyboard.java index 5091ebf..da8d302 100644 --- a/src/generated/java/org/lwjgl/input/Keyboard.java +++ b/src/generated/java/org/lwjgl/input/Keyboard.java @@ -1,5 +1,7 @@ package org.lwjgl.input; +import org.lwjglx.LWJGLException; + public class Keyboard { public static final int CHAR_NONE = (int) 0; @@ -140,71 +142,71 @@ public class Keyboard { public static final int KEY_Z = (int) 44; public static boolean areRepeatEventsEnabled() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.areRepeatEventsEnabled(); } - public static void create() { - throw new UnsupportedOperationException(); + public static void create() throws LWJGLException { + org.lwjglx.input.Keyboard.create(); } public static void destroy() { - throw new UnsupportedOperationException(); + org.lwjglx.input.Keyboard.destroy(); } public static void enableRepeatEvents(boolean arg0) { - throw new UnsupportedOperationException(); + org.lwjglx.input.Keyboard.enableRepeatEvents(arg0); } public static char getEventCharacter() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getEventCharacter(); } public static int getEventKey() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getEventKey(); } public static boolean getEventKeyState() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getEventKeyState(); } public static long getEventNanoseconds() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getEventNanoseconds(); } public static int getKeyCount() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getKeyCount(); } public static int getKeyIndex(java.lang.String arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getKeyIndex(arg0); } public static java.lang.String getKeyName(int arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getKeyName(arg0); } public static int getNumKeyboardEvents() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.getNumKeyboardEvents(); } public static boolean isCreated() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.isCreated(); } public static boolean isKeyDown(int arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.isKeyDown(arg0); } public static boolean isRepeatEvent() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.isRepeatEvent(); } public static boolean next() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Keyboard.next(); } public static void poll() { - throw new UnsupportedOperationException(); + org.lwjglx.input.Keyboard.poll(); } } diff --git a/src/generated/java/org/lwjgl/input/Mouse.java b/src/generated/java/org/lwjgl/input/Mouse.java index be7b7fa..6a8ec54 100644 --- a/src/generated/java/org/lwjgl/input/Mouse.java +++ b/src/generated/java/org/lwjgl/input/Mouse.java @@ -1,99 +1,101 @@ package org.lwjgl.input; +import org.lwjglx.LWJGLException; + public class Mouse { public static final int EVENT_SIZE = (int) 22; - public static void create() { - throw new UnsupportedOperationException(); + public static void create() throws LWJGLException { + org.lwjglx.input.Mouse.create(); } public static void destroy() { - throw new UnsupportedOperationException(); + org.lwjglx.input.Mouse.destroy(); } public static int getButtonCount() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getButtonCount(); } public static int getButtonIndex(java.lang.String arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getButtonIndex(arg0); } public static java.lang.String getButtonName(int arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getButtonName(arg0); } public static int getDWheel() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getDWheel(); } public static int getDX() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getDX(); } public static int getDY() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getDY(); } public static int getEventButton() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventButton(); } public static boolean getEventButtonState() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventButtonState(); } public static int getEventDWheel() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventDWheel(); } public static int getEventDX() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventDX(); } public static int getEventDY() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventDY(); } public static long getEventNanoseconds() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventNanoseconds(); } public static int getEventX() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventX(); } public static int getEventY() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getEventY(); } public static org.lwjgl.input.Cursor getNativeCursor() { - throw new UnsupportedOperationException(); + return null; } public static int getX() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getX(); } public static int getY() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.getY(); } public static boolean hasWheel() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.hasWheel(); } public static boolean isButtonDown(int arg0) { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.isButtonDown(arg0); } public static boolean isClipMouseCoordinatesToWindow() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.isClipMouseCoordinatesToWindow(); } public static boolean isCreated() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.isCreated(); } public static boolean isGrabbed() { @@ -101,23 +103,23 @@ public class Mouse { } public static boolean isInsideWindow() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.isInsideWindow(); } public static boolean next() { - throw new UnsupportedOperationException(); + return org.lwjglx.input.Mouse.next(); } public static void poll() { - throw new UnsupportedOperationException(); + org.lwjglx.input.Mouse.poll(); } public static void setClipMouseCoordinatesToWindow(boolean arg0) { - throw new UnsupportedOperationException(); + org.lwjglx.input.Mouse.setClipMouseCoordinatesToWindow(arg0); } public static void setCursorPosition(int arg0, int arg1) { - throw new UnsupportedOperationException(); + org.lwjglx.input.Mouse.setCursorPosition(arg0, arg1); } public static void setGrabbed(boolean arg0) { @@ -125,10 +127,10 @@ public class Mouse { } public static org.lwjgl.input.Cursor setNativeCursor(org.lwjgl.input.Cursor arg0) { - throw new UnsupportedOperationException(); + return null; } public static void updateCursor() { - throw new UnsupportedOperationException(); + org.lwjglx.input.Mouse.updateCursor(); } } diff --git a/src/generated/java/org/lwjglx/opengl/GL11.java b/src/generated/java/org/lwjglx/opengl/GL11.java index 017806e..9d23d18 100644 --- a/src/generated/java/org/lwjglx/opengl/GL11.java +++ b/src/generated/java/org/lwjglx/opengl/GL11.java @@ -1,5 +1,6 @@ package org.lwjglx.opengl; +@SuppressWarnings("unused") public class GL11 { public static final int GL_2D = (int) 1536; @@ -1001,7 +1002,19 @@ public class GL11 { } public static java.lang.String glGetString(int name) { - return org.lwjgl.opengl.GL11.glGetString(name); + // Prevent crashes when trying to access GL_RENDERER etc. from the crash report handler + boolean hasGlContext = true; + try { + org.lwjgl.opengl.GL.getCapabilities(); + } catch (IllegalStateException ise) { + // No OpenGL context in current thread + hasGlContext = false; + } + if (hasGlContext) { + return org.lwjgl.opengl.GL11.glGetString(name); + } else { + return "no valid GL context"; + } } public static void glGetTexEnv(int coord, int pname, java.nio.FloatBuffer params) { diff --git a/src/hotswap/java/me.eigenraven.lwjgl3ify.hotswap/TransformHelper.java b/src/hotswap/java/me.eigenraven.lwjgl3ify.hotswap/TransformHelper.java index df25004..4f608ba 100644 --- a/src/hotswap/java/me.eigenraven.lwjgl3ify.hotswap/TransformHelper.java +++ b/src/hotswap/java/me.eigenraven.lwjgl3ify.hotswap/TransformHelper.java @@ -14,6 +14,7 @@ public class TransformHelper { static Field classLoaderExceptionsField; static Field xformerExceptionsField; + @SuppressWarnings("unchecked") public static byte[] transform(LaunchClassLoader loader, String name, byte[] classBytes) throws Exception { if (classLoaderExceptionsField == null) { classLoaderExceptionsField = loader.getClass() diff --git a/src/main/java/cpw/mods/fml/common/fakelwjgl3ify/SafeRuntimeExit.java b/src/main/java/cpw/mods/fml/common/fakelwjgl3ify/SafeRuntimeExit.java new file mode 100644 index 0000000..0517d40 --- /dev/null +++ b/src/main/java/cpw/mods/fml/common/fakelwjgl3ify/SafeRuntimeExit.java @@ -0,0 +1,22 @@ +package cpw.mods.fml.common.fakelwjgl3ify; + +/** Safe runtime exit class to not trip the FML security manager. */ +public class SafeRuntimeExit { + + public static void exitRuntime(int code) { + nest0(code); + } + + private static void nest0(int code) { + nest1(code); + } + + private static void nest1(int code) { + nest2(code); + } + + private static void nest2(int code) { + Runtime.getRuntime() + .exit(code); + } +} diff --git a/src/forgePatches/java/net/minecraftforge/common/util/EnumHelper.java b/src/main/java/me/eigenraven/lwjgl3ify/EnumHelper.java similarity index 93% rename from src/forgePatches/java/net/minecraftforge/common/util/EnumHelper.java rename to src/main/java/me/eigenraven/lwjgl3ify/EnumHelper.java index 65d07f1..e2c8048 100644 --- a/src/forgePatches/java/net/minecraftforge/common/util/EnumHelper.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/EnumHelper.java @@ -1,4 +1,4 @@ -package net.minecraftforge.common.util; +package me.eigenraven.lwjgl3ify; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -30,6 +30,7 @@ import com.google.common.base.Throwables; import cpw.mods.fml.common.FMLLog; +@SuppressWarnings("unused") // used from asm public class EnumHelper { // Some enums are decompiled with extra arguments, so lets check for that @@ -174,6 +175,21 @@ public class EnumHelper { private static final Class extensibleEnumIface; private static final MethodHandle setFieldHandle; + public static void setup() {} + + public static Object getConstructorAccessor(Class enumClass, Class[] additionalParameterTypes) { + return null; + } + + public static > T makeEnum(Class enumClass, String value, int ordinal, + Class[] additionalTypes, Object[] additionalValues) { + return null; + } + + public static void blankField(Class enumClass, String fieldName) {} + + public static void cleanEnumCache(Class enumClass) {} + static { try { extensibleEnumIface = Class.forName("me.eigenraven.lwjgl3ify.IExtensibleEnum"); diff --git a/src/main/java/me/eigenraven/lwjgl3ify/Lwjgl3ify.java b/src/main/java/me/eigenraven/lwjgl3ify/Lwjgl3ify.java index 1d758a8..d8cf2e6 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/Lwjgl3ify.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/Lwjgl3ify.java @@ -32,7 +32,9 @@ public class Lwjgl3ify { @Mod.Instance public static Lwjgl3ify INSTANCE; - @SidedProxy(clientSide = "me.eigenraven.lwjgl3ify.ClientProxy", serverSide = "me.eigenraven.lwjgl3ify.CommonProxy") + @SidedProxy( + clientSide = "me.eigenraven.lwjgl3ify.client.ClientProxy", + serverSide = "me.eigenraven.lwjgl3ify.CommonProxy") public static CommonProxy PROXY; @Mod.EventHandler diff --git a/src/main/java/me/eigenraven/lwjgl3ify/api/InputEvents.java b/src/main/java/me/eigenraven/lwjgl3ify/api/InputEvents.java new file mode 100644 index 0000000..cd24ddc --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/api/InputEvents.java @@ -0,0 +1,138 @@ +package me.eigenraven.lwjgl3ify.api; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; + +/** + * Provides direct access to raw key press and text input events. + * The main benefit is the separation of key and char events, which allows proper dead key and unicode input handling. + */ +@SuppressWarnings({ "ForLoopReplaceableByForEach", "unused" }) // avoid allocations for performance +public class InputEvents { + + /** The key state change. */ + public enum KeyAction { + PRESSED, + REPEATED, + RELEASED, + } + + /** A key state change/repeat event. */ + public static class KeyEvent { + + /** The mapped LWJGL2 key code, e.g. {@link org.lwjglx.input.Keyboard#KEY_A} */ + public final int lwjgl2KeyCode; + /** Raw codes from LWJGL3's GLFW */ + public final int glfwKeyCode, glfwScanCode; + /** What happened to the key */ + public final KeyAction action; + /** Modifiers held while the key action happened */ + public final boolean controlPressed, shiftPressed, altPressed, superPressed; + + /** Constructs a new KeyEvent with the given data. */ + public KeyEvent(int lwjgl2KeyCode, int glfwKeyCode, int glfwScanCode, KeyAction action, boolean controlPressed, + boolean shiftPressed, boolean altPressed, boolean superPressed) { + this.lwjgl2KeyCode = lwjgl2KeyCode; + this.glfwKeyCode = glfwKeyCode; + this.glfwScanCode = glfwScanCode; + this.action = action; + this.controlPressed = controlPressed; + this.shiftPressed = shiftPressed; + this.altPressed = altPressed; + this.superPressed = superPressed; + } + } + + /** A text input event, indicating some text was typed - either via a keypress or IME input */ + public static class TextEvent { + + // Currently GLFW only provides individual chars, but a future string-oriented API is planned + /** The text that was put in */ + public final String text; + + /** Constructs a new KeyEvent with the given data. */ + public TextEvent(String text) { + this.text = text; + } + } + + /** Implement this interface and register it with this class to receive raw LWJGL3 input events. */ + public interface KeyboardListener { + + /** Handle a key press event */ + default void onKeyEvent(KeyEvent event) {} + + /** Handle a text input event */ + default void onTextEvent(TextEvent event) {} + } + + private static final ArrayList keyboardListeners = new ArrayList<>(); + private static final ArrayList> weakKeyboardListeners = new ArrayList<>(); + + /** Registers the given listener to receive events. */ + public static void addKeyboardListener(KeyboardListener listener) { + keyboardListeners.add(listener); + } + + /** Removes the given listener to no longer receive events. */ + public static void removeKeyboardListener(KeyboardListener listener) { + keyboardListeners.remove(listener); + } + + /** + * Like {@link InputEvents#addKeyboardListener}, but only holds onto a {@link WeakReference} of the given object, + * and cleans it up automatically once the object is collected. + */ + public static void addWeakKeyboardListener(KeyboardListener listener) { + weakKeyboardListeners.add(new WeakReference<>(listener)); + } + + /** Allows for early removal of a weak keyboard listener. */ + public static void removeWeakKeyboardListener(KeyboardListener listener) { + for (int i = 0; i < weakKeyboardListeners.size(); i++) { + if (weakKeyboardListeners.get(i) + .get() == listener) { + weakKeyboardListeners.remove(i); + return; + } + } + } + + /** Sends a synthetic key event to all the handlers. */ + public static void injectKeyEvent(final KeyEvent ev) { + for (int i = 0; i < keyboardListeners.size(); i++) { + final KeyboardListener listener = keyboardListeners.get(i); + listener.onKeyEvent(ev); + } + for (int i = 0; i < weakKeyboardListeners.size(); i++) { + final WeakReference weak = weakKeyboardListeners.get(i); + final KeyboardListener strong = weak.get(); + if (strong == null) { + // remove dead reference + weakKeyboardListeners.remove(i); + i--; + } else { + strong.onKeyEvent(ev); + } + } + } + + /** Sends a synthetic text event to all the handlers. */ + public static void injectTextEvent(final TextEvent ev) { + for (int i = 0; i < keyboardListeners.size(); i++) { + final KeyboardListener listener = keyboardListeners.get(i); + listener.onTextEvent(ev); + } + for (int i = 0; i < weakKeyboardListeners.size(); i++) { + final WeakReference weak = weakKeyboardListeners.get(i); + final KeyboardListener strong = weak.get(); + if (strong == null) { + // remove dead reference + weakKeyboardListeners.remove(i); + i--; + } else { + strong.onTextEvent(ev); + } + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/ClientProxy.java b/src/main/java/me/eigenraven/lwjgl3ify/client/ClientProxy.java similarity index 58% rename from src/main/java/me/eigenraven/lwjgl3ify/ClientProxy.java rename to src/main/java/me/eigenraven/lwjgl3ify/client/ClientProxy.java index 75694e3..5a3d23a 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/ClientProxy.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/client/ClientProxy.java @@ -1,19 +1,15 @@ -package me.eigenraven.lwjgl3ify; - -import java.lang.reflect.Field; -import java.util.List; +package me.eigenraven.lwjgl3ify.client; import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import org.lwjglx.input.Keyboard; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.ICrashCallable; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import me.eigenraven.lwjgl3ify.client.GLDebugLog; -import me.eigenraven.lwjgl3ify.client.GLInfoCrashCallable; +import me.eigenraven.lwjgl3ify.CommonProxy; +import me.eigenraven.lwjgl3ify.api.InputEvents; import me.eigenraven.lwjgl3ify.core.Config; public class ClientProxy extends CommonProxy { @@ -32,12 +28,33 @@ public class ClientProxy extends CommonProxy { @Override public void runCompatHooks() { super.runCompatHooks(); - replaceOpenGLCrashHandler(); if (Config.DEBUG_REGISTER_OPENGL_LOGGER) { GLDebugLog.setupDebugMessageCallback(); } // Populate keyboard-layout-dependent key lookup tables Keyboard.populateKeyLookupTables(); + registerKeybindHandler(); + } + + private static final class McKeybindHandler implements InputEvents.KeyboardListener { + + @Override + public void onKeyEvent(InputEvents.KeyEvent event) { + final Minecraft mc = Minecraft.getMinecraft(); + if (mc == null) { + return; + } + if (mc.currentScreen != null) { + return; + } + if (event.lwjgl2KeyCode > Keyboard.KEY_NONE) { + KeyBinding.setKeyBindState(event.lwjgl2KeyCode, event.action != InputEvents.KeyAction.RELEASED); + } + } + } + + private void registerKeybindHandler() { + InputEvents.addKeyboardListener(new McKeybindHandler()); } @Override @@ -45,25 +62,6 @@ public class ClientProxy extends CommonProxy { MinecraftForge.EVENT_BUS.register(this); } - @SuppressWarnings("unchecked") - private void replaceOpenGLCrashHandler() { - // Use a crash handler that's safe against being called from another thread - try { - final Field callablesField = FMLCommonHandler.class.getDeclaredField("crashCallables"); - callablesField.setAccessible(true); - List crashCallables = (List) callablesField - .get(FMLCommonHandler.instance()); - for (int i = 0; i < crashCallables.size(); i++) { - ICrashCallable original = crashCallables.get(i); - if ("GL info".equals(original.getLabel()) && !(original instanceof GLInfoCrashCallable)) { - crashCallables.set(i, new GLInfoCrashCallable()); - } - } - } catch (ReflectiveOperationException e) { - Lwjgl3ify.LOG.error("Could not access crash callables to make them OpenGL thread-safe", e); - } - } - @SubscribeEvent @SuppressWarnings("unused") // event handler public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) { diff --git a/src/main/java/me/eigenraven/lwjgl3ify/client/GLDebugLog.java b/src/main/java/me/eigenraven/lwjgl3ify/client/GLDebugLog.java index 5a1be2b..d8eb5ef 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/client/GLDebugLog.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/client/GLDebugLog.java @@ -1,5 +1,11 @@ package me.eigenraven.lwjgl3ify.client; +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL43; +import org.lwjgl.opengl.GLCapabilities; +import org.lwjgl.opengl.GLDebugMessageCallback; + public class GLDebugLog { private static void printDetail(java.io.PrintStream stream, String type, String message) { @@ -61,67 +67,69 @@ public class GLDebugLog { private static String getDebugSource(int source) { return switch (source) { - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_API -> "API"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_WINDOW_SYSTEM -> "WINDOW SYSTEM"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_SHADER_COMPILER -> "SHADER COMPILER"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_THIRD_PARTY -> "THIRD PARTY"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_APPLICATION -> "APPLICATION"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SOURCE_OTHER -> "OTHER"; + case GL43.GL_DEBUG_SOURCE_API -> "API"; + case GL43.GL_DEBUG_SOURCE_WINDOW_SYSTEM -> "WINDOW SYSTEM"; + case GL43.GL_DEBUG_SOURCE_SHADER_COMPILER -> "SHADER COMPILER"; + case GL43.GL_DEBUG_SOURCE_THIRD_PARTY -> "THIRD PARTY"; + case GL43.GL_DEBUG_SOURCE_APPLICATION -> "APPLICATION"; + case GL43.GL_DEBUG_SOURCE_OTHER -> "OTHER"; default -> String.format("Unknown [0x%X]", source); }; } private static String getDebugType(int type) { return switch (type) { - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_ERROR -> "ERROR"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR -> "DEPRECATED BEHAVIOR"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR -> "UNDEFINED BEHAVIOR"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_PORTABILITY -> "PORTABILITY"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_PERFORMANCE -> "PERFORMANCE"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_OTHER -> "OTHER"; - case org.lwjgl.opengl.GL43.GL_DEBUG_TYPE_MARKER -> "MARKER"; + case GL43.GL_DEBUG_TYPE_ERROR -> "ERROR"; + case GL43.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR -> "DEPRECATED BEHAVIOR"; + case GL43.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR -> "UNDEFINED BEHAVIOR"; + case GL43.GL_DEBUG_TYPE_PORTABILITY -> "PORTABILITY"; + case GL43.GL_DEBUG_TYPE_PERFORMANCE -> "PERFORMANCE"; + case GL43.GL_DEBUG_TYPE_OTHER -> "OTHER"; + case GL43.GL_DEBUG_TYPE_MARKER -> "MARKER"; default -> String.format("Unknown [0x%X]", type); }; } private static String getDebugSeverity(int severity) { return switch (severity) { - case org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_NOTIFICATION -> "NOTIFICATION"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_HIGH -> "HIGH"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_MEDIUM -> "MEDIUM"; - case org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_LOW -> "LOW"; + case GL43.GL_DEBUG_SEVERITY_NOTIFICATION -> "NOTIFICATION"; + case GL43.GL_DEBUG_SEVERITY_HIGH -> "HIGH"; + case GL43.GL_DEBUG_SEVERITY_MEDIUM -> "MEDIUM"; + case GL43.GL_DEBUG_SEVERITY_LOW -> "LOW"; default -> String.format("Unknown [0x%X]", severity); }; } public static void setupDebugMessageCallback() { - org.lwjgl.opengl.GLCapabilities caps = org.lwjgl.opengl.GL.getCapabilities(); + GLCapabilities caps = GL.getCapabilities(); final java.io.PrintStream stream = org.lwjgl.system.APIUtil.DEBUG_STREAM; if (caps.OpenGL43) { org.lwjgl.system.APIUtil.apiLog("[GL] Using OpenGL 4.3 for error logging."); - org.lwjgl.opengl.GLDebugMessageCallback proc = org.lwjgl.opengl.GLDebugMessageCallback + GLDebugMessageCallback proc = GLDebugMessageCallback .create((source, type, id, severity, length, message, userParam) -> { String level; - if (severity == org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_NOTIFICATION - || severity == org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_LOW) level = "info "; - else if (severity == org.lwjgl.opengl.GL43.GL_DEBUG_SEVERITY_MEDIUM) level = "warn "; + if (severity == GL43.GL_DEBUG_SEVERITY_NOTIFICATION) { + // skip + return; + } + if (severity == GL43.GL_DEBUG_SEVERITY_LOW) level = "info "; + else if (severity == GL43.GL_DEBUG_SEVERITY_MEDIUM) level = "warn "; else level = "error"; stream.println("[" + level + "] OpenGL debug message"); printDetail(stream, "ID", String.format("0x%X", id)); printDetail(stream, "Source", getDebugSource(source)); printDetail(stream, "Type", getDebugType(type)); printDetail(stream, "Severity", getDebugSeverity(severity)); - printDetail(stream, "Message", org.lwjgl.opengl.GLDebugMessageCallback.getMessage(length, message)); + printDetail(stream, "Message", GLDebugMessageCallback.getMessage(length, message)); printTrace(stream); }); - org.lwjgl.opengl.GL43.glDebugMessageCallback(proc, org.lwjgl.system.MemoryUtil.NULL); - if ((org.lwjgl.opengl.GL11.glGetInteger(org.lwjgl.opengl.GL43.GL_CONTEXT_FLAGS) - & org.lwjgl.opengl.GL43.GL_CONTEXT_FLAG_DEBUG_BIT) == 0) { + GL43.glDebugMessageCallback(proc, org.lwjgl.system.MemoryUtil.NULL); + if ((GL11.glGetInteger(GL43.GL_CONTEXT_FLAGS) & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) == 0) { org.lwjgl.system.APIUtil.apiLog("[GL] Warning: A non-debug context may not produce any debug output."); - org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL43.GL_DEBUG_OUTPUT); + GL11.glEnable(GL43.GL_DEBUG_OUTPUT); } - org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL43.GL_DEBUG_OUTPUT_SYNCHRONOUS); + GL11.glEnable(GL43.GL_DEBUG_OUTPUT_SYNCHRONOUS); } } } diff --git a/src/main/java/me/eigenraven/lwjgl3ify/client/GLInfoCrashCallable.java b/src/main/java/me/eigenraven/lwjgl3ify/client/GLInfoCrashCallable.java deleted file mode 100644 index 07e17a1..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/client/GLInfoCrashCallable.java +++ /dev/null @@ -1,42 +0,0 @@ -package me.eigenraven.lwjgl3ify.client; - -import static org.lwjgl.opengl.GL11.GL_RENDERER; -import static org.lwjgl.opengl.GL11.GL_VENDOR; -import static org.lwjgl.opengl.GL11.GL_VERSION; -import static org.lwjgl.opengl.GL11.glGetString; - -import org.lwjgl.opengl.GL; - -import cpw.mods.fml.common.ICrashCallable; - -public class GLInfoCrashCallable implements ICrashCallable { - - @Override - public String getLabel() { - return "GL info"; - } - - @Override - public String call() throws Exception { - boolean hasGlContext = true; - try { - if (GL.getCapabilities() == null) { - hasGlContext = false; - } - } catch (IllegalStateException ise) { - // No OpenGL context in current thread - hasGlContext = false; - } - if (hasGlContext) { - return "' Vendor: '" + glGetString(GL_VENDOR) - + "' Version: '" - + glGetString(GL_VERSION) - + "' Renderer: '" - + glGetString(GL_RENDERER) - + "'"; - } else { - return "No OpenGL context present in the calling thread: " + Thread.currentThread() - .getName(); - } - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/Config.java b/src/main/java/me/eigenraven/lwjgl3ify/core/Config.java index afb573a..90c3f5a 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/Config.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/core/Config.java @@ -1,59 +1,16 @@ package me.eigenraven.lwjgl3ify.core; import java.io.File; -import java.util.Arrays; -import java.util.HashSet; import java.util.Set; import net.minecraft.launchwrapper.Launch; import net.minecraftforge.common.config.Configuration; import me.eigenraven.lwjgl3ify.Tags; +import me.eigenraven.lwjgl3ify.rfb.EarlyConfig; public class Config { - public static final String[] DEFAULT_EXTENSIBLE_ENUMS = new String[] { - // From EnumHelper - "net.minecraft.item.EnumAction", "net.minecraft.item.ItemArmor$ArmorMaterial", - "net.minecraft.entity.item.EntityPainting$EnumArt", "net.minecraft.entity.EnumCreatureAttribute", - "net.minecraft.entity.EnumCreatureType", - "net.minecraft.world.gen.structure.StructureStrongholdPieces$Stronghold$Door", - "net.minecraft.enchantment.EnumEnchantmentType", "net.minecraft.entity.Entity$EnumEntitySize", - "net.minecraft.block.BlockPressurePlate$Sensitivity", - "net.minecraft.util.MovingObjectPosition$MovingObjectType", "net.minecraft.world.EnumSkyBlock", - "net.minecraft.entity.player.EntityPlayer$EnumStatus", "net.minecraft.item.Item$ToolMaterial", - "net.minecraft.item.EnumRarity", - // - "net.minecraftforge.event.terraingen.PopulateChunkEvent$Populate$EventType", - "net.minecraftforge.event.terraingen.InitMapGenEvent$EventType", - "net.minecraftforge.event.terraingen.OreGenEvent$GenerateMinable$EventType", - "net.minecraftforge.event.terraingen.DecorateBiomeEvent$Decorate$EventType", - // From GTNH crashes - "vswe.stevesfactory.Localization", "vswe.stevesfactory.blocks.ClusterMethodRegistration", - "vswe.stevesfactory.blocks.ConnectionBlockType", "vswe.stevesfactory.components.ComponentType", - "vswe.stevesfactory.components.ConnectionSet", "vswe.stevesfactory.components.ConnectionOption", - "ic2.core.init.InternalName", "gregtech.api.enums.Element", "gregtech.api.enums.OrePrefixes", - "net.minecraft.client.audio.MusicTicker$MusicType", "org.bukkit.Material", - "buildcraft.api.transport.IPipeTile.PipeType", "thaumcraft.common.entities.golems.EnumGolemType", - // Non-GTNH Mods Compat - // The Lord of the Rings Mod: Legacy - "net.minecraft.event.HoverEvent$Action", - // Reika's mods - "net.minecraft.client.audio.SoundCategory", - "Reika.RotaryCraft.TileEntities.Processing.TileEntityFuelConverter$Conversions", - "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Fertility", - "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Speeds", - "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Flowering", - "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Territory", - "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Life", - "Reika.DragonAPI.ModInteract.Bees.ButterflyAlleleRegistry$Fertility", - "Reika.DragonAPI.ModInteract.Bees.ButterflyAlleleRegistry$Life", - // Et Futurum Requiem - "net.minecraft.world.WorldSettings$GameType", - // - }; - - private static final Set EXTENSIBLE_ENUMS = new HashSet<>(Arrays.asList(DEFAULT_EXTENSIBLE_ENUMS)); private static boolean configLoaded = false; public static boolean MIXIN_STBI_TEXTURE_LOADING = true; @@ -98,7 +55,7 @@ public class Config { public static Configuration config = null; - static void loadConfig() { + public static void loadConfig() { if (configLoaded) { return; } @@ -118,16 +75,6 @@ public class Config { } public static void reloadConfigObject() { - EXTENSIBLE_ENUMS.addAll( - Arrays.asList( - config - .get( - CATEGORY_CORE, - "extensibleEnums", - EXTENSIBLE_ENUMS.toArray(new String[0]), - "Enums to make extensible at runtime") - .getStringList())); - MIXIN_STBI_TEXTURE_LOADING = config.getBoolean( "stbiTextureLoading", CATEGORY_MIXIN, @@ -237,11 +184,11 @@ public class Config { } public static Set getExtensibleEnums() { - return EXTENSIBLE_ENUMS; + return EarlyConfig.EXTENSIBLE_ENUMS; } public static void addExtensibleEnum(String className) { - EXTENSIBLE_ENUMS.add(className); + EarlyConfig.EXTENSIBLE_ENUMS.add(className); } public static boolean isConfigLoaded() { diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/FixConstantPoolInterfaceMethodRefHelper.java b/src/main/java/me/eigenraven/lwjgl3ify/core/FixConstantPoolInterfaceMethodRefHelper.java deleted file mode 100644 index ec6167b..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/FixConstantPoolInterfaceMethodRefHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -package me.eigenraven.lwjgl3ify.core; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.objectweb.asm.Handle; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.InvokeDynamicInsnNode; -import org.objectweb.asm.tree.MethodNode; - -import me.eigenraven.lwjgl3ify.Lwjgl3ify; - -/** - * Fixes a compilation bug of the java 8 compiler leading to the following exception at runtime: - * cpw.mods.fml.common.LoaderException: java.lang.IncompatibleClassChangeError: Inconsistent constant pool data in - * classfile for class com/gtnewhorizon/structurelib/alignment/IAlignmentLimits. Method 'boolean - * lambda$static$0(net.minecraftforge.common.util.ForgeDirection, - * com.gtnewhorizon.structurelib.alignment.enumerable.Rotation, - * com.gtnewhorizon.structurelib.alignment.enumerable.Flip)' at index 77 is CONSTANT_MethodRef and should be - * CONSTANT_InterfaceMethodRef - */ -public class FixConstantPoolInterfaceMethodRefHelper { - - public boolean transform(ClassNode node) { - if (System.getProperty("java.specification.version", "1.8") - .trim() - .startsWith("1.8")) { - return false; - } - final boolean iAmAnInterface = ((node.access & Opcodes.ACC_INTERFACE) != 0); - boolean changesMade = false; - final String internalClassName = node.name; - if (node.methods != null) { - for (MethodNode method : node.methods) { - if (method.instructions != null) { - for (AbstractInsnNode insn : method.instructions) { - changesMade |= validateInstruction(internalClassName, iAmAnInterface, insn); - } - } - } - } - return changesMade; - } - - private boolean validateInstruction(String internalClassName, boolean iAmAnInterface, AbstractInsnNode rawInsn) { - AtomicBoolean changed = new AtomicBoolean(false); - switch (rawInsn.getType()) { - case AbstractInsnNode.INVOKE_DYNAMIC_INSN -> { - final InvokeDynamicInsnNode insn = (InvokeDynamicInsnNode) rawInsn; - insn.bsm = fixHandle(internalClassName, iAmAnInterface, insn.bsm, changed); - if (insn.bsmArgs != null) { - for (int i = 0; i < insn.bsmArgs.length; i++) { - final Object arg = insn.bsmArgs[i]; - if (arg instanceof Handle handle) { - insn.bsmArgs[i] = fixHandle(internalClassName, iAmAnInterface, handle, changed); - } - } - } - } - default -> {} - // no-op - } - return changed.get(); - } - - private Handle fixHandle(String internalClassName, boolean iAmAnInterface, Handle handle, AtomicBoolean changed) { - if (!handle.isInterface()) { - final boolean fixSelfReference = handle.getOwner() - .equals(internalClassName) && iAmAnInterface; - boolean fixJavaReference = false; - if (!fixSelfReference && handle.getOwner() - .startsWith("java/")) { - final String regularName = handle.getOwner() - .replace('/', '.'); - try { - final Class javaClass = Class.forName(regularName); - if (javaClass.isInterface()) { - fixJavaReference = true; - } - } catch (ClassNotFoundException cnfe) { - // no-op - Lwjgl3ify.LOG.warn("Reference to non-existing java class {} found.", regularName, cnfe); - } - } - if (fixSelfReference || fixJavaReference) { - changed.set(true); - return new Handle(handle.getTag(), handle.getOwner(), handle.getName(), handle.getDesc(), true); - } - } - return handle; - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/LateInit.java b/src/main/java/me/eigenraven/lwjgl3ify/core/LateInit.java new file mode 100644 index 0000000..a926774 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/core/LateInit.java @@ -0,0 +1,34 @@ +package me.eigenraven.lwjgl3ify.core; + +import java.awt.Toolkit; + +import org.lwjgl.system.Configuration; +import org.lwjgl.system.Platform; +import org.lwjglx.Sys; + +import cpw.mods.fml.relauncher.FMLLaunchHandler; + +public class LateInit { + + public static void lateConstruct() { + // Ensure javax.script.ScriptEngineManager gets loaded + try { + Class.forName("javax.script.ScriptEngineManager"); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + if (FMLLaunchHandler.side() + .isClient()) { + clientMacOsFix(); + Sys.initialize(); + } + } + + private static void clientMacOsFix() { + if (Platform.get() == Platform.MACOSX) { + Configuration.GLFW_LIBRARY_NAME.set("glfw_async"); + Configuration.GLFW_CHECK_THREAD0.set(false); + Toolkit.getDefaultToolkit(); // Initialize AWT before GLFW + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/Lwjgl3ifyCoremod.java b/src/main/java/me/eigenraven/lwjgl3ify/core/Lwjgl3ifyCoremod.java index ed3b7e1..5491579 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/Lwjgl3ifyCoremod.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/core/Lwjgl3ifyCoremod.java @@ -1,6 +1,5 @@ package me.eigenraven.lwjgl3ify.core; -import java.awt.Toolkit; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; @@ -13,11 +12,6 @@ import net.minecraft.launchwrapper.LaunchClassLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.lwjgl.system.Configuration; -import org.lwjgl.system.Platform; -import org.lwjglx.Sys; -import org.spongepowered.asm.launch.GlobalProperties; -import org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper; import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader; @@ -34,16 +28,6 @@ public class Lwjgl3ifyCoremod implements IFMLLoadingPlugin, IEarlyMixinLoader { Config.loadConfig(); try { LaunchClassLoader launchLoader = (LaunchClassLoader) getClass().getClassLoader(); - // Packages that used to be in rt.jar - launchLoader.addClassLoaderExclusion("com.sun"); - launchLoader.addClassLoaderExclusion("com.oracle"); - launchLoader.addClassLoaderExclusion("javax"); - launchLoader.addClassLoaderExclusion("jdk"); - launchLoader.addClassLoaderExclusion("org.ietf.jgss"); - launchLoader.addClassLoaderExclusion("org.jcp.xml.dsig.internal"); - launchLoader.addClassLoaderExclusion("org.omg"); - launchLoader.addClassLoaderExclusion("org.w3c.dom"); - launchLoader.addClassLoaderExclusion("org.xml.sax"); launchLoader.addClassLoaderExclusion("org.hotswap.agent"); launchLoader.addClassLoaderExclusion("org.lwjglx.debug"); } catch (ClassCastException e) { @@ -52,38 +36,15 @@ public class Lwjgl3ifyCoremod implements IFMLLoadingPlugin, IEarlyMixinLoader { .getClass(), e); } - // Ensure javax.script.ScriptEngineManager gets loaded - try { - Class.forName("javax.script.ScriptEngineManager"); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - if (FMLLaunchHandler.side() - .isClient()) { - clientMacOsFix(); - Sys.initialize(); - } - } - - private void clientMacOsFix() { - if (Platform.get() == Platform.MACOSX) { - Configuration.GLFW_LIBRARY_NAME.set("glfw_async"); - Configuration.GLFW_CHECK_THREAD0.set(false); - Toolkit.getDefaultToolkit(); // Initialize AWT before GLFW + if (Launch.blackboard.get("lwjgl3ify:rfb-booted") != Boolean.TRUE) { + return; } + LateInit.lateConstruct(); } @Override public String[] getASMTransformerClass() { - LOGGER.info("Registering lwjgl3ify redirect transformer"); - - List tweakClasses = GlobalProperties.get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKCLASSES); - if (tweakClasses != null) { - tweakClasses.add(PostMixinTransformInjector.class.getName()); - } - - return new String[] { LwjglRedirectTransformer.class.getName(), - UnfinalizeObjectHoldersTransformer.class.getName() }; + return new String[0]; } @Override @@ -118,11 +79,13 @@ public class Lwjgl3ifyCoremod implements IFMLLoadingPlugin, IEarlyMixinLoader { // FML Java 9+ compatibility patches mixins.add("fml.ItemStackHolderRef"); mixins.add("fml.JarDiscoverer"); - mixins.add("fml.ModVisitorAsmVersion"); mixins.add("fml.ObjectHolderRef"); mixins.add("fml.ObjectHolderRegistry"); if (FMLLaunchHandler.side() .isClient()) { + // Improved KeyBinding handling to handle dead keys + mixins.add("game.MixinMinecraftKeyBinding"); + // STB replacements for vanilla functions if (Config.MIXIN_STBI_TEXTURE_LOADING) { LOGGER.info("Enabling STB texture loading mixin"); diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/LwjglRedirectTransformer.java b/src/main/java/me/eigenraven/lwjgl3ify/core/LwjglRedirectTransformer.java deleted file mode 100644 index 562f47e..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/LwjglRedirectTransformer.java +++ /dev/null @@ -1,102 +0,0 @@ -package me.eigenraven.lwjgl3ify.core; - -import java.util.Arrays; -import java.util.stream.Stream; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.spongepowered.asm.lib.AnnotationVisitor; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassVisitor; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.commons.ClassRemapper; -import org.spongepowered.asm.lib.commons.Remapper; - -import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; - -public class LwjglRedirectTransformer extends Remapper implements IClassTransformer { - - int remaps = 0, calls = 0; - - public static LwjglRedirectTransformer activeInstance = null; - - public LwjglRedirectTransformer() { - // Only use the last constructed transformer - activeInstance = this; - excludedPackages = Stream.concat(Arrays.stream(fromPrefixes), Arrays.stream(toPrefixes)) - .map(s -> s.replace('/', '.')) - .toArray(String[]::new); - } - - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { - if (this != activeInstance) { - return basicClass; - } - if (basicClass == null) { - return null; - } - if (transformedName.contains("lwjgl3ify")) { - return basicClass; - } - for (String prefix : excludedPackages) { - if (transformedName.startsWith(prefix)) { - return basicClass; - } - } - ClassReader reader = new ClassReader(basicClass); - ClassWriter writer = new ClassWriter(0); - ClassVisitor visitor = new EscapingClassRemapper(writer); - - try { - reader.accept(visitor, ClassReader.EXPAND_FRAMES); - } catch (Lwjgl3AwareException e) { - return basicClass; - } catch (Exception e) { - Lwjgl3ifyCoremod.LOGGER.warn("Couldn't remap class {}", transformedName, e); - return basicClass; - } - - return writer.toByteArray(); - } - - final String[] fromPrefixes = new String[] { "org/lwjgl/", "javax/xml/bind/", "javax/servlet/" }; - final String[] excludedPackages; - - final String[] toPrefixes = new String[] { "org/lwjglx/", "jakarta/xml/bind/", "jakarta/servlet/" }; - - @Override - public String map(String typeName) { - if (typeName == null) { - return null; - } - calls++; - for (int pfx = 0; pfx < fromPrefixes.length; pfx++) { - if (typeName.startsWith(fromPrefixes[pfx])) { - remaps++; - return toPrefixes[pfx] + typeName.substring(fromPrefixes[pfx].length()); - } - } - - return typeName; - } - - public static class Lwjgl3AwareException extends RuntimeException { - } - - public class EscapingClassRemapper extends ClassRemapper { - - public EscapingClassRemapper(ClassWriter writer) { - super(writer, LwjglRedirectTransformer.this); - } - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - if (desc.equals(Type.getDescriptor(Lwjgl3Aware.class))) { - throw new Lwjgl3AwareException(); - } - return super.visitAnnotation(desc, visible); - } - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java b/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java deleted file mode 100644 index 4462461..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.eigenraven.lwjgl3ify.core; - -import java.io.File; -import java.util.List; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; - -/** - * Mixins inject themselves at the end of the asm transformer chain in the class loader via a ITweaker hack, we do the - * same for compatibility because lwjgl3ify has to run after mixins. - * - * @see org.spongepowered.asm.mixin.EnvironmentStateTweaker - * @see org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper - */ -public class PostMixinTransformInjector implements ITweaker { - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - // no-op - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) { - // no-op - } - - @Override - public String getLaunchTarget() { - // no-op - return null; - } - - @Override - public String[] getLaunchArguments() { - // Here we can inject ourselves - Launch.classLoader.registerTransformer(LwjglRedirectTransformer.class.getName()); - return new String[0]; - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/UnfinalizeObjectHoldersTransformer.java b/src/main/java/me/eigenraven/lwjgl3ify/core/UnfinalizeObjectHoldersTransformer.java deleted file mode 100644 index dc4d63a..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/UnfinalizeObjectHoldersTransformer.java +++ /dev/null @@ -1,121 +0,0 @@ -package me.eigenraven.lwjgl3ify.core; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldNode; - -import me.eigenraven.lwjgl3ify.WasFinalObjectHolder; - -public class UnfinalizeObjectHoldersTransformer implements IClassTransformer { - - // Keep ClassNode-operating transformers together for efficiency (don't read/write the class multiple times) - final ExtensibleEnumTransformerHelper enumTransformer = new ExtensibleEnumTransformerHelper(); - final FixConstantPoolInterfaceMethodRefHelper cpiMethodRefTransformer = new FixConstantPoolInterfaceMethodRefHelper(); - - private static boolean isHolder(List annotations) { - if (annotations == null) { - return false; - } - for (AnnotationNode annotationNode : annotations) { - // Java 17 uses $ instead of / - final String desc = annotationNode.desc.replace('$', '/'); - if (desc.contains("cpw/mods/fml/common/registry/GameRegistry/ObjectHolder")) { - return true; - } - if (desc.contains("cpw/mods/fml/common/registry/GameRegistry/ItemStackHolder")) { - return true; - } - } - return false; - } - - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { - if (basicClass == null) { - return null; - } - if (transformedName.startsWith("me.eigenraven.lwjgl3ify")) { - return basicClass; - } - try { - final ClassReader reader = new ClassReader(basicClass); - final ClassNode node = new ClassNode(); - reader.accept(node, ClassReader.EXPAND_FRAMES); - final Type classType = Type.getType("L" + name.replace('.', '/') + ";"); - - boolean transformClass = false; - boolean workDone = false; - if (transformedName.equals("net.minecraft.init.Blocks") - || transformedName.equals("net.minecraft.init.Items")) { - transformClass = true; - } - transformClass |= isHolder(node.visibleAnnotations); - if (transformedName.equals("team.chisel.init.ChiselBlocks")) { - Lwjgl3ifyCoremod.LOGGER.info("chiselblocks"); - } - int fieldsModified = 0; - for (FieldNode field : node.fields) { - boolean transform = transformClass; - if (!transform) { - transform = isHolder(field.visibleAnnotations); - } - if (transform) { - workDone = true; - if ((field.access & Opcodes.ACC_FINAL) != 0) { - if (field.visibleAnnotations == null) { - field.visibleAnnotations = new ArrayList<>(1); - field.visibleAnnotations - .add(new AnnotationNode(Type.getDescriptor(WasFinalObjectHolder.class))); - } - field.access = field.access & (~Opcodes.ACC_FINAL); - } - fieldsModified++; - } - } - if (workDone) { - Lwjgl3ifyCoremod.LOGGER.info("Unfinalized {} Holder fields in {}", fieldsModified, transformedName); - } - - if (Config.getExtensibleEnums() - .contains(transformedName)) { - if (node.interfaces == null) { - node.interfaces = new ArrayList<>(1); - } - node.interfaces.add(enumTransformer.MARKER_IFACE.getInternalName()); - } - - final boolean enumsTransformed = enumTransformer.processClassWithFlags(node, classType); - - if (enumsTransformed) { - workDone = true; - Lwjgl3ifyCoremod.LOGGER.info("Dynamicized enum {}={}", name, transformedName); - } - - final boolean ifaceMethodRefsTransformed = cpiMethodRefTransformer.transform(node); - - if (ifaceMethodRefsTransformed) { - workDone = true; - Lwjgl3ifyCoremod.LOGGER - .warn("Fixed missing CONSTANT_InterfaceMethodRef miscompilation in {}={}", name, transformedName); - } - - if (workDone) { - final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); - node.accept(writer); - return writer.toByteArray(); - } - } catch (Exception e) { - Lwjgl3ifyCoremod.LOGGER.error("Error when unfinalizing ObjectHolder transformer", e); - } - return basicClass; - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ItemStackHolderRef.java b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ItemStackHolderRef.java index 181e63f..1b904d2 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ItemStackHolderRef.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ItemStackHolderRef.java @@ -1,7 +1,5 @@ package me.eigenraven.lwjgl3ify.mixins.fml; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; import net.minecraft.item.ItemStack; @@ -31,8 +29,6 @@ public class ItemStackHolderRef { @Shadow(remap = false) private String serializednbt; - private static MethodHandle fieldSetter; - /** * @author eigenraven * @reason Simple helper function @@ -41,8 +37,6 @@ public class ItemStackHolderRef { private static void makeWritable(Field f) { try { f.setAccessible(true); - fieldSetter = MethodHandles.lookup() - .unreflectSetter(f); } catch (Exception e) { throw Throwables.propagate(e); } @@ -71,7 +65,7 @@ public class ItemStackHolderRef { throw e; } try { - fieldSetter.invoke(is); + field.set(null, is); } catch (Throwable e) { FMLLog.getLogger() .log( diff --git a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ModVisitorAsmVersion.java b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ModVisitorAsmVersion.java deleted file mode 100644 index 961cedc..0000000 --- a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ModVisitorAsmVersion.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.eigenraven.lwjgl3ify.mixins.fml; - -import org.objectweb.asm.Opcodes; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.Constant; -import org.spongepowered.asm.mixin.injection.ModifyConstant; - -import cpw.mods.fml.common.discovery.asm.ModAnnotationVisitor; -import cpw.mods.fml.common.discovery.asm.ModClassVisitor; -import cpw.mods.fml.common.discovery.asm.ModFieldVisitor; -import cpw.mods.fml.common.discovery.asm.ModMethodVisitor; - -@Mixin( - value = { ModClassVisitor.class, ModAnnotationVisitor.class, ModFieldVisitor.class, ModMethodVisitor.class }, - remap = false) -public class ModVisitorAsmVersion { - - @ModifyConstant(method = "*", constant = @Constant(intValue = Opcodes.ASM5), remap = false) - private static int lwjgl3ify$acceptNewerAsm(int original) { - return Opcodes.ASM9; - } -} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ObjectHolderRef.java b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ObjectHolderRef.java index e947167..4b24527 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ObjectHolderRef.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/ObjectHolderRef.java @@ -1,10 +1,9 @@ package me.eigenraven.lwjgl3ify.mixins.fml; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; import net.minecraft.init.Blocks; +import net.minecraft.util.RegistryNamespaced; import org.apache.logging.log4j.Level; import org.spongepowered.asm.mixin.Mixin; @@ -31,8 +30,6 @@ public class ObjectHolderRef { @Shadow(remap = false) private boolean isItem; - private MethodHandle fieldSetter = null; - /** * @author eigenraven * @reason Simple helper function @@ -52,24 +49,17 @@ public class ObjectHolderRef { */ @Overwrite(remap = false) public void apply() { - if (fieldSetter == null) { - try { - fieldSetter = MethodHandles.lookup() - .unreflectSetter(this.field); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } Object thing; + RegistryNamespaced registry; if (isBlock) { - thing = GameData.getBlockRegistry() - .getObject(injectedObject); + registry = GameData.getBlockRegistry(); + thing = registry.getObject(injectedObject); if (thing == Blocks.air) { thing = null; } } else if (isItem) { - thing = GameData.getItemRegistry() - .getObject(injectedObject); + registry = GameData.getItemRegistry(); + thing = registry.getObject(injectedObject); } else { thing = null; } @@ -84,7 +74,7 @@ public class ObjectHolderRef { return; } try { - fieldSetter.invoke(thing); + field.set(null, thing); FMLLog.finer("Set field " + field.toString() + " to " + thing); } catch (Throwable e) { FMLLog.log(Level.WARN, e, "Unable to set %s with value %s (%s)", this.field, thing, this.injectedObject); diff --git a/src/main/java/me/eigenraven/lwjgl3ify/mixins/game/MixinMinecraftKeyBinding.java b/src/main/java/me/eigenraven/lwjgl3ify/mixins/game/MixinMinecraftKeyBinding.java new file mode 100644 index 0000000..83c70b1 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/mixins/game/MixinMinecraftKeyBinding.java @@ -0,0 +1,23 @@ +package me.eigenraven.lwjgl3ify.mixins.game; + +import net.minecraft.client.Minecraft; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.Slice; + +/** + * Use raw key events for keybind handling to handle dead keys, etc. + */ +@Mixin(Minecraft.class) +public class MixinMinecraftKeyBinding { + + @Redirect( + method = "runTick", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/settings/KeyBinding;setKeyBindState(IZ)V"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lorg/lwjgl/input/Keyboard;next()Z", remap = false))) + private void lwjgl3ify$noKeybindUpdateHere(int eventKey, boolean eventKeyState) { + // Disable, handled in the client proxy + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/redirects/InvalidActivityException.java b/src/main/java/me/eigenraven/lwjgl3ify/redirects/InvalidActivityException.java new file mode 100644 index 0000000..598b6a7 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/redirects/InvalidActivityException.java @@ -0,0 +1,22 @@ +package me.eigenraven.lwjgl3ify.redirects; + +// Used by LiteLoader +@SuppressWarnings("unused") +public class InvalidActivityException extends java.rmi.RemoteException { + + public InvalidActivityException() { + super(); + } + + public InvalidActivityException(String message) { + super(message); + } + + public InvalidActivityException(Throwable cause) { + this("", cause); + } + + public InvalidActivityException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/redirects/LiteLoaderClassPathUtilities.java b/src/main/java/me/eigenraven/lwjgl3ify/redirects/LiteLoaderClassPathUtilities.java new file mode 100644 index 0000000..59b1e66 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/redirects/LiteLoaderClassPathUtilities.java @@ -0,0 +1,154 @@ +package me.eigenraven.lwjgl3ify.redirects; + +import java.io.File; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Paths; +import java.util.jar.JarFile; + +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; +import com.mumfrey.liteloader.launch.InjectionStrategy; + +import cpw.mods.fml.common.fakelwjgl3ify.SafeRuntimeExit; + +@SuppressWarnings("unused") // used by ASM +public abstract class LiteLoaderClassPathUtilities { + + private static Field ucp = null; + private static Field classPathURLs = null; + private static Field classPathPath = null; + private static Field classPathLoaderMap = null; + private static Field classPathLoaderList = null; + private static boolean canInject; + private static boolean canTerminate; + private static final MethodHandle rfg$addURL; + + static { + try { + final Class uclClass = URLClassLoader.class; + final Method addURL = uclClass.getDeclaredMethod("addURL", URL.class); + addURL.setAccessible(true); + // Allowed by our add-opens flags + rfg$addURL = MethodHandles.lookup() + .unreflect(addURL); + } catch (Throwable t) { + throw new RuntimeException(t); + } + } + + public static void injectIntoClassPath(URLClassLoader classLoader, URL url, InjectionStrategy strategy) { + addURL(classLoader, url); + } + + public static void injectIntoClassPath(URLClassLoader classLoader, URL url) { + addURL(classLoader, url); + } + + public static void injectIntoClassPath(URLClassLoader classLoader, URL url, URL above) { + addURL(classLoader, url); + } + + public static void injectIntoClassPath(URLClassLoader classLoader, URL url, String above) { + addURL(classLoader, url); + } + + public static void addURL(URLClassLoader classLoader, URL url) { + if (classLoader instanceof ExtensibleClassLoader) { + ((ExtensibleClassLoader) classLoader).addURL(url); + } else { + try { + rfg$addURL.invokeExact((URLClassLoader) classLoader, (URL) url); + } catch (Throwable t) { + // ignored + } + } + } + + public static boolean isJarOnClassPath(File jarFile) { + try { + String jarURL = jarFile.toURI() + .toURL() + .toString(); + URL[] classPath = RetroFuturaBootstrap.API.compatClassLoader() + .getURLs(); + + for (URL classPathEntry : classPath) { + if (classPathEntry.toString() + .equals(jarURL)) { + return true; + } + } + } catch (Exception e) { + e.printStackTrace(System.err); + } + return false; + } + + public static File getPathToResource(Class contextClass, String resource) { + URL res = contextClass.getResource(resource); + if (res == null) { + return null; + } else { + boolean returnParent = true; + String jarPath = res.toString(); + if (jarPath.startsWith("jar:") && jarPath.indexOf('!') > -1) { + jarPath = jarPath.substring(4, jarPath.indexOf('!')); + returnParent = false; + } + + if (jarPath.startsWith("file:")) { + try { + File targetFile = new File(new URI(jarPath)); + return returnParent ? targetFile.getParentFile() : targetFile; + } catch (URISyntaxException exc) { + // ignored + } + } + + return null; + } + } + + public static boolean deleteClassPathJarContaining(Class contextClass, String resource) { + return false; + } + + public static boolean deleteClassPathJar(String jarFileName) { + return false; + } + + public static void terminateRuntime(int status) { + if (canTerminate) { + SafeRuntimeExit.exitRuntime(status); + } else { + throw new IllegalStateException(); + } + } + + private static JarFile getJarFromClassLoader(URLClassLoader classLoader, String fileName, + boolean removeFromClassPath) { + try { + final URL[] urls = classLoader.getURLs(); + for (final URL url : urls) { + final URI uri = url.toURI(); + if (uri.getPath() + .endsWith(fileName)) { + final File f = Paths.get(uri) + .toFile(); + return new JarFile(f, false, JarFile.OPEN_READ); + } + } + } catch (Exception e) { + e.printStackTrace(System.err); + } + + return null; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/redirects/Pack200.java b/src/main/java/me/eigenraven/lwjgl3ify/redirects/Pack200.java new file mode 100644 index 0000000..8c4ddfd --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/redirects/Pack200.java @@ -0,0 +1,79 @@ +package me.eigenraven.lwjgl3ify.redirects; + +import java.beans.PropertyChangeListener; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.SortedMap; +import java.util.jar.JarOutputStream; + +import org.apache.commons.io.IOUtils; + +/** + * Redirection class for Java 8's java.util.jar.Pack200 classes. + */ +@SuppressWarnings("unused") // Used from asm +public class Pack200 { + + private Pack200() {} + + public static Unpacker newUnpacker() { + return new UnpackerImpl(); + } + + public interface Unpacker { + + String KEEP = "keep"; + String TRUE = "true"; + String FALSE = "false"; + String DEFLATE_HINT = "unpack.deflate.hint"; + String PROGRESS = "unpack.progress"; + + SortedMap properties(); + + void unpack(InputStream in, JarOutputStream out) throws IOException; + + void unpack(File in, JarOutputStream out) throws IOException; + + default void addPropertyChangeListener(PropertyChangeListener listener) {} + + default void removePropertyChangeListener(PropertyChangeListener listener) {} + } + + public static class UnpackerImpl implements Unpacker { + + public final org.apache.commons.compress.java.util.jar.Pack200.Unpacker parent; + + UnpackerImpl() { + parent = org.apache.commons.compress.java.util.jar.Pack200.newUnpacker(); + } + + @Override + public SortedMap properties() { + return parent.properties(); + } + + @Override + public void unpack(InputStream in, JarOutputStream out) throws IOException { + // The Apache library doesn't handle LzmaInputStreams well + final byte[] allData = IOUtils.toByteArray(in); + parent.unpack(new ByteArrayInputStream(allData), out); + } + + @Override + public void unpack(File in, JarOutputStream out) throws IOException { + parent.unpack(in, out); + } + + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + parent.addPropertyChangeListener(listener); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + parent.removePropertyChangeListener(listener); + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Downloader.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Downloader.java new file mode 100644 index 0000000..b326ba0 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Downloader.java @@ -0,0 +1,405 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.SystemUtils; +import org.jetbrains.annotations.NotNull; + +import com.google.common.base.Throwables; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class Downloader { + + public final @NotNull Path mavenCachePath; + private final AtomicInteger remainingTasks = new AtomicInteger(0); + private final List jarPaths = new ArrayList<>(); + private final List nativePaths = new ArrayList<>(); + private final List tasks = new ArrayList<>(); + private final ConcurrentLinkedDeque taskExceptions = new ConcurrentLinkedDeque<>(); + public final Set busyDownloads = Collections.newSetFromMap(new ConcurrentHashMap<>(8)); + + public Downloader(@NotNull Path mavenCachePath) { + this.mavenCachePath = Objects.requireNonNull(mavenCachePath); + } + + public int remainingTasks() { + return remainingTasks.get() + tasks.size(); + } + + public List jarPaths() { + return jarPaths; + } + + public List nativePaths() { + return nativePaths; + } + + @SuppressWarnings("deprecated") // Need to use deprecated Gson methods for compatibility + public void loadTasks() { + try { + String osFull = ""; + String os = ""; + String archBits = SystemUtils.OS_ARCH.contains("64") ? "64" : "32"; + final boolean isArm = SystemUtils.OS_ARCH.equalsIgnoreCase("aarch64") + || SystemUtils.OS_ARCH.toLowerCase(Locale.ROOT) + .startsWith("arm"); + if (SystemUtils.IS_OS_WINDOWS) { + osFull = isArm ? "windows-arm64" : "windows"; + os = "windows"; + } else if (SystemUtils.IS_OS_MAC) { + osFull = isArm ? "osx-arm64" : "osx"; + os = "osx"; + } else if (SystemUtils.IS_OS_LINUX) { + // There is also linux-arm32, but does anyone care? + osFull = isArm ? "linux-arm64" : "linux"; + os = "linux"; + } else { + throw new UnsupportedOperationException( + "Unknown operating system " + SystemUtils.OS_NAME + ":" + SystemUtils.OS_ARCH); + } + final JsonElement versionRoot; + try (final InputStream is = Downloader.class.getResourceAsStream("version.json"); + final BufferedInputStream bis = new BufferedInputStream(is); + final InputStreamReader rdr = new InputStreamReader(bis, StandardCharsets.UTF_8)) { + versionRoot = new JsonParser().parse(rdr); + } catch (Exception e) { + throw new RuntimeException(e); + } + final JsonArray libraries = versionRoot.getAsJsonObject() + .getAsJsonArray("libraries"); + for (final JsonElement libraryR : libraries) { + final JsonObject elLibrary = libraryR.getAsJsonObject(); + if (!passesRules(elLibrary, osFull)) { + continue; + } + final String elGav = elLibrary.getAsJsonPrimitive("name") + .getAsString(); + if (elLibrary.has("downloads")) { + final JsonObject elDownloads = elLibrary.getAsJsonObject("downloads"); + // URL artifact + if (elDownloads.has("artifact")) { + // No classifiers + final JsonObject elArtifact = elDownloads.getAsJsonObject("artifact"); + addArtifactDownload(elGav, elArtifact, tasks); + } else { + // Classifiers + final JsonObject elNatives = elLibrary.getAsJsonObject("natives"); + if (!elNatives.has(os)) { + continue; + } + final String classifier = elNatives.getAsJsonPrimitive(os) + .getAsString() + .replace("${arch}", archBits); + final JsonObject elClassifiers = elDownloads.getAsJsonObject("classifiers"); + if (!elClassifiers.has(classifier)) { + throw new IllegalStateException( + "Missing download for " + elGav + " classifier " + classifier); + } + final JsonObject elArtifact = elClassifiers.getAsJsonObject(classifier); + final DownloadTask task = addArtifactDownload(elGav + ":" + classifier, elArtifact, tasks); + nativePaths.add(task.targetLocation()); + } + } else { + // Maven artifact + final String elMavenUrl = elLibrary.getAsJsonPrimitive("url") + .getAsString(); + final GavCoords gav = new GavCoords(elGav); + if (gav.mArtifact.equals("lwjgl3ify")) { + continue; + } + + final String mURL = elMavenUrl + gav.mPath; + final Path path = mavenCachePath.resolve(gav.mPath); + final URL url = new URL(mURL); + jarPaths.add(path); + tasks.add(new DownloadTask(url, null, path)); + } + } + + // Add the minecraft client download + final JsonObject elClientDownload = versionRoot.getAsJsonObject() + .getAsJsonObject("downloads") + .getAsJsonObject("client"); + addArtifactDownload("net.minecraft:client:1.7.10", elClientDownload, tasks); + + for (Iterator it = tasks.iterator(); it.hasNext();) { + final DownloadTask task = it.next(); + if (Files.exists(task.targetLocation)) { + // already downloaded, skip + it.remove(); + } + } + } catch (Exception e) { + throw Throwables.propagate(e); + } + } + + public void runDownloads() { + final Path cacheLockPath = mavenCachePath.resolve("cache.lock"); + if (!Files.exists(cacheLockPath)) { + try { + Files.createFile(cacheLockPath); + } catch (FileAlreadyExistsException e) { + // ignored + } catch (IOException e) { + throw new RuntimeException(e); + } + } + try (final FileChannel cacheChannel = FileChannel.open(cacheLockPath, StandardOpenOption.WRITE)) { + FileLock cacheLock = cacheChannel.tryLock(); // released by closing the channel + if (cacheLock == null) { + Relauncher.logger.warn("Another process is already holding a lock on {}, waiting", cacheLockPath); + cacheLock = cacheChannel.lock(); + } + + final ExecutorService executor = Executors.newFixedThreadPool(4, r -> { + final Thread t = new Thread(r); + t.setName("Lwjgl3ify downloader"); + t.setDaemon(true); + return t; + }); + try { + remainingTasks.addAndGet(tasks.size()); + for (final DownloadTask task : tasks) { + executor.submit(() -> { + final String name = task.targetLocation() + .getFileName() + .toString(); + busyDownloads.add(name); + try { + task.download(); + } catch (Throwable e) { + taskExceptions.add(e); + } + busyDownloads.remove(name); + remainingTasks.decrementAndGet(); + }); + } + tasks.clear(); + executor.shutdown(); + if (!executor.awaitTermination(1, TimeUnit.DAYS)) { + throw new IllegalStateException("executor won't terminate"); + } + if (!taskExceptions.isEmpty()) { + Relauncher.logger.error("Exceptions happened during download task execution:"); + Throwable last = null; + while (!taskExceptions.isEmpty()) { + last = taskExceptions.removeFirst(); + Relauncher.logger.error("Download exception", last); + } + if (last != null) { + throw Throwables.propagate(last); + } + } + } finally { + executor.shutdownNow(); + } + + } catch (Exception e) { + throw Throwables.propagate(e); + } + } + + private DownloadTask addArtifactDownload(String name, JsonObject elArtifact, List tasks) + throws MalformedURLException, DecoderException { + final String elPath; + if (elArtifact.has("path")) { + elPath = elArtifact.getAsJsonPrimitive("path") + .getAsString(); + } else { + final GavCoords gav = new GavCoords(name); + elPath = gav.mPath; + } + final String elUrl = elArtifact.getAsJsonPrimitive("url") + .getAsString(); + final String elSha1 = elArtifact.getAsJsonPrimitive("sha1") + .getAsString(); + final URL url = new URL(elUrl); + final Path path = mavenCachePath.resolve(elPath); + final byte[] sha1 = Hex.decodeHex(elSha1.toCharArray()); + jarPaths.add(path); + final DownloadTask task = new DownloadTask(url, sha1, path); + tasks.add(task); + return task; + } + + private static boolean passesRules(final JsonObject library, final String os) { + if (library.has("rules")) { + final JsonArray elRules = library.getAsJsonArray("rules"); + boolean allowed = false; + for (final JsonElement ruleR : elRules) { + final JsonObject elRule = ruleR.getAsJsonObject(); + if (elRule.has("os")) { + final JsonObject elOs = elRule.getAsJsonObject("os"); + if (elOs.has("name")) { + final String elOsName = elOs.get("name") + .getAsString(); + if (!os.equals(elOsName)) { + continue; + } + } + } + if (elRule.has("action")) { + final String elAction = elRule.get("action") + .getAsString(); + switch (elAction) { + case "allow" -> allowed = true; + case "disallow" -> allowed = false; + default -> throw new IllegalStateException("Illegal rule action: " + elAction); + } + } + } + return allowed; + } else { + return true; + } + } + + public static final class GavCoords { + + public final String[] gav; + final String mGroup; + final String mArtifact; + final String mVersion; + final String mClassifier; + final String mGroupPath; + final String mFilename; + + final String mPath; + + public GavCoords(final String elGav) { + gav = elGav.split(":"); + mGroup = (gav.length > 2) ? gav[0] : ""; + mArtifact = (gav.length > 2) ? gav[1] : gav[0]; + mVersion = (gav.length > 2) ? gav[2] : gav[1]; + mClassifier = (gav.length > 3) ? gav[3] : ""; + mGroupPath = mGroup.replace('.', '/'); + + String mFilename = mArtifact; + if (!mVersion.isEmpty()) { + mFilename += '-' + mVersion; + } + if (!mClassifier.isEmpty()) { + mFilename += '-' + mClassifier; + } + mFilename += ".jar"; + this.mFilename = mFilename; + + mPath = mGroupPath + '/' + mArtifact + '/' + mVersion + '/' + mFilename; + } + } + + public static final class DownloadTask { + + private final URL sourceUrl; + private final byte[] checksum; + private final Path targetLocation; + + public DownloadTask(URL sourceUrl, byte[] checksum, Path targetLocation) { + this.sourceUrl = sourceUrl; + this.checksum = checksum; + this.targetLocation = targetLocation; + } + + public URL sourceUrl() { + return sourceUrl; + } + + public byte[] checksum() { + return checksum; + } + + public Path targetLocation() { + return targetLocation; + } + + public void download() throws IOException { + final Path targetDir = targetLocation.getParent(); + + Files.createDirectories(targetDir); + Files.deleteIfExists(targetLocation); + + byte[] data = null; + Relauncher.logger.info("Downloading {} from {}", targetLocation, sourceUrl); + for (int retries = 0; retries < 5; retries++) { + try { + data = IOUtils.toByteArray(sourceUrl); + if (checksum != null) { + final byte[] dataSum = DigestUtils.sha1(data); + if (!Arrays.equals(dataSum, checksum)) { + throw new RuntimeException("Checksum mismatch for " + targetLocation); + } + } + } catch (Exception e) { + if (retries != 4) { + continue; + } else { + throw e; + } + } + } + Objects.requireNonNull(data); + Files.write(targetLocation, data); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (DownloadTask) obj; + return Objects.equals(this.sourceUrl, that.sourceUrl) && Arrays.equals(this.checksum, that.checksum) + && Objects.equals(this.targetLocation, that.targetLocation); + } + + @Override + public int hashCode() { + return Objects.hash(sourceUrl, Arrays.hashCode(checksum), targetLocation); + } + + @Override + public String toString() { + return "DownloadTask[" + "sourceUrl=" + + sourceUrl + + ", " + + "checksum=" + + checksum + + ", " + + "targetLocation=" + + targetLocation + + ']'; + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/JvmLocator.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/JvmLocator.java new file mode 100644 index 0000000..c1101e9 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/JvmLocator.java @@ -0,0 +1,222 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.SystemUtils; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +/** + * Locates JVM installations in standard OS paths. + * Standard paths collected from Gradle's + * installation suppliers + */ +public final class JvmLocator { + + private JvmLocator() {} + + /** @return List of paths to executable java(w.exe) binaries */ + public static List detectJavaInstalls(List cache) { + final ArrayList out = new ArrayList<>(); + + for (final String cacheEntry : cache) { + final Path p = Paths.get(cacheEntry); + if (Files.isRegularFile(p)) { + out.add(p); + } + } + + if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_FREE_BSD) { + try { + searchLinuxDirs(out); + } catch (Throwable t) { + Relauncher.logger.warn("Could not scan JVM homes", t); + } + } + + if (SystemUtils.IS_OS_MAC) { + try { + searchMacJavaHomes(out); + } catch (Throwable t) { + Relauncher.logger.warn("Could not scan JVM homes", t); + } + } + + if (SystemUtils.IS_OS_WINDOWS) { + try { + searchWindowsRegistry(out); + } catch (Throwable t) { + Relauncher.logger.warn("Could not scan JVM homes", t); + } + } + + Collections.sort(out); + return Lists.newArrayList(Sets.newLinkedHashSet(out)); + } + + private static final boolean IS_UNIXY = !SystemUtils.IS_OS_WINDOWS; + private static final Function BIN_JAVA_RESOLVER = IS_UNIXY ? (p -> p.resolve("bin") + .resolve("java")) + : (p -> p.resolve("bin") + .resolve("javaw.exe")); + + // Finds subdirectories with bin/java executables + private static void searchDirs(List out, String... dirs) { + for (final String dir : dirs) { + final Path path = Paths.get(dir); + if (!Files.isDirectory(path)) { + continue; + } + final Path simpleChild = BIN_JAVA_RESOLVER.apply(path); + if (Files.isRegularFile(simpleChild)) { + out.add(simpleChild); + } + try (final Stream children = Files.list(path)) { + children.forEach(child -> { + final Path binJava = BIN_JAVA_RESOLVER.apply(child); + if (Files.isRegularFile(binJava)) { + out.add(binJava); + } + }); + } catch (IOException e) { + // ignored + } + } + } + + private static void searchLinuxDirs(List out) { + searchDirs(out, "/usr/lib/jvm", "/usr/lib/java", "/usr/java", "/usr/local/java", "/opt/java"); + if (!Files.isSymbolicLink(Paths.get("/usr/lib64"))) { + searchDirs(out, "/usr/lib64/jvm", "/usr/lib64/java"); + } + } + + private static final Pattern OSX_INSTALLATION_PATTERN = Pattern.compile(".+\\s+(/.+)"); + + private static void searchMacJavaHomes(List out) { + final String[] cmdOut = getProcessOutput("/usr/libexec/java_home", "-V").split("\n"); + for (final String outLine : cmdOut) { + final Matcher matcher = OSX_INSTALLATION_PATTERN.matcher(outLine); + if (matcher.matches()) { + final String javaHome = matcher.group(1); + final Path binJava = BIN_JAVA_RESOLVER.apply(Paths.get(javaHome)); + if (Files.isRegularFile(binJava)) { + out.add(binJava); + } + } + } + } + + private static void searchWindowsRegistry(List out) { + // OpenJDK candidates + final List javaHomes = new ArrayList<>(); + Stream.of("SOFTWARE\\AdoptOpenJDK\\JDK", "SOFTWARE\\Eclipse Adoptium\\JDK", "SOFTWARE\\Eclipse Foundation\\JDK") + .forEach(p -> javaHomes.addAll(scanRegistryJvms(p, "\\hotspot\\MSI", "Path"))); + // Other JDKs + Stream + .of( + "SOFTWARE\\JavaSoft\\JDK", + "SOFTWARE\\JavaSoft\\Java Development Kit", + "SOFTWARE\\JavaSoft\\Java Runtime Environment", + "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Development Kit", + "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment") + .forEach(p -> javaHomes.addAll(scanRegistryJvms(p, "", "JavaHome"))); + for (final String javaHome : javaHomes) { + final Path binJava = BIN_JAVA_RESOLVER.apply(Paths.get(javaHome)); + if (Files.isRegularFile(binJava)) { + out.add(binJava); + } + } + } + + private static List scanRegistryJvms(String sdkSubkey, String path, String value) { + return getRegistrySubkeys("HKLM\\" + sdkSubkey).stream() + .map(withVersion -> getRegistryKey(withVersion + path, value)) + .collect(Collectors.toList()); + } + + private static String getRegistryKey(String location, String key) { + final String out = getProcessOutput("REG.EXE", "QUERY", location, "/v", key); + if (out.isEmpty()) { + return null; + } + if (!out.contains(key)) { + return null; + } + for (String line : out.split("\n")) { + // key[spaces]REG_type[spaces]value + line = line.trim(); + if (line.isEmpty()) { + continue; + } + if (!line.startsWith(key)) { + continue; + } + line = line.substring(key.length()) + .trim(); + final String firstWord = line.split("\\s+")[0]; + line = line.substring(firstWord.length()) + .trim(); + return line; + } + return null; + } + + // HKCU\a -> HKCU\a\b, HKCU\a\c, ... + private static List getRegistrySubkeys(String location) { + final String out = getProcessOutput("REG.EXE", "QUERY", location); + if (out.isEmpty()) { + return Collections.emptyList(); + } + final String sublocationPrefix = location + '\\'; + if (!out.contains(sublocationPrefix)) { + return Collections.emptyList(); + } + final List ret = new ArrayList<>(); + for (String line : out.split("\n")) { + // key[spaces]REG_type[spaces]value + line = line.trim(); + if (line.isEmpty()) { + continue; + } + if (!line.startsWith(sublocationPrefix)) { + continue; + } + ret.add(line); + } + return ret; + } + + private static String getProcessOutput(String... cmd) { + try { + final ProcessBuilder pb = new ProcessBuilder(cmd).redirectOutput(ProcessBuilder.Redirect.PIPE) + .redirectError(ProcessBuilder.Redirect.PIPE); + pb.environment() + .remove("JAVA_VERSION"); + final Process p = pb.start(); + String stdout = IOUtils.toString(p.getInputStream()) + "\n" + IOUtils.toString(p.getErrorStream()); + final int ec = p.waitFor(); + if (ec != 0) { + return ""; + } + return stdout.trim(); + } catch (IOException | InterruptedException e) { + return ""; + } + } + +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Lwjgl3ifyRelauncherTweaker.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Lwjgl3ifyRelauncherTweaker.java new file mode 100644 index 0000000..d6f692b --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Lwjgl3ifyRelauncherTweaker.java @@ -0,0 +1,127 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.file.Paths; +import java.util.List; + +import net.minecraft.launchwrapper.ITweaker; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; + +import org.apache.logging.log4j.LogManager; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.CoreModManager; +import cpw.mods.fml.relauncher.FMLLaunchHandler; +import cpw.mods.fml.relauncher.FMLRelaunchLog; + +public class Lwjgl3ifyRelauncherTweaker implements ITweaker { + + private static boolean coremodInjected = false; + + public Lwjgl3ifyRelauncherTweaker() { + // Load early in prod, late in dev to avoid a crash + if (FMLLaunchHandler.side() != null) { + injectMyCoremod(); + } + } + + private void injectMyCoremod() { + if (coremodInjected) { + return; + } + try { + URL mySrc = Lwjgl3ifyRelauncherTweaker.class.getProtectionDomain() + .getCodeSource() + .getLocation(); + while (mySrc.getProtocol() + .equals("jar")) { + final String all = mySrc.toString(); + mySrc = new URL(all.substring("jar:".length(), all.lastIndexOf('!'))); + } + File myFile = new File("."); + if (mySrc.getProtocol() + .equals("file")) { + myFile = Paths.get(mySrc.toURI()) + .toFile(); + } + final String coreModName = myFile.getName(); + boolean isReparseable = !System.getProperty("java.class.path") + .contains(coreModName); + FMLRelaunchLog.log.getLogger() + .info("Lwjgl3ify reparseable status: {} (name: {})", isReparseable, coreModName); + // If this tweaker is loaded, FML skips loading the coremod by default. + Launch.classLoader.addTransformerExclusion("me.eigenraven.lwjgl3ify.core.Lwjgl3ifyCoremod"); + final Class cmmClass = (Class) Class + .forName("cpw.mods.fml.relauncher.CoreModManager", true, Launch.classLoader); + + if (isReparseable) { + final Method cmmGetReparseableCoremods = cmmClass.getMethod("getReparseableCoremods"); + final Method cmmGetLoadedCoremods = cmmClass.getMethod("getLoadedCoremods"); + final List reparseableCoremods = (List) cmmGetReparseableCoremods.invoke(null); + final List loadedCoremods = (List) cmmGetLoadedCoremods.invoke(null); + if (loadedCoremods.remove(coreModName)) { + FMLRelaunchLog.log.getLogger() + .info("Removed lwjgl3ify from the list of non-mod coremods"); + } + if (!reparseableCoremods.contains(coreModName)) { + reparseableCoremods.add(coreModName); + } + } + + final Method cmmAddCoremod = cmmClass + .getDeclaredMethod("loadCoreMod", LaunchClassLoader.class, String.class, File.class); + cmmAddCoremod.setAccessible(true); + cmmAddCoremod.invoke(null, Launch.classLoader, "me.eigenraven.lwjgl3ify.core.Lwjgl3ifyCoremod", myFile); + coremodInjected = true; + } catch (InvocationTargetException e) { + if (e.getCause() instanceof RuntimeException re) { + throw re; + } else { + throw new RuntimeException(e); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + if (Launch.blackboard.get("lwjgl3ify:rfb-booted") != Boolean.TRUE) { + if (FMLLaunchHandler.side() + .isServer()) { + LogManager.getLogger() + .fatal( + "lwjgl3ify relauncher does not support server launches, install according to lwjgl3ify's README."); + FMLCommonHandler.instance() + .exitJava(1, false); + } + // Not launched via RFB, transfer control to the relauncher. + try { + new Relauncher(args.toArray(new String[0]), profile).run(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + injectMyCoremod(); + } + + @Override + public String getLaunchTarget() { + return null; + } + + @Override + public String[] getLaunchArguments() { + return new String[0]; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.form b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.form new file mode 100644 index 0000000..7454b02 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.form @@ -0,0 +1,64 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.java new file mode 100644 index 0000000..881a0b8 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/ProgressDialog.java @@ -0,0 +1,107 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.ResourceBundle; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JProgressBar; + +public class ProgressDialog { + + public JProgressBar progressBar; + public JButton cancelButton; + public JLabel statusLabel; + public JPanel panel; + public JLabel filesLabel; + + public void loadTranslations() { + final ResourceBundle bundle = ResourceBundle.getBundle("me.eigenraven.lwjgl3ify.relauncher.TranslationsBundle"); + statusLabel.setText(bundle.getString(TranslationsBundle.KEY_PROGRESS_DOWNLOADING_HEADER)); + cancelButton.setText(bundle.getString(TranslationsBundle.KEY_CANCEL)); + } + + { + // GUI initializer generated by IntelliJ IDEA GUI Designer + // >>> IMPORTANT!! <<< + // DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR call it in your + * code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + progressBar = new JProgressBar(); + GridBagConstraints gbc; + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 2; + gbc.gridwidth = 2; + gbc.weightx = 1.0; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.insets = new Insets(0, 16, 0, 16); + panel.add(progressBar, gbc); + final JPanel spacer1 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 3; + gbc.fill = GridBagConstraints.VERTICAL; + panel.add(spacer1, gbc); + cancelButton = new JButton(); + cancelButton.setText("KEY_CANCEL"); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 5; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.insets = new Insets(0, 0, 16, 16); + panel.add(cancelButton, gbc); + statusLabel = new JLabel(); + statusLabel.setText("KEY_PROGRESS_DOWNLOADING_HEADER"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 1; + gbc.gridwidth = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(0, 16, 8, 0); + panel.add(statusLabel, gbc); + final JPanel spacer2 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 4; + gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.VERTICAL; + panel.add(spacer2, gbc); + final JPanel spacer3 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.VERTICAL; + panel.add(spacer3, gbc); + filesLabel = new JLabel(); + filesLabel.setText(""); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 5; + gbc.weightx = 1.0; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(0, 16, 0, 16); + panel.add(filesLabel, gbc); + } + + /** @noinspection ALL */ + public JComponent $$$getRootComponent$$$() { + return panel; + } + +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Relauncher.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Relauncher.java new file mode 100644 index 0000000..6b80d3a --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/Relauncher.java @@ -0,0 +1,292 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import net.minecraft.launchwrapper.Launch; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.fakelwjgl3ify.SafeRuntimeExit; +import me.eigenraven.lwjgl3ify.Tags; + +public class Relauncher { + + static final Logger logger = LogManager.getLogger("Lwjgl3ify/Relauncher"); + static final String[] SYSTEM_PROPERTY_PREFIXES = new String[] { "java.", "os.", "path.", "file.", "line.", "user.", + "native.", "com.sun.", "sun.", "awt.", }; + static final String[] RECOMMENDED_JAVA_ARGS = Tags.RECOMMENDED_JAVA_ARGS.split("\t"); + final Path osCache; + final Path mavenDownloadPath; + final String[] args; + final String gameVersion; + final Downloader downloader; + final RelauncherUserInterface gui; + Path forgePatchesJarPath; + + public void runtimeExit(int exitCode) { + SafeRuntimeExit.exitRuntime(exitCode); + } + + public Relauncher(String[] args, String gameVersion) { + this.args = args; + this.gameVersion = gameVersion; + + final String userHome = System.getProperty("user.home"); + final String system = System.getProperty("os.name") + .toLowerCase(); + Path cacheDir; + try { + if (system.contains("win")) { + String temp = System.getenv("TEMP"); + String localAppData = System.getenv("LOCALAPPDATA"); + if (temp != null) { + cacheDir = Paths.get(temp, "lwjgl3ify"); + } else if (localAppData != null) { + cacheDir = Paths.get(localAppData, "Temp", "lwjgl3ify"); + } else { + cacheDir = Paths.get(userHome, "AppData", "Local", "Temp", "lwjgl3ify"); + } + } else if (system.contains("mac")) { + cacheDir = Paths.get(userHome, "Library", "Caches", "lwjgl3ify"); + } else { + String xdgCacheHome = System.getenv("XDG_CACHE_HOME"); + if (xdgCacheHome == null) { + cacheDir = Paths.get(userHome, ".cache", "lwjgl3ify"); + } else { + cacheDir = Paths.get(xdgCacheHome, "lwjgl3ify"); + } + } + } catch (InvalidPathException e) { + if (system.contains("win")) { + cacheDir = Paths.get(userHome, "AppData", "Local", "Temp", "lwjgl3ify"); + } else { + cacheDir = Paths.get(userHome, ".cache", "lwjgl3ify"); + } + logger.warn( + "An error occurred while the lwjgl3ify relauncher cache path was created. The environment variable TEMP or LOCALAPPDATA could be set incorrectly. Using the default cache location: {}", + cacheDir, + e); + } + osCache = cacheDir; + + final String mavenDownloadRoot = System.getProperty("lwjgl3ify.relauncher.mavenDownloadRoot", ""); + final Path mavenDownloadPath; + if (mavenDownloadRoot.isEmpty()) { + mavenDownloadPath = osCache.resolve("maven"); + } else { + mavenDownloadPath = Paths.get(mavenDownloadRoot); + } + if (!Files.isDirectory(mavenDownloadPath)) { + try { + Files.createDirectories(mavenDownloadPath); + } catch (IOException e) { + logger.fatal("Could not create Maven download cache at {}", mavenDownloadPath, e); + FMLCommonHandler.instance() + .exitJava(1, false); + } + } + this.mavenDownloadPath = mavenDownloadPath; + RelauncherConfig.load(); + + this.gui = new RelauncherUserInterface(this); + + downloader = new Downloader(mavenDownloadPath); + downloader.loadTasks(); + final int dlTasks = downloader.remainingTasks(); + if (dlTasks > 0) { + logger.info("We need to download {} libraries into the cache at {}", dlTasks, mavenDownloadPath); + gui.downloadWithGui(downloader); + } else { + logger.info("All libraries found in the cache at {}", mavenDownloadPath); + } + } + + public List createClasspath() { + final List classpath = new ArrayList<>(); + try { + // Extract RFB&libraries jar + final byte[] forgePatchesData = IOUtils.toByteArray( + Objects.requireNonNull( + Relauncher.class.getResourceAsStream("forgePatches.zip"), + "missing bundled forgePatches jar")); + final String forgePatchesDigest = DigestUtils.sha256Hex(forgePatchesData); + final Path jarsDir = mavenDownloadPath.getParent() + .resolve("jars"); + Files.createDirectories(jarsDir); + final Path jarFile = jarsDir.resolve("forgePatches-" + forgePatchesDigest + ".jar"); + if (!Files.exists(jarFile)) { + logger.info("Extracting bundled early classpath libraries to {}", jarFile); + Files.write(jarFile, forgePatchesData, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + } else { + logger.info("Using previously extracted bundled early classpath libraries from {}", jarFile); + } + classpath.add(jarFile.toString()); + this.forgePatchesJarPath = jarFile; + } catch (IOException e) { + throw new RuntimeException(e); + } + for (final Path cpFile : downloader.jarPaths()) { + if (!Files.exists(cpFile)) { + continue; + } + classpath.add( + cpFile.toAbsolutePath() + .toString()); + } + return classpath; + } + + private static long getCurrentPid() { + final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); + // getName is implemented to return getPid() + "@" + hostname + final String combinedPidHostname = runtime.getName(); + final String[] parts = combinedPidHostname.split("@", 2); + return Integer.parseInt(parts[0]); + } + + @SuppressWarnings("deprecation") + public void run() throws IOException { + gui.startSettingsIfNeeded(); + if (!gui.runClicked) { + runtimeExit(0); + return; + } + + URL myJarUrl = Relauncher.class.getProtectionDomain() + .getCodeSource() + .getLocation(); + // In case of broken LW-like classloaders that pass in jar: urls as the code source + while ("jar".equalsIgnoreCase(myJarUrl.getProtocol())) { + final String str = myJarUrl.toString(); + myJarUrl = new URL(str.substring(4, str.lastIndexOf('!'))); + } + final Path myJarPath; + try { + myJarPath = Paths.get(myJarUrl.toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + + final List cmd = new ArrayList<>(); + cmd.addAll(Arrays.asList(RECOMMENDED_JAVA_ARGS)); + cmd.addAll(RelauncherConfig.config.toJvmArgs()); + cmd.add("-cp"); + cmd.add(StringUtils.join(createClasspath(), File.pathSeparatorChar)); + // Forward any custom system properties + outer: for (final Map.Entry prop : System.getProperties() + .entrySet()) { + if (prop.getKey() == null || prop.getValue() == null) { + continue; + } + final String key = prop.getKey() + .toString(); + for (final String systemPrefix : SYSTEM_PROPERTY_PREFIXES) { + if (key.startsWith(systemPrefix)) { + continue outer; + } + } + final String value = prop.getValue() + .toString(); + cmd.add("-D" + key + "=" + value); + } + + cmd.add("com.gtnewhorizons.retrofuturabootstrap.Main"); + + cmd.addAll( + Arrays.asList( + "--version", + gameVersion, + "--gameDir", + Launch.minecraftHome.toString(), + "--assetsDir", + Launch.assetsDir.toString(), + "--tweakClass", + "cpw.mods.fml.common.launcher.FMLTweaker")); + cmd.addAll(Arrays.asList(args)); + + final Path argFile = Files.createTempFile("lwjgl3ify-relaunch-", ".arg"); + Files.write( + argFile, + cmd.stream() + .map(c -> '"' + StringEscapeUtils.escapeJava(c) + '"') + .collect(Collectors.toList()), + StandardCharsets.UTF_8); + + final List bootstrapCmd = new ArrayList<>(); + final String[] javas = RelauncherConfig.config.javaInstallationsCache; + final int javaIdx = RelauncherConfig.config.javaInstallation; + final String javaPath; + if (javaIdx < 0 || javaIdx >= javas.length) { + javaPath = SystemUtils.IS_OS_WINDOWS ? "javaw" : "java"; + } else { + javaPath = javas[javaIdx]; + } + bootstrapCmd.add(javaPath); + if (RelauncherConfig.config.forwardLogs) { + bootstrapCmd.add("@" + argFile); + } else { + bootstrapCmd.add("-Xms16M"); + bootstrapCmd.add("-Xmx256M"); + bootstrapCmd.add("-cp"); + bootstrapCmd.add(forgePatchesJarPath + File.pathSeparator + myJarPath); + bootstrapCmd.add("--disable-@files"); + bootstrapCmd.add("me.eigenraven.lwjgl3ify.relauncherstub.RelauncherStubMain"); + bootstrapCmd.add(Long.toString(getCurrentPid())); + bootstrapCmd.add("true"); + bootstrapCmd.add(javaPath); + bootstrapCmd.add("@" + argFile); + } + + final ProcessBuilder pb = new ProcessBuilder(bootstrapCmd); + pb.inheritIO(); + if (!RelauncherConfig.config.forwardLogs) { + pb.redirectOutput(ProcessBuilder.Redirect.PIPE); + } + logger.info("Starting relaunched process using args {}", bootstrapCmd); + final Process p = pb.start(); + if (RelauncherConfig.config.forwardLogs) { + while (p.isAlive()) { + try { + p.waitFor(); + break; + } catch (InterruptedException e) { + continue; + } + } + runtimeExit(p.exitValue()); + } else { + // Wait for the "quit" message from the child process + try { + p.getInputStream() + .read(new byte[6]); + } catch (IOException e) { + // ignored + } + runtimeExit(0); + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherConfig.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherConfig.java new file mode 100644 index 0000000..280fdc3 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherConfig.java @@ -0,0 +1,184 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.minecraft.launchwrapper.Launch; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class RelauncherConfig { + + public enum GCOption { + + G1GC(new String[] { "-XX:+UseG1GC" }), + ZGC(new String[] { "-XX:+UseZGC" }), + Shenandoah(new String[] { "-XX:+UseShenandoahGC" }), + GenerationalZGC(new String[] { "-XX:+UseZGC", "-XX:+ZGenerational" }), + Custom(new String[] {}); + + public final String[] FLAGS; + + GCOption(String[] flags) { + FLAGS = flags; + } + } + + public static class ConfigObject { + + public ConfigObject() {} + + // Basic + public String[] javaInstallationsCache = new String[0]; + public int javaInstallation = 0; + public int minMemoryMB = 512; + public int maxMemoryMB = 4096; + public GCOption garbageCollector = GCOption.G1GC; + public String[] customOptions = new String[0]; + // Advanced + public boolean forwardLogs = false; + public boolean allowDebugger = false; + public boolean waitForDebugger = false; + public boolean mixinDebug = false; + public boolean mixinDebugExport = false; + public boolean mixinDebugCount = false; + public boolean fmlDebugAts = false; + public boolean rfbDumpClasses = false; + public boolean rfbDumpPerTransformer = false; + + public void setCustomOptionsFromQuotedString(final String input) { + final List tokens = new ArrayList<>(); + final StringBuilder tokenBuilder = new StringBuilder(); + boolean inQuotes = false; + for (int i = 0; i < input.length(); i++) { + final char c = input.charAt(i); + final char peek = (i == input.length() - 1) ? '\0' : input.charAt(i + 1); + if (!inQuotes && Character.isWhitespace(c)) { + if (tokenBuilder.length() != 0) { + tokens.add(tokenBuilder.toString()); + tokenBuilder.delete(0, tokenBuilder.length()); + } + } else if (c == '\\' && peek != '\0') { + tokenBuilder.append(peek); + i++; + } else if (c == '"') { + inQuotes = !inQuotes; + } else { + tokenBuilder.append(c); + } + } + if (tokenBuilder.length() != 0) { + tokens.add(tokenBuilder.toString()); + tokenBuilder.delete(0, tokenBuilder.length()); + } + this.customOptions = tokens.toArray(new String[0]); + } + + public String customOptionsToQuotedString() { + final StringBuilder out = new StringBuilder(); + for (final String arg : this.customOptions) { + final String escaped = arg.replace("\\", "\\\\") + .replace("\"", "\\\""); + if (escaped.chars() + .anyMatch(Character::isWhitespace)) { + out.append('"'); + out.append(escaped); + out.append('"'); + } else { + out.append(escaped); + } + out.append('\n'); + } + return out.toString(); + } + + public List toJvmArgs() { + final List out = new ArrayList<>(); + if (minMemoryMB > 0) { + out.add("-Xms" + minMemoryMB + "M"); + } + if (maxMemoryMB > 0) { + out.add("-Xmx" + maxMemoryMB + "M"); + } + out.addAll(Arrays.asList(garbageCollector.FLAGS)); + if (allowDebugger) { + out.add( + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=" + (waitForDebugger ? 'y' : 'n') + + ",address=5005"); + } + if (mixinDebug) { + out.add("-Dmixin.debug=true"); + } + if (mixinDebugExport) { + out.add("-Dmixin.debug.export=true"); + } + if (mixinDebugCount) { + out.add("-Dmixin.debug.countInjections=true"); + } + if (fmlDebugAts) { + out.add("-Dfml.debugAccessTransformer=true"); + } + if (rfbDumpClasses) { + out.add("-Drfb.dumpLoadedClasses=true"); + } + if (rfbDumpPerTransformer) { + out.add("-Drfb.dumpLoadedClassesPerTransformer=true"); + } + for (final String arg : customOptions) { + if (arg == null || arg.trim() + .isEmpty()) { + continue; + } + out.add(arg.trim()); + } + return out; + } + } + + public static ConfigObject config = new ConfigObject(); + private static final Gson gson = new GsonBuilder().setPrettyPrinting() + .create(); + + public static void load() { + final Path gamePath = (Launch.minecraftHome == null) ? Paths.get(".") : Launch.minecraftHome.toPath(); + final Path earlyConfigPath = gamePath.resolve("config") + .resolve("lwjgl3ify-relauncher.json"); + + if (Files.exists(earlyConfigPath)) { + try { + final String configContents = new String(Files.readAllBytes(earlyConfigPath), StandardCharsets.UTF_8); + config = gson.fromJson(configContents, ConfigObject.class); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + if (config.javaInstallationsCache.length > 0) { + config.javaInstallation = Math + .max(0, Math.min(config.javaInstallation, config.javaInstallationsCache.length - 1)); + } + + save(); + } + + public static void save() { + final Path gamePath = (Launch.minecraftHome == null) ? Paths.get(".") : Launch.minecraftHome.toPath(); + final Path earlyConfigPath = gamePath.resolve("config") + .resolve("lwjgl3ify-relauncher.json"); + + final String jsonCfg = gson.toJson(config); + try { + Files.createDirectories(earlyConfigPath.getParent()); + Files.write(earlyConfigPath, jsonCfg.getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherUserInterface.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherUserInterface.java new file mode 100644 index 0000000..dc4acc3 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/RelauncherUserInterface.java @@ -0,0 +1,347 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.lang.management.ManagementFactory; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.swing.ComboBoxModel; +import javax.swing.DefaultComboBoxModel; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.filechooser.FileFilter; +import javax.swing.text.DefaultEditorKit; + +import org.apache.commons.lang3.StringUtils; + +import com.github.weisj.darklaf.LafManager; +import com.github.weisj.darklaf.theme.spec.ColorToneRule; +import com.github.weisj.darklaf.theme.spec.ContrastRule; +import com.github.weisj.darklaf.theme.spec.PreferredThemeStyle; +import com.google.common.base.Throwables; + +/** Implements the UI components of the relauncher */ +/* + * Dev note on recompiling forms: + * 1. Import into IntelliJ as a gradle project + * 2. In gradle settings, change Build with: from Gradle to IntelliJ + * 3. Open the .form file in the form editor and use the main menu Build->Recompile 'currentfile.form' function + * 4. You might have to remove the build/libs and build/distributions files afterwards, IntelliJ messes with Gradle's + * caching + */ +public class RelauncherUserInterface { + + private final Relauncher relauncher; + private boolean swingInitialized = false; + public boolean runClicked = false; + + public RelauncherUserInterface(Relauncher relauncher) { + this.relauncher = relauncher; + } + + // Only call from the Swing thread + private void initSwingIfNeeded() { + if (swingInitialized) { + return; + } + swingInitialized = true; + final ClassLoader original = Thread.currentThread() + .getContextClassLoader(); + final ClassLoader mcLoader = RelauncherUserInterface.class.getClassLoader(); + Thread.currentThread() + .setContextClassLoader(mcLoader); + try { + System.setProperty("awt.useSystemAAFontSettings", "on"); + LafManager.installTheme(new PreferredThemeStyle(ContrastRule.STANDARD, ColorToneRule.DARK)); + } catch (Exception e) { + Relauncher.logger.warn("Could not initialize DarkLaf GUI theme", e); + } + Thread.currentThread() + .setContextClassLoader(original); + } + + private void invokeOnSwingThread(boolean wait, Runnable runnable) { + try { + if (wait) { + SwingUtilities.invokeAndWait(runnable); + } else { + SwingUtilities.invokeLater(runnable); + } + } catch (InterruptedException e) { + // cancelled + } catch (InvocationTargetException e) { + throw Throwables.propagate(e.getCause()); + } + } + + public void downloadWithGui(Downloader dler) { + invokeOnSwingThread(true, () -> { + initSwingIfNeeded(); + + final int totalTasks = dler.remainingTasks(); + final JDialog progressDialog = new JDialog( + null, + "Lwjgl3ify Library Downloader", + Dialog.ModalityType.APPLICATION_MODAL); + progressDialog.setMinimumSize(new Dimension(400, 128)); + progressDialog.setSize(new Dimension(400, 128)); + progressDialog.setLocationRelativeTo(null); + progressDialog.setResizable(false); + progressDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + final ProgressDialog dialogContent = new ProgressDialog(); + dialogContent.loadTranslations(); + progressDialog.add(dialogContent.panel); + + dialogContent.progressBar.setMinimum(0); + dialogContent.progressBar.setMaximum(totalTasks); + dialogContent.progressBar.setValue(0); + dialogContent.cancelButton.addActionListener(al -> { relauncher.runtimeExit(1); }); + + final Thread dlThread = new Thread(dler::runDownloads, "Download thread"); + dlThread.setContextClassLoader(RelauncherUserInterface.class.getClassLoader()); + dlThread.setDaemon(true); + + final AtomicBoolean normallyTerminated = new AtomicBoolean(false); + + final Timer updater = new Timer(1000 / 120, al -> { + final int remaining = dler.remainingTasks(); + dialogContent.progressBar.setValue(totalTasks - remaining); + final String files = StringUtils.join(dler.busyDownloads, ", "); + dialogContent.filesLabel.setText(files); + if (remaining <= 0) { + try { + dlThread.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + normallyTerminated.set(true); + progressDialog.dispose(); + } + }); + updater.start(); + + progressDialog.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosed(WindowEvent e) { + if (!normallyTerminated.get()) { + relauncher.runtimeExit(1); + } + } + + @Override + public void windowOpened(WindowEvent e) { + dlThread.start(); + } + }); + + progressDialog.setVisible(true); + }); + } + + private static long getTotalMemoryBytes() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + Object attribute = mBeanServer + .getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "TotalPhysicalMemorySize"); + return Long.parseLong(attribute.toString()); + } catch (Exception e) { + return 8192; + } + } + + public void startSettingsIfNeeded() { + invokeOnSwingThread(true, () -> { + initSwingIfNeeded(); + final JDialog settingsDialog = new JDialog( + null, + "Lwjgl3ify settings", + Dialog.ModalityType.APPLICATION_MODAL); + settingsDialog.setMinimumSize(new Dimension(800, 600)); + settingsDialog.setSize(new Dimension(800, 600)); + settingsDialog.setLocationRelativeTo(null); + settingsDialog.setResizable(true); + settingsDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + final SettingsDialog contents = new SettingsDialog(); + contents.loadTranslations(); + settingsDialog.add(contents.rootPanel); + + // Configure memory sliders + final long totalSystemMemory = getTotalMemoryBytes(); + final int totalSystemMemoryMB = (int) ((totalSystemMemory + (1024 * 1024) - 1) / (1024 * 1024)); + contents.optMinMemory.setMaximum(totalSystemMemoryMB); + contents.optMaxMemory.setMaximum(totalSystemMemoryMB); + int memTickSpacing = 1024; + while ((totalSystemMemoryMB / memTickSpacing) > 9) { + memTickSpacing *= 2; + } + contents.optMinMemory.setLabelTable(null); + contents.optMaxMemory.setLabelTable(null); + contents.optMinMemory.setMajorTickSpacing(memTickSpacing); + contents.optMaxMemory.setMajorTickSpacing(memTickSpacing); + + // Update labels + contents.labelMinJavaVer + .setText(String.format(contents.translations.getString(TranslationsBundle.KEY_MIN_MOD_JAVA), 17)); + + // Set settings values + final RelauncherConfig.ConfigObject initCfg = RelauncherConfig.config; + final DefaultComboBoxModel modelJavaPaths = new DefaultComboBoxModel<>( + initCfg.javaInstallationsCache.clone()); + contents.comboJavaExecutable.setModel(modelJavaPaths); + if (modelJavaPaths.getSize() > 0) { + contents.comboJavaExecutable.setSelectedIndex(initCfg.javaInstallation); + } + contents.optMinMemory.setValue(initCfg.minMemoryMB); + contents.optMaxMemory.setValue(initCfg.maxMemoryMB); + contents.optGC.setModel(new GCComboModel()); + contents.optGC.setSelectedItem(initCfg.garbageCollector); + contents.optCustom.getDocument() + .putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n"); + contents.optCustom.setText(initCfg.customOptionsToQuotedString()); + contents.optForwardLogs.setSelected(initCfg.forwardLogs); + contents.optDebugAgent.setSelected(initCfg.allowDebugger); + contents.optDebugSuspend.setSelected(initCfg.waitForDebugger); + contents.optMixinDebug.setSelected(initCfg.mixinDebug); + contents.optMixinExport.setSelected(initCfg.mixinDebugExport); + contents.optMixinCount.setSelected(initCfg.mixinDebugCount); + contents.optFmlDebugAts.setSelected(initCfg.fmlDebugAts); + contents.optRfbDumpClasses.setSelected(initCfg.rfbDumpClasses); + contents.optRfbDumpTransformers.setSelected(initCfg.rfbDumpPerTransformer); + + refreshJavaInstalls(contents); + saveConfig(contents); + + settingsDialog.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent e) { + saveConfig(contents); + } + }); + + contents.buttonAddJava.addActionListener(al -> { + final JFileChooser jfc = new JFileChooser(); + jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); + jfc.setDialogType(JFileChooser.OPEN_DIALOG); + jfc.setDialogTitle("Pick java executable"); + final FileFilter fileFilter = new FileFilter() { + + @Override + public boolean accept(File f) { + if (f == null) { + return false; + } + final String name = f.getName(); + return !f.isFile() || name.equalsIgnoreCase("java") + || name.equalsIgnoreCase("javaw") + || name.equalsIgnoreCase("java.exe") + || name.equalsIgnoreCase("javaw.exe"); + } + + @Override + public String getDescription() { + return "Java binaries"; + } + }; + jfc.addChoosableFileFilter(fileFilter); + jfc.setFileFilter(fileFilter); + final int result = jfc.showOpenDialog(settingsDialog); + if (result == JFileChooser.APPROVE_OPTION) { + final String path = jfc.getSelectedFile() + .getAbsolutePath(); + final DefaultComboBoxModel model = (DefaultComboBoxModel) contents.comboJavaExecutable + .getModel(); + model.addElement(path); + model.setSelectedItem(path); + refreshJavaInstalls(contents); + } + }); + + contents.buttonPreviewJavaOpts.addActionListener(al -> { + saveConfig(contents); + JOptionPane.showMessageDialog( + settingsDialog, + String.join(System.lineSeparator(), RelauncherConfig.config.toJvmArgs()), + "Java", + JOptionPane.INFORMATION_MESSAGE); + }); + + contents.buttonRun.addActionListener(al -> { + runClicked = true; + saveConfig(contents); + settingsDialog.dispose(); + }); + + settingsDialog.setVisible(true); + }); + } + + private static void refreshJavaInstalls(SettingsDialog contents) { + final DefaultComboBoxModel model = (DefaultComboBoxModel) contents.comboJavaExecutable + .getModel(); + final String oldSelection = Objects.toString(model.getSelectedItem()); + final List validInstalls = JvmLocator.detectJavaInstalls(comboToList(model)); + model.removeAllElements(); + for (final Path p : validInstalls) { + final String pString = p.toString(); + model.addElement(pString); + if (pString.equals(oldSelection)) { + model.setSelectedItem(pString); + } + } + } + + private static List comboToList(ComboBoxModel model) { + final List out = new ArrayList<>(model.getSize()); + for (int i = 0; i < model.getSize(); i++) { + out.add(model.getElementAt(i)); + } + return out; + } + + private static void saveConfig(SettingsDialog contents) { + final RelauncherConfig.ConfigObject initCfg = RelauncherConfig.config; + initCfg.javaInstallationsCache = comboToList(contents.comboJavaExecutable.getModel()).toArray(new String[0]); + initCfg.javaInstallation = contents.comboJavaExecutable.getSelectedIndex(); + initCfg.minMemoryMB = contents.optMinMemory.getValue(); + initCfg.maxMemoryMB = contents.optMaxMemory.getValue(); + initCfg.garbageCollector = (RelauncherConfig.GCOption) contents.optGC.getSelectedItem(); + initCfg.setCustomOptionsFromQuotedString( + contents.optCustom.getText() + .replace("\r\n", "\n")); + initCfg.forwardLogs = contents.optForwardLogs.isSelected(); + initCfg.allowDebugger = contents.optDebugAgent.isSelected(); + initCfg.waitForDebugger = contents.optDebugSuspend.isSelected(); + initCfg.mixinDebug = contents.optMixinDebug.isSelected(); + initCfg.mixinDebugExport = contents.optMixinExport.isSelected(); + initCfg.mixinDebugCount = contents.optMixinCount.isSelected(); + initCfg.fmlDebugAts = contents.optFmlDebugAts.isSelected(); + initCfg.rfbDumpClasses = contents.optRfbDumpClasses.isSelected(); + initCfg.rfbDumpPerTransformer = contents.optRfbDumpTransformers.isSelected(); + RelauncherConfig.save(); + } + + public static class GCComboModel extends DefaultComboBoxModel { + + public GCComboModel() { + super(RelauncherConfig.GCOption.values()); + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.form b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.form new file mode 100644 index 0000000..951275a --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.form @@ -0,0 +1,330 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.java new file mode 100644 index 0000000..7741ef3 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/SettingsDialog.java @@ -0,0 +1,436 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.Locale; +import java.util.ResourceBundle; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSlider; +import javax.swing.JTabbedPane; +import javax.swing.JTextPane; +import javax.swing.border.TitledBorder; +import javax.swing.plaf.FontUIResource; +import javax.swing.text.StyleContext; + +public class SettingsDialog { + + public JComboBox comboJavaExecutable; + public JButton buttonRefreshJavas; + public JButton buttonAddJava; + public JTabbedPane tabbedPane1; + public JSlider optMinMemory; + public JComboBox optGC; + public JTextPane optCustom; + public JButton buttonRun; + public JCheckBox optHideOnFutureLaunches; + public JCheckBox optRfbDumpClasses; + public JCheckBox optRfbDumpTransformers; + public JCheckBox optDebugAgent; + public JCheckBox optDebugSuspend; + public JCheckBox optForwardLogs; + public JSlider optMaxMemory; + public JCheckBox optMixinDebug; + public JCheckBox optMixinExport; + public JCheckBox optMixinCount; + public JCheckBox optFmlDebugAts; + public JPanel rootPanel; + public JLabel labelMinJavaVer; + public JLabel lblHeader; + public JLabel lblJavaExecutable; + public JLabel lblJavaOptions; + public JPanel panelBasic; + public JPanel panelAdvanced; + public JLabel lblMinMemory; + public JLabel lblMaxMemory; + public JLabel lblGarbageCollector; + public JLabel lblCustomOptions; + public JButton buttonPreviewJavaOpts; + + public final ResourceBundle translations; + + public SettingsDialog() { + translations = ResourceBundle.getBundle("me.eigenraven.lwjgl3ify.relauncher.TranslationsBundle"); + } + + public void loadTranslations() { + lblHeader.setText(translations.getString(TranslationsBundle.KEY_SETTINGS_HEADER)); + buttonRefreshJavas.setText(translations.getString(TranslationsBundle.KEY_REFRESH)); + buttonAddJava.setText(translations.getString(TranslationsBundle.KEY_ADD_JAVA)); + buttonRun.setText(translations.getString(TranslationsBundle.KEY_RUN_GAME)); + lblJavaExecutable.setText(translations.getString(TranslationsBundle.KEY_JAVA_EXECUTABLE)); + labelMinJavaVer.setText(String.format(translations.getString(TranslationsBundle.KEY_MIN_MOD_JAVA), 17)); + tabbedPane1.setTitleAt(0, translations.getString(TranslationsBundle.KEY_TAB_BASIC)); + tabbedPane1.setTitleAt(1, translations.getString(TranslationsBundle.KEY_TAB_ADVANCED)); + lblMinMemory.setText(translations.getString(TranslationsBundle.KEY_MIN_MEMORY_MB)); + lblMaxMemory.setText(translations.getString(TranslationsBundle.KEY_MAX_MEMORY_MB)); + lblGarbageCollector.setText(translations.getString(TranslationsBundle.KEY_GARBAGE_COLLECTOR)); + lblCustomOptions.setText(translations.getString(TranslationsBundle.KEY_CUSTOM_OPTIONS)); + lblJavaOptions.setText(translations.getString(TranslationsBundle.KEY_JAVA_OPTIONS)); + optHideOnFutureLaunches.setText(translations.getString(TranslationsBundle.KEY_SKIP_IN_FUTURE)); + buttonPreviewJavaOpts.setText(translations.getString(TranslationsBundle.KEY_PREVIEW_JAVA_OPTS)); + + optForwardLogs.setText(translations.getString(TranslationsBundle.KEY_FORWARD_LOGS)); + optDebugAgent.setText(translations.getString(TranslationsBundle.KEY_ALLOW_DEBUGGER)); + optDebugSuspend.setText(translations.getString(TranslationsBundle.KEY_WAIT_FOR_DEBUGGER)); + optMixinDebug.setText(translations.getString(TranslationsBundle.KEY_MIXIN_DEBUG)); + optMixinExport.setText(translations.getString(TranslationsBundle.KEY_MIXIN_EXPORT_CLASSES)); + optMixinCount.setText(translations.getString(TranslationsBundle.KEY_MIXIN_COUNT_INJECTIONS)); + optFmlDebugAts.setText(translations.getString(TranslationsBundle.KEY_FML_DEBUG_AT)); + optRfbDumpClasses.setText(translations.getString(TranslationsBundle.KEY_RFB_DUMP_CLASSES)); + optRfbDumpTransformers.setText(translations.getString(TranslationsBundle.KEY_RFB_DUMP_CLASSES_PER_TRANSFORMER)); + + optForwardLogs.setToolTipText(translations.getString(TranslationsBundle.KEY_FORWARD_LOGS_TIP)); + } + + { + // GUI initializer generated by IntelliJ IDEA GUI Designer + // >>> IMPORTANT!! <<< + // DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR call it in your + * code! + * + * @noinspection ALL + */ + private void $$$setupUI$$$() { + rootPanel = new JPanel(); + rootPanel.setLayout(new GridBagLayout()); + final JPanel spacer1 = new JPanel(); + GridBagConstraints gbc; + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(spacer1, gbc); + lblHeader = new JLabel(); + Font lblHeaderFont = this.$$$getFont$$$(null, Font.BOLD, -1, lblHeader.getFont()); + if (lblHeaderFont != null) lblHeader.setFont(lblHeaderFont); + lblHeader.setHorizontalAlignment(0); + lblHeader.setHorizontalTextPosition(0); + lblHeader.setText("KEY_SETTINGS_HEADER"); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.gridwidth = 5; + gbc.weightx = 1.0; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(lblHeader, gbc); + lblJavaExecutable = new JLabel(); + lblJavaExecutable.setText("KEY_JAVA_EXECUTABLE"); + gbc = new GridBagConstraints(); + gbc.gridx = 2; + gbc.gridy = 1; + gbc.anchor = GridBagConstraints.WEST; + rootPanel.add(lblJavaExecutable, gbc); + comboJavaExecutable = new JComboBox(); + gbc = new GridBagConstraints(); + gbc.gridx = 3; + gbc.gridy = 1; + gbc.weightx = 1.0; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(comboJavaExecutable, gbc); + buttonRefreshJavas = new JButton(); + buttonRefreshJavas.setText("KEY_REFRESH"); + gbc = new GridBagConstraints(); + gbc.gridx = 4; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(buttonRefreshJavas, gbc); + final JPanel spacer2 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 6; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(spacer2, gbc); + buttonAddJava = new JButton(); + buttonAddJava.setText("KEY_ADD_JAVA"); + gbc = new GridBagConstraints(); + gbc.gridx = 5; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(buttonAddJava, gbc); + labelMinJavaVer = new JLabel(); + labelMinJavaVer.setText("KEY_MIN_MOD_JAVA"); + gbc = new GridBagConstraints(); + gbc.gridx = 3; + gbc.gridy = 2; + gbc.gridwidth = 3; + gbc.anchor = GridBagConstraints.WEST; + rootPanel.add(labelMinJavaVer, gbc); + lblJavaOptions = new JLabel(); + lblJavaOptions.setText("KEY_JAVA_OPTIONS"); + gbc = new GridBagConstraints(); + gbc.gridx = 2; + gbc.gridy = 3; + gbc.anchor = GridBagConstraints.WEST; + rootPanel.add(lblJavaOptions, gbc); + tabbedPane1 = new JTabbedPane(); + gbc = new GridBagConstraints(); + gbc.gridx = 3; + gbc.gridy = 3; + gbc.gridwidth = 3; + gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.BOTH; + rootPanel.add(tabbedPane1, gbc); + panelBasic = new JPanel(); + panelBasic.setLayout(new GridBagLayout()); + tabbedPane1.addTab("KEY_TAB_BASIC", panelBasic); + panelBasic.setBorder( + BorderFactory.createTitledBorder( + BorderFactory.createEtchedBorder(), + null, + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, + null, + null)); + lblMinMemory = new JLabel(); + lblMinMemory.setText("KEY_MIN_MEMORY_MB"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.anchor = GridBagConstraints.EAST; + panelBasic.add(lblMinMemory, gbc); + optMinMemory = new JSlider(); + optMinMemory.setMajorTickSpacing(1024); + optMinMemory.setMaximum(8192); + optMinMemory.setMinorTickSpacing(256); + optMinMemory.setPaintLabels(true); + optMinMemory.setPaintTicks(true); + optMinMemory.setSnapToTicks(true); + optMinMemory.setValueIsAdjusting(false); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 0; + gbc.weightx = 1.0; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.HORIZONTAL; + panelBasic.add(optMinMemory, gbc); + lblMaxMemory = new JLabel(); + lblMaxMemory.setText("KEY_MAX_MEMORY_MB"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 1; + gbc.anchor = GridBagConstraints.EAST; + panelBasic.add(lblMaxMemory, gbc); + optMaxMemory = new JSlider(); + optMaxMemory.setMajorTickSpacing(1024); + optMaxMemory.setMaximum(8192); + optMaxMemory.setMinorTickSpacing(256); + optMaxMemory.setPaintLabels(true); + optMaxMemory.setPaintTicks(true); + optMaxMemory.setSnapToTicks(true); + optMaxMemory.setValueIsAdjusting(false); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 1; + gbc.weightx = 1.0; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.HORIZONTAL; + panelBasic.add(optMaxMemory, gbc); + lblGarbageCollector = new JLabel(); + lblGarbageCollector.setText("KEY_GARBAGE_COLLECTOR"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 2; + gbc.anchor = GridBagConstraints.EAST; + panelBasic.add(lblGarbageCollector, gbc); + optGC = new JComboBox(); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.HORIZONTAL; + panelBasic.add(optGC, gbc); + lblCustomOptions = new JLabel(); + lblCustomOptions.setText("KEY_CUSTOM_OPTIONS"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 3; + gbc.gridwidth = 2; + gbc.weightx = 1.0; + gbc.anchor = GridBagConstraints.WEST; + panelBasic.add(lblCustomOptions, gbc); + final JScrollPane scrollPane1 = new JScrollPane(); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 4; + gbc.gridwidth = 2; + gbc.weightx = 1.0; + gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.BOTH; + gbc.insets = new Insets(4, 4, 4, 4); + panelBasic.add(scrollPane1, gbc); + optCustom = new JTextPane(); + optCustom.setMinimumSize(new Dimension(256, 128)); + scrollPane1.setViewportView(optCustom); + panelAdvanced = new JPanel(); + panelAdvanced.setLayout(new GridBagLayout()); + tabbedPane1.addTab("KEY_TAB_ADVANCED", panelAdvanced); + panelAdvanced.setBorder( + BorderFactory.createTitledBorder( + BorderFactory.createEtchedBorder(), + null, + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, + null, + null)); + optRfbDumpClasses = new JCheckBox(); + optRfbDumpClasses.setText("KEY_RFB_DUMP_CLASSES"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 7; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optRfbDumpClasses, gbc); + final JPanel spacer3 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 7; + gbc.weightx = 1.0; + gbc.fill = GridBagConstraints.HORIZONTAL; + panelAdvanced.add(spacer3, gbc); + final JPanel spacer4 = new JPanel(); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 9; + gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.VERTICAL; + panelAdvanced.add(spacer4, gbc); + optRfbDumpTransformers = new JCheckBox(); + optRfbDumpTransformers.setText("KEY_RFB_DUMP_CLASSES_PER_TRANSFORMER"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 8; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optRfbDumpTransformers, gbc); + optDebugAgent = new JCheckBox(); + optDebugAgent.setText("KEY_ALLOW_DEBUGGER"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 1; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optDebugAgent, gbc); + optDebugSuspend = new JCheckBox(); + optDebugSuspend.setText("KEY_WAIT_FOR_DEBUGGER"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 2; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optDebugSuspend, gbc); + optForwardLogs = new JCheckBox(); + optForwardLogs.setEnabled(true); + optForwardLogs.setSelected(false); + optForwardLogs.setText("KEY_FORWARD_LOGS"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optForwardLogs, gbc); + optMixinExport = new JCheckBox(); + optMixinExport.setText("KEY_MIXIN_EXPORT_CLASSES"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 4; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optMixinExport, gbc); + optMixinDebug = new JCheckBox(); + optMixinDebug.setText("KEY_MIXIN_DEBUG"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 3; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optMixinDebug, gbc); + optMixinCount = new JCheckBox(); + optMixinCount.setText("KEY_MIXIN_COUNT_INJECTIONS"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 5; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optMixinCount, gbc); + optFmlDebugAts = new JCheckBox(); + optFmlDebugAts.setText("KEY_FML_DEBUG_AT"); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 6; + gbc.anchor = GridBagConstraints.WEST; + gbc.insets = new Insets(4, 0, 0, 0); + panelAdvanced.add(optFmlDebugAts, gbc); + buttonRun = new JButton(); + buttonRun.setText("KEY_RUN_GAME"); + gbc = new GridBagConstraints(); + gbc.gridx = 4; + gbc.gridy = 5; + gbc.gridwidth = 2; + gbc.fill = GridBagConstraints.HORIZONTAL; + rootPanel.add(buttonRun, gbc); + optHideOnFutureLaunches = new JCheckBox(); + optHideOnFutureLaunches.setSelected(true); + optHideOnFutureLaunches.setText("KEY_SKIP_IN_FUTURE"); + gbc = new GridBagConstraints(); + gbc.gridx = 3; + gbc.gridy = 5; + gbc.anchor = GridBagConstraints.WEST; + rootPanel.add(optHideOnFutureLaunches, gbc); + buttonPreviewJavaOpts = new JButton(); + buttonPreviewJavaOpts.setText("KEY_PREVIEW_JAVA_OPTS"); + gbc = new GridBagConstraints(); + gbc.gridx = 3; + gbc.gridy = 4; + gbc.anchor = GridBagConstraints.WEST; + rootPanel.add(buttonPreviewJavaOpts, gbc); + } + + /** @noinspection ALL */ + private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) { + if (currentFont == null) return null; + String resultName; + if (fontName == null) { + resultName = currentFont.getName(); + } else { + Font testFont = new Font(fontName, Font.PLAIN, 10); + if (testFont.canDisplay('a') && testFont.canDisplay('1')) { + resultName = fontName; + } else { + resultName = currentFont.getName(); + } + } + Font font = new Font( + resultName, + style >= 0 ? style : currentFont.getStyle(), + size >= 0 ? size : currentFont.getSize()); + boolean isMac = System.getProperty("os.name", "") + .toLowerCase(Locale.ENGLISH) + .startsWith("mac"); + Font fontWithFallback = isMac ? new Font(font.getFamily(), font.getStyle(), font.getSize()) + : new StyleContext().getFont(font.getFamily(), font.getStyle(), font.getSize()); + return fontWithFallback instanceof FontUIResource ? fontWithFallback : new FontUIResource(fontWithFallback); + } + + /** @noinspection ALL */ + public JComponent $$$getRootComponent$$$() { + return rootPanel; + } + +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle.java new file mode 100644 index 0000000..96cef3c --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle.java @@ -0,0 +1,77 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +import java.util.ListResourceBundle; + +/** + * The default English translations, and translation key constants. + * We're using Java bundles instead of Property bundles to allow UTF-8 encoding in the sources. + */ +public class TranslationsBundle extends ListResourceBundle { + + public static final String KEY_CANCEL = "cancel"; + + public static final String KEY_PROGRESS_DOWNLOADING_HEADER = "progressDownloading"; + + public static final String KEY_SETTINGS_HEADER = "settingsHeader"; + public static final String KEY_ADD_JAVA = "addJava"; + public static final String KEY_REFRESH = "refresh"; + public static final String KEY_RUN_GAME = "runGame"; + public static final String KEY_JAVA_EXECUTABLE = "javaExecutable"; + public static final String KEY_MIN_MOD_JAVA = "minModJava"; + public static final String KEY_TAB_BASIC = "tabBasic"; + public static final String KEY_TAB_ADVANCED = "tabAdvanced"; + public static final String KEY_JAVA_OPTIONS = "javaOptions"; + public static final String KEY_MIN_MEMORY_MB = "minMemoryMB"; + public static final String KEY_MAX_MEMORY_MB = "maxMemoryMB"; + public static final String KEY_GARBAGE_COLLECTOR = "garbageCollector"; + public static final String KEY_CUSTOM_OPTIONS = "customOptions"; + public static final String KEY_SKIP_IN_FUTURE = "skipInFuture"; + public static final String KEY_FORWARD_LOGS = "forwardLogs"; + public static final String KEY_ALLOW_DEBUGGER = "allowDebugger"; + public static final String KEY_WAIT_FOR_DEBUGGER = "waitForDebugger"; + public static final String KEY_MIXIN_DEBUG = "mixinDebug"; + public static final String KEY_MIXIN_EXPORT_CLASSES = "mixinExportClasses"; + public static final String KEY_MIXIN_COUNT_INJECTIONS = "mixinCountInjections"; + public static final String KEY_FML_DEBUG_AT = "fmlDebugAT"; + public static final String KEY_RFB_DUMP_CLASSES = "rfbDumpClasses"; + public static final String KEY_RFB_DUMP_CLASSES_PER_TRANSFORMER = "rfbDumpClassesPerTransformer"; + public static final String KEY_FORWARD_LOGS_TIP = "forwardLogsTip"; + public static final String KEY_PREVIEW_JAVA_OPTS = "previewJavaOpts"; + + @Override + protected Object[][] getContents() { + return new Object[][] { + // spotless:off + { KEY_CANCEL, "Cancel" }, + { KEY_PROGRESS_DOWNLOADING_HEADER, "Downloading lwjgl3ify libraries..." }, + + { KEY_SETTINGS_HEADER, "Lwjgl3ify Modern Java Relaunch Settings" }, + { KEY_REFRESH, "Refresh" }, + { KEY_ADD_JAVA, "Add" }, + { KEY_RUN_GAME, "Run" }, + { KEY_JAVA_EXECUTABLE, "Java executable: " }, + { KEY_MIN_MOD_JAVA, "Minimum Java version required by your mods: %s" }, + { KEY_TAB_BASIC, "Basic" }, + { KEY_TAB_ADVANCED, "Advanced" }, + { KEY_JAVA_OPTIONS, "Java options: " }, + { KEY_MIN_MEMORY_MB, "Min memory [MB]" }, + { KEY_MAX_MEMORY_MB, "Max memory [MB]" }, + { KEY_GARBAGE_COLLECTOR, "Garbage collector" }, + { KEY_CUSTOM_OPTIONS, "Custom options" }, + { KEY_SKIP_IN_FUTURE, "Skip the settings window in the future" }, + + { KEY_FORWARD_LOGS, "Forward logs to the parent launcher (uses more memory)" }, + { KEY_FORWARD_LOGS_TIP, "Requires you to keep running this old java instance in parallel with the new java instance, so if you didn't configure your launcher to use less memory, the game might use double the memory or more." }, + { KEY_ALLOW_DEBUGGER, "Allow attaching a debugger" }, + { KEY_WAIT_FOR_DEBUGGER, "Wait for debugger" }, + { KEY_MIXIN_DEBUG, "Mixin: Debug" }, + { KEY_MIXIN_EXPORT_CLASSES, "Mixin: Export classes" }, + { KEY_MIXIN_COUNT_INJECTIONS, "Mixin: Count injections" }, + { KEY_FML_DEBUG_AT, "FML: Debug Access Transformers" }, + { KEY_RFB_DUMP_CLASSES, "RFB: Dump loaded classes" }, + { KEY_RFB_DUMP_CLASSES_PER_TRANSFORMER, "RFB: Dump classes per transformer" }, + { KEY_PREVIEW_JAVA_OPTS, "Preview Java options" }, + // spotless:on + }; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle_pl_PL.java b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle_pl_PL.java new file mode 100644 index 0000000..66bf856 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/relauncher/TranslationsBundle_pl_PL.java @@ -0,0 +1,41 @@ +package me.eigenraven.lwjgl3ify.relauncher; + +public class TranslationsBundle_pl_PL extends TranslationsBundle { + + @Override + protected Object[][] getContents() { + return new Object[][] { + // spotless:off + { KEY_CANCEL, "Anuluj" }, + { KEY_PROGRESS_DOWNLOADING_HEADER, "Ściąganie bibliotek lwjgl3ify..." }, + + { KEY_SETTINGS_HEADER, "Ustawienia ponownego uruchamiania Javy przez lwjgl3ify" }, + { KEY_REFRESH, "Odśwież" }, + { KEY_ADD_JAVA, "Dodaj" }, + { KEY_RUN_GAME, "Uruchom" }, + { KEY_JAVA_EXECUTABLE, "Plik wykonywalny Javy: " }, + { KEY_MIN_MOD_JAVA, "Minimalna wersja Javy wymagana przez twoje mody: %s" }, + { KEY_TAB_BASIC, "Podstawowe" }, + { KEY_TAB_ADVANCED, "Zaawansowane" }, + { KEY_JAVA_OPTIONS, "Opcje Javy: " }, + { KEY_MIN_MEMORY_MB, "Minimalna pamięć [MB]" }, + { KEY_MAX_MEMORY_MB, "Maksymalna pamięć [MB]" }, + { KEY_GARBAGE_COLLECTOR, "Odśmiecacz pamięci" }, + { KEY_CUSTOM_OPTIONS, "Własne opcje" }, + { KEY_SKIP_IN_FUTURE, "Pomiń to okno ustawień w przyszłości" }, + + { KEY_FORWARD_LOGS, "Przekaż konsolę gry do programu uruchamiającego (zużywa więcej pamięci)" }, + { KEY_FORWARD_LOGS_TIP, "Wymaga podtrzymania istniejącej instancji Javy równolegle z nową instancją Javy. Bez zmniejszenia alokacji pamięci w programie uruchamiającym może zużyć podwojoną ilość pamięci, lub więcej." }, + { KEY_ALLOW_DEBUGGER, "Pozwól na dołączanie debugera" }, + { KEY_WAIT_FOR_DEBUGGER, "Poczekaj na debugera" }, + { KEY_MIXIN_DEBUG, "Mixin: Debugowanie" }, + { KEY_MIXIN_EXPORT_CLASSES, "Mixin: Eksportuj klasy" }, + { KEY_MIXIN_COUNT_INJECTIONS, "Mixin: Policz modyfikacje" }, + { KEY_FML_DEBUG_AT, "FML: Debuguj transformatory dostępu (AT)" }, + { KEY_RFB_DUMP_CLASSES, "RFB: Zapisz wczytywane klasy" }, + { KEY_RFB_DUMP_CLASSES_PER_TRANSFORMER, "RFB: Zapisz wczytywane klasy dla każdego transformatora" }, + { KEY_PREVIEW_JAVA_OPTS, "Podgląd opcji Javy" }, + // spotless:on + }; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/rfb/EarlyConfig.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/EarlyConfig.java new file mode 100644 index 0000000..1146b44 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/EarlyConfig.java @@ -0,0 +1,106 @@ +package me.eigenraven.lwjgl3ify.rfb; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; + +public class EarlyConfig { + + public static final String[] DEFAULT_EXTENSIBLE_ENUMS = new String[] { + // From EnumHelper + "net.minecraft.item.EnumAction", "net.minecraft.item.ItemArmor$ArmorMaterial", + "net.minecraft.entity.item.EntityPainting$EnumArt", "net.minecraft.entity.EnumCreatureAttribute", + "net.minecraft.entity.EnumCreatureType", + "net.minecraft.world.gen.structure.StructureStrongholdPieces$Stronghold$Door", + "net.minecraft.enchantment.EnumEnchantmentType", "net.minecraft.entity.Entity$EnumEntitySize", + "net.minecraft.block.BlockPressurePlate$Sensitivity", + "net.minecraft.util.MovingObjectPosition$MovingObjectType", "net.minecraft.world.EnumSkyBlock", + "net.minecraft.entity.player.EntityPlayer$EnumStatus", "net.minecraft.item.Item$ToolMaterial", + "net.minecraft.item.EnumRarity", + // + "net.minecraftforge.event.terraingen.PopulateChunkEvent$Populate$EventType", + "net.minecraftforge.event.terraingen.InitMapGenEvent$EventType", + "net.minecraftforge.event.terraingen.OreGenEvent$GenerateMinable$EventType", + "net.minecraftforge.event.terraingen.DecorateBiomeEvent$Decorate$EventType", + // From GTNH crashes + "vswe.stevesfactory.Localization", "vswe.stevesfactory.blocks.ClusterMethodRegistration", + "vswe.stevesfactory.blocks.ConnectionBlockType", "vswe.stevesfactory.components.ComponentType", + "vswe.stevesfactory.components.ConnectionSet", "vswe.stevesfactory.components.ConnectionOption", + "ic2.core.init.InternalName", "gregtech.api.enums.Element", "gregtech.api.enums.OrePrefixes", + "net.minecraft.client.audio.MusicTicker$MusicType", "org.bukkit.Material", + "buildcraft.api.transport.IPipeTile.PipeType", "thaumcraft.common.entities.golems.EnumGolemType", + // Non-GTNH Mods Compat + // The Lord of the Rings Mod: Legacy + "net.minecraft.event.HoverEvent$Action", + // Reika's mods + "net.minecraft.client.audio.SoundCategory", + "Reika.RotaryCraft.TileEntities.Processing.TileEntityFuelConverter$Conversions", + "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Fertility", + "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Speeds", + "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Flowering", + "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Territory", + "Reika.DragonAPI.ModInteract.Bees.BeeAlleleRegistry$Life", + "Reika.DragonAPI.ModInteract.Bees.ButterflyAlleleRegistry$Fertility", + "Reika.DragonAPI.ModInteract.Bees.ButterflyAlleleRegistry$Life", + // Et Futurum Requiem + "net.minecraft.world.WorldSettings$GameType", + // EnderIO Addons + "crazypants.enderio.ModObject", + // + }; + + public static final Set EXTENSIBLE_ENUMS = new HashSet<>(Arrays.asList(DEFAULT_EXTENSIBLE_ENUMS)); + + public static class ConfigObject { + + public String[] extensibleEnums; + } + + private static boolean isLoaded = false; + + public static void load() { + if (isLoaded) { + return; + } + isLoaded = true; + + final Path gamePath = RetroFuturaBootstrap.API.gameDirectory(); + final Path earlyConfigPath = gamePath.resolve("config") + .resolve("lwjgl3ify-early.json"); + final Gson gson = new GsonBuilder().disableJdkUnsafe() + .setPrettyPrinting() + .create(); + ConfigObject cfg = new ConfigObject(); + if (Files.exists(earlyConfigPath)) { + try { + final String earlyConfigContents = new String( + Files.readAllBytes(earlyConfigPath), + StandardCharsets.UTF_8); + cfg = gson.fromJson(earlyConfigContents, ConfigObject.class); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + if (cfg.extensibleEnums != null) { + EXTENSIBLE_ENUMS.addAll(Arrays.asList(cfg.extensibleEnums)); + } + cfg.extensibleEnums = EXTENSIBLE_ENUMS.toArray(new String[0]); + + final String jsonCfg = gson.toJson(cfg); + try { + Files.createDirectories(earlyConfigPath.getParent()); + Files.write(earlyConfigPath, jsonCfg.getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/forgePatches/java/cpw/mods/fml/relauncher/FMLSecurityManager.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/Lwjgl3ifyRfbPlugin.java similarity index 61% rename from src/forgePatches/java/cpw/mods/fml/relauncher/FMLSecurityManager.java rename to src/main/java/me/eigenraven/lwjgl3ify/rfb/Lwjgl3ifyRfbPlugin.java index b980d35..fafbe80 100644 --- a/src/forgePatches/java/cpw/mods/fml/relauncher/FMLSecurityManager.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/Lwjgl3ifyRfbPlugin.java @@ -1,25 +1,43 @@ -package cpw.mods.fml.relauncher; +package me.eigenraven.lwjgl3ify.rfb; import java.awt.GraphicsEnvironment; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; -import java.security.Permission; import javax.swing.JOptionPane; -/** - * A custom security manager stopping certain events from happening unexpectedly. - * - * @author cpw - * - * @author eigenraven Patch ArrayIndexOutOfBoundsException - the length condition were 1-off - * - */ -public class FMLSecurityManager extends SecurityManager { +import net.minecraft.launchwrapper.Launch; - public FMLSecurityManager() { - // This is the first class that gets loaded, do the 17 check first. +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbPlugin; + +import me.eigenraven.lwjgl3ify.rfb.transformers.ExtensibleEnumTransformer; +import me.eigenraven.lwjgl3ify.rfb.transformers.ForgePatchTransformer; +import me.eigenraven.lwjgl3ify.rfb.transformers.LwjglRedirectTransformer; +import me.eigenraven.lwjgl3ify.rfb.transformers.UnfinalizeObjectHoldersTransformer; + +public class Lwjgl3ifyRfbPlugin implements RfbPlugin { + + @Override + public void onConstruction(@NotNull PluginContext ctx) { + Launch.blackboard.put("lwjgl3ify:rfb-booted", Boolean.TRUE); + EarlyConfig.load(); + verifyJavaVersion(); + Launch.classLoader.addClassLoaderExclusion("org.openjdk.nashorn"); + } + + @Override + public @NotNull RfbClassTransformer @Nullable [] makeTransformers() { + return new RfbClassTransformer[] { new LwjglRedirectTransformer(), new ExtensibleEnumTransformer(), + new UnfinalizeObjectHoldersTransformer(), new ForgePatchTransformer() }; + } + + private void verifyJavaVersion() { if (!Boolean.getBoolean("lwjgl3ify.skipjavacheck")) { final String specVer = System.getProperty("java.specification.version"); if (specVer.equals("17")) { @@ -60,30 +78,4 @@ public class FMLSecurityManager extends SecurityManager { } } } - - @Override - public void checkPermission(Permission perm) { - String permName = perm.getName() != null ? perm.getName() : "missing"; - if (permName.startsWith("exitVM")) { - Class[] classContexts = getClassContext(); - String callingClass = classContexts.length > 4 ? classContexts[4].getName() : "none"; // PATCHED - String callingParent = classContexts.length > 5 ? classContexts[5].getName() : "none"; // PATCHED - // FML is allowed to call system exit and the Minecraft applet (from the quit button) - if (!(callingClass.startsWith("cpw.mods.fml.") - || ("net.minecraft.client.Minecraft".equals(callingClass) - && "net.minecraft.client.Minecraft".equals(callingParent)) - || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) - && "net.minecraft.server.MinecraftServer".equals(callingParent)))) { - throw new ExitTrappedException(); - } - } else if ("setSecurityManager".equals(permName)) { - throw new SecurityException("Cannot replace the FML security manager"); - } - return; - } - - public static class ExitTrappedException extends SecurityException { - - private static final long serialVersionUID = 1L; - } } diff --git a/src/forgePatches/java/cpw/mods/fml/relauncher/ServerLaunchWrapper.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/entry/ServerMain.java similarity index 61% rename from src/forgePatches/java/cpw/mods/fml/relauncher/ServerLaunchWrapper.java rename to src/main/java/me/eigenraven/lwjgl3ify/rfb/entry/ServerMain.java index f03bc00..73cf7a7 100644 --- a/src/forgePatches/java/cpw/mods/fml/relauncher/ServerLaunchWrapper.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/entry/ServerMain.java @@ -1,27 +1,27 @@ -package cpw.mods.fml.relauncher; +package me.eigenraven.lwjgl3ify.rfb.entry; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class ServerLaunchWrapper { +/** + * The replacement for ServerLaunchWrapper as the main class when starting the server. + */ +public class ServerMain { - /** - * @param args - */ public static void main(String[] args) { - new ServerLaunchWrapper().run(args); + new ServerMain().run(args); } - private ServerLaunchWrapper() { - - } + private ServerMain() {} private void run(String[] args) { Class launchwrapper = null; try { - launchwrapper = Class.forName("net.minecraft.launchwrapper.Launch", true, getClass().getClassLoader()); + launchwrapper = Class + .forName("com.gtnewhorizons.retrofuturabootstrap.Main", true, getClass().getClassLoader()); Class.forName("org.objectweb.asm.Type", true, getClass().getClassLoader()); } catch (Exception e) { - System.err.printf( + System.err.print( "We appear to be missing one or more essential library files.\n" + "You will need to add them to your server before FML and Forge will run successfully."); e.printStackTrace(System.err); @@ -36,10 +36,13 @@ public class ServerLaunchWrapper { System.arraycopy(args, 0, allArgs, 2, args.length); main.invoke(null, (Object) allArgs); } catch (Exception e) { - System.err.printf("A problem occurred running the Server launcher."); + Throwable cause = e; + if (e instanceof InvocationTargetException) { + cause = e.getCause(); + } + System.err.print("A problem occurred running the Server launcher."); e.printStackTrace(System.err); System.exit(1); } } - } diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/ExtensibleEnumTransformerHelper.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ExtensibleEnumTransformer.java similarity index 82% rename from src/main/java/me/eigenraven/lwjgl3ify/core/ExtensibleEnumTransformerHelper.java rename to src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ExtensibleEnumTransformer.java index 499151f..7e2a080 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/ExtensibleEnumTransformerHelper.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ExtensibleEnumTransformer.java @@ -1,13 +1,16 @@ -/* - * Copyright (c) Forge Development LLC and contributors SPDX-License-Identifier: LGPL-2.1-only - */ -package me.eigenraven.lwjgl3ify.core; +package me.eigenraven.lwjgl3ify.rfb.transformers; +import java.util.ArrayList; import java.util.List; +import java.util.jar.Manifest; import java.util.stream.Collectors; import org.apache.commons.lang3.ArrayUtils; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.intellij.lang.annotations.Pattern; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -17,42 +20,76 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; +import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; + import me.eigenraven.lwjgl3ify.IExtensibleEnum; import me.eigenraven.lwjgl3ify.api.MakeEnumExtensible; +import me.eigenraven.lwjgl3ify.rfb.EarlyConfig; -public class ExtensibleEnumTransformerHelper { +public class ExtensibleEnumTransformer implements RfbClassTransformer { - private final Logger LOGGER = Lwjgl3ifyCoremod.LOGGER; + private final Logger LOGGER = LogManager.getLogger("lwjgl3ify"); private final Type STRING = Type.getType(String.class); private final Type ENUM = Type.getType(Enum.class); public final Type MARKER_IFACE = Type.getType(IExtensibleEnum.class); public final Type MARKER_ANNOTATION = Type.getType(MakeEnumExtensible.class); private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); // Don't directly reference - // this to prevent class - // loading. + // this to prevent class + // loading. private final String ADD_DESC = Type .getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class)); private final Type UNSAFE_HACKS = Type.getType("Lme/eigenraven/lwjgl3ify/UnsafeHacks;"); // Again, not direct - // reference to prevent - // class loading. + // reference to prevent + // class loading. private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class)); private final String NAME_DESC = Type.getMethodDescriptor(STRING); private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING); public static final String CREATE_METHOD_NAME = "dynamicCreate"; - /** - * @return Were changes made? - */ - public boolean processClassWithFlags(final ClassNode classNode, final Type classType) { - if ((classNode.access & Opcodes.ACC_ENUM) == 0) return false; + @Pattern("[a-z0-9-]+") + @Override + public @NotNull String id() { + return "extensible-enum"; + } + + @Override + public boolean shouldTransformClass(@NotNull ExtensibleClassLoader extensibleClassLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle classNodeHandle) { + return classNodeHandle.getFastAccessor() != null && classNodeHandle.getFastAccessor() + .isEnum(); + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader extensibleClassLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle classNodeHandle) { + final Type classType = Type.getObjectType(className.replace('.', '/')); + final ClassNode classNode = classNodeHandle.getNode(); + if (classNode == null) { + return; + } + + if (EarlyConfig.EXTENSIBLE_ENUMS.contains(className)) { + if (classNode.interfaces == null) { + classNode.interfaces = new ArrayList<>(1); + } + classNode.interfaces.add(MARKER_IFACE.getInternalName()); + } Type array = Type.getType("[" + classType.getDescriptor()); final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC; - FieldNode values = classNode.fields.stream() + final FieldNode values = classNode.fields.stream() .filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)) .findFirst() - .orElse(null); + .orElse( + classNode.fields.stream() + .filter(f -> f.desc.contentEquals(array.getDescriptor()) && f.name.equals("$VALUES")) + .findFirst() + .orElse(null)); boolean process = false; if (classNode.interfaces.contains(MARKER_IFACE.getInternalName())) { @@ -65,9 +102,12 @@ public class ExtensibleEnumTransformerHelper { } } if (!process) { - return false; + return; } + classNodeHandle.computeMaxs(); + classNodeHandle.computeFrames(); + List constructors = classNode.methods.stream() .filter(m -> m.name.equals("")) .collect(Collectors.toList()); @@ -271,6 +311,5 @@ public class ExtensibleEnumTransformerHelper { ins.areturn(classType); } }); - return true; } } diff --git a/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ForgePatchTransformer.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ForgePatchTransformer.java new file mode 100644 index 0000000..d97793a --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/ForgePatchTransformer.java @@ -0,0 +1,204 @@ +package me.eigenraven.lwjgl3ify.rfb.transformers; + +import static org.objectweb.asm.Opcodes.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.jar.Manifest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.commons.InstructionAdapter; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; + +public class ForgePatchTransformer implements RfbClassTransformer { + + final Logger logger = LogManager.getLogger("Lwjgl3ifyForgePatches"); + + @Override + public @NotNull String id() { + return "forge-patch"; + } + + public static final String TRACING_PRINT_STREAM = "cpw.mods.fml.common.TracingPrintStream"; + public static final String FML_SECURITY_MANAGER = "cpw.mods.fml.relauncher.FMLSecurityManager"; + public static final String ENUM_HELPER = "net.minecraftforge.common.util.EnumHelper"; + + public static final String[] PATCHED_CLASSES = new String[] { TRACING_PRINT_STREAM, FML_SECURITY_MANAGER, + ENUM_HELPER }; + + @Override + public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle classNode) { + for (final String toPatch : PATCHED_CLASSES) { + if (toPatch.equals(className)) { + return true; + } + } + return false; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + if (!classNode.isPresent()) { + return; + } + switch (className) { + case TRACING_PRINT_STREAM -> tfTracingPrintStream(classNode); + case FML_SECURITY_MANAGER -> tfFmlSecurityManager(classNode); + case ENUM_HELPER -> tfEnumHelper(classNode); + } + } + + private void tfTracingPrintStream(@NotNull ClassNodeHandle handle) { + // Add a close() override that does not close the underlying stream + // Pack200 tries to close this stream when loading patches. + final ClassNode node = handle.getNode(); + if (node == null || node.methods == null) { + logger.error("Tracing print stream missing class data"); + return; + } + if (node.methods.stream() + .anyMatch(m -> "close".equals(m.name) && "()V".equals(m.desc))) { + logger.warn("{} already has a close method", TRACING_PRINT_STREAM); + // Someone already added a close method + return; + } + final MethodVisitor mv = node.visitMethod(ACC_PUBLIC, "close", "()V", null, null); + mv.visitInsn(RETURN); + mv.visitMaxs(0, 1); + mv.visitEnd(); + } + + private static Integer tryIconst(AbstractInsnNode i) { + return switch (i.getOpcode()) { + case ICONST_0 -> 0; + case ICONST_1 -> 1; + case ICONST_2 -> 2; + case ICONST_3 -> 3; + case ICONST_4 -> 4; + case ICONST_5 -> 5; + case ICONST_M1 -> -1; + case LDC -> { + final Object cst = ((LdcInsnNode) i).cst; + if (cst instanceof Integer) { + yield (Integer) cst; + } else { + yield null; + } + } + default -> null; + }; + } + + private static AbstractInsnNode makeIconst(int i) { + return switch (i) { + case 0 -> new InsnNode(ICONST_0); + case 1 -> new InsnNode(ICONST_1); + case 2 -> new InsnNode(ICONST_2); + case 3 -> new InsnNode(ICONST_3); + case 4 -> new InsnNode(ICONST_4); + case 5 -> new InsnNode(ICONST_5); + case -1 -> new InsnNode(ICONST_M1); + default -> new LdcInsnNode(i); + }; + } + + private void tfFmlSecurityManager(@NotNull ClassNodeHandle handle) { + // Fix an ArrayIndexOutOfBounds exception due to off-by-1 array length checks + final ClassNode node = handle.getNode(); + if (node == null || node.methods == null) { + logger.error("FML security manager missing class data"); + return; + } + final MethodNode checkPermission = node.methods.stream() + .filter(m -> "checkPermission".equals(m.name) && "(Ljava/security/Permission;)V".equals(m.desc)) + .findFirst() + .orElse(null); + if (checkPermission == null || checkPermission.instructions == null + || checkPermission.instructions.size() < 5) { + logger.error("FML security manager missing the checkPermission method"); + return; + } + final InsnList chkInsns = checkPermission.instructions; + // Search for a iconst_A; if_icmple; _; iconst_A+1 pattern and fix it + final int insns = chkInsns.size(); + int matches = 0; + for (int i = 0; i < insns - 4; i++) { + final AbstractInsnNode i_iconstA = chkInsns.get(i); + final AbstractInsnNode i_icmple = chkInsns.get(i + 1); + final AbstractInsnNode i_iconstAp1 = chkInsns.get(i + 3); + if (i_icmple.getOpcode() != IF_ICMPLE) { + continue; + } + final Integer A = tryIconst(i_iconstA); + final Integer Ap1 = tryIconst(i_iconstAp1); + if (A == null || Ap1 == null || Ap1 != A + 1) { + continue; + } + matches++; + chkInsns.set(i_iconstA, makeIconst(A + 1)); + } + + if (matches < 2) { + logger.warn("Only found {}<2 instances of AIOOB fixes in FMLSecurityManager", matches); + } + } + + private void tfEnumHelper(@NotNull ClassNodeHandle handle) { + // Redirect everything to our own implementation, too much has changed + final ClassNode node = handle.getNode(); + if (node == null || node.methods == null) { + logger.error("Enum Helper missing class data"); + return; + } + final String INTERNAL_TARGET = "me/eigenraven/lwjgl3ify/EnumHelper"; + final List newMethods = new ArrayList<>(); + for (final MethodNode oldMethod : node.methods) { + if (oldMethod.instructions == null || "".equals(oldMethod.name)) { + newMethods.add(oldMethod); + continue; + } + final Type desc = Type.getMethodType(oldMethod.desc); + final boolean isStatic = (oldMethod.access & ACC_STATIC) != 0; + if (!isStatic) { + newMethods.add(oldMethod); + continue; + } + final MethodNode newMethod = new MethodNode( + oldMethod.access, + oldMethod.name, + oldMethod.desc, + oldMethod.signature, + null); + final InsnList insns = newMethod.instructions; + insns.clear(); + final InstructionAdapter ihelp = new InstructionAdapter(newMethod); + final Type[] args = desc.getArgumentTypes(); + for (int i = 0; i < args.length; i++) { + ihelp.load(i, args[i]); + } + ihelp.invokestatic(INTERNAL_TARGET, newMethod.name, newMethod.desc, false); + ihelp.areturn(desc.getReturnType()); + ihelp.visitMaxs(args.length, args.length); + ihelp.visitEnd(); + newMethods.add(newMethod); + } + node.methods = newMethods; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/LwjglRedirectTransformer.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/LwjglRedirectTransformer.java new file mode 100644 index 0000000..b150d29 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/LwjglRedirectTransformer.java @@ -0,0 +1,160 @@ +package me.eigenraven.lwjgl3ify.rfb.transformers; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.stream.Stream; + +import net.minecraft.launchwrapper.LaunchClassLoader; + +import org.intellij.lang.annotations.Pattern; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; +import org.objectweb.asm.tree.ClassNode; + +import com.gtnewhorizons.retrofuturabootstrap.api.ClassHeaderMetadata; +import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import me.eigenraven.lwjgl3ify.core.Lwjgl3ifyCoremod; + +public class LwjglRedirectTransformer extends Remapper implements RfbClassTransformer { + + /** Attribute to set to "true" on a JAR to skip class transforms from this transformer entirely */ + public static final Attributes.Name MANIFEST_SAFE_ATTRIBUTE = new Attributes.Name("Lwjgl3ify-Aware"); + + int remaps = 0, calls = 0; + + public LwjglRedirectTransformer() { + excludedPackages = Stream.concat(Arrays.stream(fromPrefixes), Arrays.stream(toPrefixes)) + .map(s -> s.replace('/', '.')) + .toArray(String[]::new); + quickScans = Arrays.stream(fromPrefixes) + .map(s -> s.getBytes(StandardCharsets.UTF_8)) + .toArray(byte[][]::new); + } + + @Override + public @NotNull String @Nullable [] sortAfter() { + return new String[] { "*", "mixin:mixin" }; + } + + @Pattern("[a-z0-9-]+") + @Override + public @NotNull String id() { + return "redirect"; + } + + @Override + public @NotNull String @Nullable [] additionalExclusions() { + return excludedPackages; + } + + @Override + public void onRegistration(@NotNull ExtensibleClassLoader classLoader) { + if (classLoader instanceof LaunchClassLoader lcl) { + lcl.addClassLoaderExclusion("me.eigenraven.lwjgl3ify.pack200."); + } + } + + @Override + public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle nodeHandle) { + if (!nodeHandle.isPresent()) { + return false; + } + if (manifest != null && "true".equals( + manifest.getMainAttributes() + .getValue(MANIFEST_SAFE_ATTRIBUTE))) { + return false; + } + if (!nodeHandle.isOriginal()) { + return true; + } + final byte[] original = nodeHandle.getOriginalBytes(); + if (original == null) { + return false; + } + for (final byte[] pattern : quickScans) { + if (ClassHeaderMetadata.hasSubstring(original, pattern)) { + return true; + } + } + return false; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle nodeHandle) { + final ClassNode inputNode = nodeHandle.getNode(); + if (inputNode == null) { + return; + } + + final ClassNode outputNode = new ClassNode(); + final ClassVisitor visitor = new EscapingClassRemapper(outputNode); + + try { + inputNode.accept(visitor); + } catch (Lwjgl3AwareException e) { + return; + } catch (Exception e) { + Lwjgl3ifyCoremod.LOGGER.warn("Couldn't remap class {}", className, e); + return; + } + + nodeHandle.setNode(outputNode); + } + + final String[] fromPrefixes = new String[] { "org/lwjgl/", "javax/xml/bind/", "java/util/jar/Pack200", + "jdk/nashorn/", "com/mumfrey/liteloader/launch/ClassPathUtilities", "javax/activity/InvalidActivityException" }; + final String[] toPrefixes = new String[] { "org/lwjglx/", "jakarta/xml/bind/", + "me/eigenraven/lwjgl3ify/redirects/Pack200", "org/openjdk/nashorn/", + "me/eigenraven/lwjgl3ify/redirects/LiteLoaderClassPathUtilities", + "me/eigenraven/lwjgl3ify/redirects/InvalidActivityException" }; + final byte[][] quickScans; + final String[] excludedPackages; + + @Override + public String map(String typeName) { + if (typeName == null) { + return null; + } + calls++; + for (int pfx = 0; pfx < fromPrefixes.length; pfx++) { + if (typeName.startsWith(fromPrefixes[pfx])) { + remaps++; + return toPrefixes[pfx] + typeName.substring(fromPrefixes[pfx].length()); + } + } + + return typeName; + } + + public static class Lwjgl3AwareException extends RuntimeException { + } + + public class EscapingClassRemapper extends ClassRemapper { + + public EscapingClassRemapper(ClassVisitor visitor) { + super(visitor, LwjglRedirectTransformer.this); + } + + @Override + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + if (desc.equals(Type.getDescriptor(Lwjgl3Aware.class))) { + throw new Lwjgl3AwareException(); + } + return super.visitAnnotation(desc, visible); + } + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/UnfinalizeObjectHoldersTransformer.java b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/UnfinalizeObjectHoldersTransformer.java new file mode 100644 index 0000000..2d82f39 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/rfb/transformers/UnfinalizeObjectHoldersTransformer.java @@ -0,0 +1,109 @@ +package me.eigenraven.lwjgl3ify.rfb.transformers; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.Manifest; + +import org.intellij.lang.annotations.Pattern; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; + +import com.gtnewhorizons.retrofuturabootstrap.api.ClassHeaderMetadata; +import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; + +import me.eigenraven.lwjgl3ify.WasFinalObjectHolder; +import me.eigenraven.lwjgl3ify.core.Lwjgl3ifyCoremod; + +public class UnfinalizeObjectHoldersTransformer implements RfbClassTransformer { + + final byte[] QUICKSCAN_BYTES = "cpw/mods/fml/common/registry/GameRegistry".getBytes(StandardCharsets.UTF_8); + + @Pattern("[a-z0-9-]+") + @Override + public @NotNull String id() { + return "unfinalize-object-holders"; + } + + @Override + public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle classNode) { + if (!classNode.isPresent()) { + return false; + } + if (className.equals("net.minecraft.init.Blocks") || className.equals("net.minecraft.init.Items")) { + return true; + } + if (classNode.isOriginal()) { + return ClassHeaderMetadata.hasSubstring(classNode.getOriginalBytes(), QUICKSCAN_BYTES); + } else { + return true; + } + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String name, @NotNull ClassNodeHandle classNodeHandle) { + final ClassNode node = classNodeHandle.getNode(); + if (node == null) { + return; + } + boolean transformClass = false; + boolean workDone = false; + if (name.equals("net.minecraft.init.Blocks") || name.equals("net.minecraft.init.Items")) { + transformClass = true; + } + transformClass |= isHolder(node.visibleAnnotations); + int fieldsModified = 0; + for (FieldNode field : node.fields) { + boolean transform = transformClass; + if (!transform) { + transform = isHolder(field.visibleAnnotations); + } + if (transform) { + workDone = true; + if ((field.access & Opcodes.ACC_FINAL) != 0) { + if (field.visibleAnnotations == null) { + field.visibleAnnotations = new ArrayList<>(1); + field.visibleAnnotations + .add(new AnnotationNode(Type.getDescriptor(WasFinalObjectHolder.class))); + } + field.access = field.access & (~Opcodes.ACC_FINAL); + } + fieldsModified++; + } + } + if (workDone) { + Lwjgl3ifyCoremod.LOGGER.debug("Unfinalized {} Holder fields in {}", fieldsModified, name); + } + } + + private static boolean isHolder(List annotations) { + if (annotations == null) { + return false; + } + for (AnnotationNode annotationNode : annotations) { + if (annotationNode.desc.contains("cpw/mods/fml/common/registry/GameRegistry$ObjectHolder")) { + return true; + } + if (annotationNode.desc.contains("cpw/mods/fml/common/registry/GameRegistry$ItemStackHolder")) { + return true; + } + if (annotationNode.desc.contains("cpw/mods/fml/common/registry/GameRegistry/ObjectHolder")) { + return true; + } + if (annotationNode.desc.contains("cpw/mods/fml/common/registry/GameRegistry/ItemStackHolder")) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/org/lwjglx/PointerBuffer.java b/src/main/java/org/lwjglx/PointerBuffer.java index 1cd17b8..be42979 100644 --- a/src/main/java/org/lwjglx/PointerBuffer.java +++ b/src/main/java/org/lwjglx/PointerBuffer.java @@ -50,6 +50,16 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer { super(ver3.address(), getContainer(ver3), ver3.position(), ver3.position(), ver3.limit(), ver3.capacity()); } + public PointerBuffer(ByteBuffer buffer) { + this( + org.lwjgl.system.MemoryUtil.memAddress(buffer), + buffer, + 0, + buffer.position(), + buffer.limit(), + buffer.capacity()); + } + /** * Allocates a new pointer buffer. * @@ -85,4 +95,8 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer { public static PointerBuffer create(ByteBuffer source) { return new PointerBuffer(org.lwjgl.PointerBuffer.create(source)); } + + public static int getPointerSize() { + return org.lwjgl.PointerBuffer.POINTER_SIZE; + } } diff --git a/src/main/java/org/lwjglx/opengl/ContextAttribs.java b/src/main/java/org/lwjglx/opengl/ContextAttribs.java index 5c05013..ed5d3e0 100644 --- a/src/main/java/org/lwjglx/opengl/ContextAttribs.java +++ b/src/main/java/org/lwjglx/opengl/ContextAttribs.java @@ -15,77 +15,440 @@ */ package org.lwjglx.opengl; +import java.nio.IntBuffer; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLUtil; + public final class ContextAttribs { - public ContextAttribs() {} + // ATTRIBUTES - public ContextAttribs(final int majorVersion, final int minorVersion) {} + public static final int CONTEXT_MAJOR_VERSION_ARB = 0x2091; + public static final int CONTEXT_MINOR_VERSION_ARB = 0x2092; + public static final int CONTEXT_PROFILE_MASK_ARB = 0x9126, CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001, + CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002, CONTEXT_ES2_PROFILE_BIT_EXT = 0x00000004; + + public static final int CONTEXT_FLAGS_ARB = 0x2094, CONTEXT_DEBUG_BIT_ARB = 0x0001, + CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002, CONTEXT_ROBUST_ACCESS_BIT_ARB = 0x00000004, + CONTEXT_RESET_ISOLATION_BIT_ARB = 0x00000008; + + public static final int CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256, NO_RESET_NOTIFICATION_ARB = 0x8261, + LOSE_CONTEXT_ON_RESET_ARB = 0x8252; + + public static final int CONTEXT_RELEASE_BEHABIOR_ARB = 0x2097, CONTEXT_RELEASE_BEHAVIOR_NONE_ARB = 0x0000, + CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB = 0x2098; + + public static final int CONTEXT_LAYER_PLANE_ARB = 0x2093; // WGL-only + + // STATE + + private int majorVersion; + private int minorVersion; + + private int profileMask; + private int contextFlags; + + private int contextResetNotificationStrategy = NO_RESET_NOTIFICATION_ARB; + private int contextReleaseBehavior = CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB; + + private int layerPlane; + + // CONSTRUCTORS + + /** + * Creates the default ContextAttribs instance. No special attributes will be used when creating the OpenGL context. + */ + public ContextAttribs() { + this(1, 0); + } + + /** Creates a ContextAttribs instance for the given OpenGL version. */ + public ContextAttribs(int majorVersion, int minorVersion) { + this(majorVersion, minorVersion, 0, 0); + } + + /** + * Creates a new ContextAttribs instance with the given attributes. + * + * @param majorVersion the major OpenGL version + * @param minorVersion the minor OpenGL version + * @param profileMask the context profile mask. One of:
+ * {@link #CONTEXT_CORE_PROFILE_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, + * {@link #CONTEXT_ES2_PROFILE_BIT_EXT} + */ + public ContextAttribs(int majorVersion, int minorVersion, int profileMask) { + this(majorVersion, minorVersion, 0, profileMask); + } + + /** + * Creates a new ContextAttribs instance with the given attributes. + * + * @param majorVersion the major OpenGL version + * @param minorVersion the minor OpenGL version + * @param profileMask the context profile mask. One of:
+ * {@link #CONTEXT_CORE_PROFILE_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, + * {@link #CONTEXT_ES2_PROFILE_BIT_EXT} + * @param contextFlags the context flags, a bitfield value. One or more of:
+ * {@link #CONTEXT_DEBUG_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, + * {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB}, {@link #CONTEXT_RESET_ISOLATION_BIT_ARB} + */ + public ContextAttribs(int majorVersion, int minorVersion, int profileMask, int contextFlags) { + if (majorVersion < 0 || 4 < majorVersion + || minorVersion < 0 + || (majorVersion == 4 && 5 < minorVersion) + || (majorVersion == 3 && 3 < minorVersion) + || (majorVersion == 2 && 1 < minorVersion) + || (majorVersion == 1 && 5 < minorVersion)) + throw new IllegalArgumentException( + "Invalid OpenGL version specified: " + majorVersion + '.' + minorVersion); + + if (1 < Integer.bitCount(profileMask) || CONTEXT_ES2_PROFILE_BIT_EXT < profileMask) + throw new IllegalArgumentException( + "Invalid profile mask specified: " + Integer.toBinaryString(profileMask)); + + if (0xF < contextFlags) throw new IllegalArgumentException( + "Invalid context flags specified: " + Integer.toBinaryString(profileMask)); + + this.majorVersion = majorVersion; + this.minorVersion = minorVersion; + + this.profileMask = profileMask; + this.contextFlags = contextFlags; + } + + // Copy constructor + private ContextAttribs(ContextAttribs other) { + this.majorVersion = other.majorVersion; + this.minorVersion = other.minorVersion; + + this.profileMask = other.profileMask; + this.contextFlags = other.contextFlags; + + this.contextResetNotificationStrategy = other.contextResetNotificationStrategy; + this.contextReleaseBehavior = other.contextReleaseBehavior; + + this.layerPlane = other.layerPlane; + } + + // GETTERS + + /** Returns the {@link #CONTEXT_MAJOR_VERSION_ARB} value. */ public int getMajorVersion() { - return 0; + return majorVersion; } + /** Returns the {@link #CONTEXT_MINOR_VERSION_ARB} value. */ public int getMinorVersion() { - return 0; + return minorVersion; } - public int getLayerPlane() { - return 0; + /** Returns the {@link #CONTEXT_PROFILE_MASK_ARB} value. */ + public int getProfileMask() { + return profileMask; } - public boolean isDebug() { - return false; - } - - public boolean isForwardCompatible() { - return false; + private boolean hasMask(int mask) { + return profileMask == mask; } + /** Returns true if the {@link #CONTEXT_CORE_PROFILE_BIT_ARB} has been set. */ public boolean isProfileCore() { - return false; + return hasMask(CONTEXT_CORE_PROFILE_BIT_ARB); } + /** Returns true if the {@link #CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB} has been set. */ public boolean isProfileCompatibility() { - return false; + return hasMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB); } + /** Returns true if the {@link #CONTEXT_ES2_PROFILE_BIT_EXT} has been set. */ public boolean isProfileES() { - return false; + return hasMask(CONTEXT_ES2_PROFILE_BIT_EXT); } - public ContextAttribs withLayer(final int layerPlane) { - return null; + /** Returns the {@link #CONTEXT_FLAGS_ARB} value. */ + public int getContextFlags() { + return contextFlags; } - public ContextAttribs withDebug(final boolean debug) { - return null; + private boolean hasFlag(int flag) { + return (contextFlags & flag) != 0; } - public ContextAttribs withForwardCompatible(final boolean forwardCompatible) { - return null; + /** Returns true if the {@link #CONTEXT_DEBUG_BIT_ARB} has been set. */ + public boolean isDebug() { + return hasFlag(CONTEXT_DEBUG_BIT_ARB); } - public ContextAttribs withProfileCore(final boolean profileCore) { - return null; + /** Returns true if the {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB} has been set. */ + public boolean isForwardCompatible() { + return hasFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB); } - public ContextAttribs withProfileCompatibility(final boolean profileCompatibility) { - return null; + /** Returns true if the {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB} has been set. */ + public boolean isRobustAccess() { + return hasFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB); } - public ContextAttribs withProfileES(final boolean profileES) { - return null; + /** Returns true if the {@link #CONTEXT_RESET_ISOLATION_BIT_ARB} has been set. */ + public boolean isContextResetIsolation() { + return hasFlag(CONTEXT_RESET_ISOLATION_BIT_ARB); } - public ContextAttribs withLoseContextOnReset(final boolean loseContextOnReset) { - return null; + /** Returns the {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} value. */ + public int getContextResetNotificationStrategy() { + return contextResetNotificationStrategy; } - public ContextAttribs withContextResetIsolation(final boolean contextResetIsolation) { - return null; + /** + * Returns true if the {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} has been set to + * {@link #LOSE_CONTEXT_ON_RESET_ARB}. + * + * @deprecated use {@link #getContextResetNotificationStrategy} instead + */ + public boolean isLoseContextOnReset() { + return contextResetNotificationStrategy == LOSE_CONTEXT_ON_RESET_ARB; + } + + /** Returns the {@link #CONTEXT_RELEASE_BEHABIOR_ARB} value. */ + public int getContextReleaseBehavior() { + return contextReleaseBehavior; + } + + /** Returns the {@link #CONTEXT_LAYER_PLANE_ARB} value. */ + public int getLayerPlane() { + return layerPlane; + } + + // CHAIN CONFIGURATION PATTERN + + private ContextAttribs toggleMask(int mask, boolean value) { + if (value == hasMask(mask)) return this; + + ContextAttribs attribs = new ContextAttribs(this); + attribs.profileMask = value ? mask : 0; + return attribs; + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_CORE_PROFILE_BIT_ARB} bit in + * {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value. + * If {@code profileCore} is true, all other bits in the mask are cleared. + */ + public ContextAttribs withProfileCore(boolean profileCore) { + if (majorVersion < 3 || (majorVersion == 3 && minorVersion < 2)) + throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher."); + + return toggleMask(CONTEXT_CORE_PROFILE_BIT_ARB, profileCore); + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB} bit in + * {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value. + * If {@code profileCompatibility} is true, all other bits in the mask are cleared. + */ + public ContextAttribs withProfileCompatibility(boolean profileCompatibility) { + if (majorVersion < 3 || (majorVersion == 3 && minorVersion < 2)) + throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher."); + + return toggleMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, profileCompatibility); + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_ES2_PROFILE_BIT_EXT} bit in + * {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value. + * If {@code profileES} is true, all other bits in the mask are cleared. + */ + public ContextAttribs withProfileES(boolean profileES) { + if (!(majorVersion == 2 && minorVersion == 0)) + throw new IllegalArgumentException("The OpenGL ES profile is only supported on OpenGL version 2.0."); + + return toggleMask(CONTEXT_ES2_PROFILE_BIT_EXT, profileES); + } + + private ContextAttribs toggleFlag(int flag, boolean value) { + if (value == hasFlag(flag)) return this; + + ContextAttribs attribs = new ContextAttribs(this); + attribs.contextFlags ^= flag; // toggle bit + return attribs; + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_DEBUG_BIT_ARB} bit in + * {@link #CONTEXT_FLAGS_ARB} set to the given value. + */ + public ContextAttribs withDebug(boolean debug) { + return toggleFlag(CONTEXT_DEBUG_BIT_ARB, debug); + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB} bit in + * {@link #CONTEXT_FLAGS_ARB} set to the given value. + */ + public ContextAttribs withForwardCompatible(boolean forwardCompatible) { + return toggleFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, forwardCompatible); + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB} bit in + * {@link #CONTEXT_FLAGS_ARB} set to the given value. + */ + public ContextAttribs withRobustAccess(boolean robustAccess) { + return toggleFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB, robustAccess); + } + + /** + * Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_RESET_ISOLATION_BIT_ARB} bit in + * {@link #CONTEXT_FLAGS_ARB} set to the given value. + */ + public ContextAttribs withContextResetIsolation(boolean contextResetIsolation) { + return toggleFlag(CONTEXT_RESET_ISOLATION_BIT_ARB, contextResetIsolation); + } + + /** + * Returns a ContextAttribs instance with {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} set to the given + * strategy. The default context reset notification + * strategy is {@link #NO_RESET_NOTIFICATION_ARB}. + * + * @param strategy the context reset notification strategy. One of:
+ * {@link #NO_RESET_NOTIFICATION_ARB}, {@link #LOSE_CONTEXT_ON_RESET_ARB} + * + * @return the new ContextAttribs + */ + public ContextAttribs withResetNotificationStrategy(int strategy) { + if (strategy == contextResetNotificationStrategy) return this; + + if (!(strategy == NO_RESET_NOTIFICATION_ARB || strategy == LOSE_CONTEXT_ON_RESET_ARB)) + throw new IllegalArgumentException( + "Invalid context reset notification strategy specified: 0x" + LWJGLUtil.toHexString(strategy)); + + ContextAttribs attribs = new ContextAttribs(this); + attribs.contextResetNotificationStrategy = strategy; + return attribs; + } + + /** + * Returns a ContextAttribs instance with {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} set to + * {@link #LOSE_CONTEXT_ON_RESET_ARB} if the parameter is + * true or to {@link #NO_RESET_NOTIFICATION_ARB} if the parameter is false. + * + * @param loseContextOnReset the context reset notification strategy + * + * @return the new ContextAttribs + * + * @deprecated use {@link #withResetNotificationStrategy} instead + */ + public ContextAttribs withLoseContextOnReset(boolean loseContextOnReset) { + return withResetNotificationStrategy( + loseContextOnReset ? LOSE_CONTEXT_ON_RESET_ARB : NO_RESET_NOTIFICATION_ARB); + } + + /** + * Returns a ContextAttribs instance with {@link #CONTEXT_RELEASE_BEHABIOR_ARB} set to the given behavior. The + * default context release behavior is + * {@link #CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB}. + * + * @param behavior the context release behavior. One of:
+ * {@link #CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB}, {@link #CONTEXT_RELEASE_BEHAVIOR_NONE_ARB} + * + * @return the new ContextAttribs + */ + public ContextAttribs withContextReleaseBehavior(int behavior) { + if (behavior == contextReleaseBehavior) return this; + + if (!(behavior == CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB || behavior == CONTEXT_RELEASE_BEHAVIOR_NONE_ARB)) + throw new IllegalArgumentException( + "Invalid context release behavior specified: 0x" + LWJGLUtil.toHexString(behavior)); + + ContextAttribs attribs = new ContextAttribs(this); + attribs.contextReleaseBehavior = behavior; + return attribs; + } + + /** Returns a new {@code ContextAttribs} instance with {@link #CONTEXT_LAYER_PLANE_ARB} set to the given value. */ + public ContextAttribs withLayer(int layerPlane) { + if (LWJGLUtil.getPlatform() != LWJGLUtil.PLATFORM_WINDOWS) throw new IllegalArgumentException( + "The CONTEXT_LAYER_PLANE_ARB attribute is supported only on the Windows platform."); + + if (layerPlane == this.layerPlane) return this; + + if (layerPlane < 0) throw new IllegalArgumentException("Invalid layer plane specified: " + layerPlane); + + ContextAttribs attribs = new ContextAttribs(this); + attribs.layerPlane = layerPlane; + return attribs; + } + + IntBuffer getAttribList() { + if (LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX) return null; + + LinkedHashMap map = new LinkedHashMap(8); + + if (!(majorVersion == 1 && minorVersion == 0)) { + map.put(CONTEXT_MAJOR_VERSION_ARB, majorVersion); + map.put(CONTEXT_MINOR_VERSION_ARB, minorVersion); + } + + if (contextFlags != 0) map.put(CONTEXT_FLAGS_ARB, contextFlags); + + if (profileMask != 0) map.put(CONTEXT_PROFILE_MASK_ARB, profileMask); + + if (contextResetNotificationStrategy != NO_RESET_NOTIFICATION_ARB) + map.put(CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, contextResetNotificationStrategy); + + if (contextReleaseBehavior != CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB) + map.put(CONTEXT_RELEASE_BEHABIOR_ARB, contextReleaseBehavior); + + if (layerPlane != 0) map.put(CONTEXT_LAYER_PLANE_ARB, layerPlane); + + if (map.isEmpty()) return null; + + IntBuffer attribs = BufferUtils.createIntBuffer((map.size() * 2) + 1); + for (Map.Entry attrib : map.entrySet()) { + attribs.put(attrib.getKey()) + .put(attrib.getValue()); + } + attribs.put(0); + attribs.rewind(); + return attribs; } public String toString() { - return null; + StringBuilder sb = new StringBuilder(32); + + sb.append("ContextAttribs:"); + sb.append(" Version=") + .append(majorVersion) + .append('.') + .append(minorVersion); + + if (profileMask != 0) { + sb.append(", Profile="); + if (hasMask(CONTEXT_CORE_PROFILE_BIT_ARB)) sb.append("CORE"); + else if (hasMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB)) sb.append("COMPATIBLITY"); + else if (hasMask(CONTEXT_ES2_PROFILE_BIT_EXT)) sb.append("ES2"); + else sb.append("*unknown*"); + } + + if (contextFlags != 0) { + if (hasFlag(CONTEXT_DEBUG_BIT_ARB)) sb.append(", DEBUG"); + if (hasFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)) sb.append(", FORWARD_COMPATIBLE"); + if (hasFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB)) sb.append(", ROBUST_ACCESS"); + if (hasFlag(CONTEXT_RESET_ISOLATION_BIT_ARB)) sb.append(", RESET_ISOLATION"); + } + + if (contextResetNotificationStrategy != NO_RESET_NOTIFICATION_ARB) sb.append(", LOSE_CONTEXT_ON_RESET"); + if (contextReleaseBehavior != CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB) sb.append(", RELEASE_BEHAVIOR_NONE"); + + if (layerPlane != 0) sb.append(", Layer=") + .append(layerPlane); + + return sb.toString(); } + } diff --git a/src/main/java/org/lwjglx/opengl/Display.java b/src/main/java/org/lwjglx/opengl/Display.java index 4fe1305..c37b32c 100644 --- a/src/main/java/org/lwjglx/opengl/Display.java +++ b/src/main/java/org/lwjglx/opengl/Display.java @@ -35,6 +35,7 @@ import org.lwjglx.input.Keyboard; import org.lwjglx.input.Mouse; import me.eigenraven.lwjgl3ify.Lwjgl3ify; +import me.eigenraven.lwjgl3ify.api.InputEvents; import me.eigenraven.lwjgl3ify.core.Config; public class Display { @@ -109,27 +110,28 @@ public class Display { *

* The window created will be set up in orthographic 2D projection, with 1:1 pixel ratio with GL coordinates. * - * @param pixel_format Describes the minimum specifications the context must fulfill. - * @param shared_drawable The Drawable to share context with. (optional, may be null) + * @param pixelFormat Describes the minimum specifications the context must fulfill. + * @param sharedDrawable The Drawable to share context with. (optional, may be null) * * @throws org.lwjglx.LWJGLException */ - public static void create(PixelFormat pixel_format, Drawable shared_drawable) { - System.out.println("TODO: Implement Display.create(PixelFormat, Drawable)"); // TODO - create(); - } - - public static void create(PixelFormat pixel_format, ContextAttribs attribs) { - System.out.println("TODO: Implement Display.create(PixelFormat, ContextAttribs)"); // TODO - create(); - } - - public static void create(PixelFormat pixel_format) { - System.out.println("TODO: Implement Display.create(PixelFormat)"); // TODO - create(); + public static void create(PixelFormat pixelFormat, Drawable sharedDrawable) { + create(pixelFormat, (ContextAttribs) null, sharedDrawable.getGlfwWindowId()); } public static void create() { + create(null, (ContextAttribs) null); + } + + public static void create(PixelFormat pixelFormat) { + create(pixelFormat, (ContextAttribs) null); + } + + public static void create(PixelFormat pixelFormat, ContextAttribs attribs) { + create(pixelFormat, attribs, NULL); + } + + public static void create(PixelFormat pixelFormat, ContextAttribs attribs, long sharedWindow) { if (displayCreated) { return; } @@ -144,11 +146,24 @@ public class Display { desktopDisplayMode = new DisplayMode(monitorWidth, monitorHeight, monitorBitPerPixel, monitorRefreshRate); + final int ctxMajor = (attribs != null) ? attribs.getMajorVersion() : 2; + final int ctxMinor = (attribs != null) ? attribs.getMinorVersion() : 1; + final boolean ctxForwardCompat = attribs != null && attribs.isForwardCompatible(); + final boolean ctxSrgb = pixelFormat != null ? pixelFormat.isSRGB() : Config.OPENGL_SRGB_CONTEXT; + glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, GLFW_TRUE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, ctxMajor); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, ctxMinor); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, ctxForwardCompat ? GLFW_TRUE : GLFW_FALSE); + if (attribs != null) { + if (attribs.isProfileCore()) { + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + } else if (attribs.isProfileCompatibility()) { + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); + } + } glfwWindowHint(GLFW_MAXIMIZED, Config.WINDOW_START_MAXIMIZED ? GLFW_TRUE : GLFW_FALSE); glfwWindowHint(GLFW_FOCUSED, Config.WINDOW_START_FOCUSED ? GLFW_TRUE : GLFW_FALSE); @@ -157,7 +172,7 @@ public class Display { displayVisible = !Config.WINDOW_START_ICONIFIED; glfwWindowHint(GLFW_DECORATED, Config.WINDOW_DECORATED ? GLFW_TRUE : GLFW_FALSE); - glfwWindowHint(GLFW_SRGB_CAPABLE, Config.OPENGL_SRGB_CONTEXT ? GLFW_TRUE : GLFW_FALSE); + glfwWindowHint(GLFW_SRGB_CAPABLE, ctxSrgb ? GLFW_TRUE : GLFW_FALSE); glfwWindowHint(GLFW_DOUBLEBUFFER, Config.OPENGL_DOUBLEBUFFER ? GLFW_TRUE : GLFW_FALSE); glfwWindowHint(GLFW_CONTEXT_NO_ERROR, Config.OPENGL_CONTEXT_NO_ERROR ? GLFW_TRUE : GLFW_FALSE); glfwWindowHint( @@ -173,7 +188,7 @@ public class Display { glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE); // request a non-hidpi framebuffer on Retina displays // on MacOS - Window.handle = glfwCreateWindow(mode.getWidth(), mode.getHeight(), windowTitle, NULL, NULL); + Window.handle = glfwCreateWindow(mode.getWidth(), mode.getHeight(), windowTitle, NULL, sharedWindow); if (Window.handle == 0L) { throw new IllegalStateException("Failed to create Display window"); } @@ -194,6 +209,22 @@ public class Display { KeyEvent.getKeyText(KeyCodes.lwjglToAwt(KeyCodes.glfwToLwjgl(key))), (key >= 32 && key < 127) ? ((char) key) : '?'); } + final InputEvents.KeyAction enumAction = switch (action) { + case GLFW_PRESS -> InputEvents.KeyAction.PRESSED; + case GLFW_RELEASE -> InputEvents.KeyAction.RELEASED; + case GLFW_REPEAT -> InputEvents.KeyAction.REPEATED; + default -> InputEvents.KeyAction.PRESSED; + }; + InputEvents.injectKeyEvent( + new InputEvents.KeyEvent( + KeyCodes.glfwToLwjgl(key), + key, + scancode, + enumAction, + (mods & GLFW_MOD_CONTROL) != 0, + (mods & GLFW_MOD_SHIFT) != 0, + (mods & GLFW_MOD_ALT) != 0, + (mods & GLFW_MOD_SUPER) != 0)); cancelNextChar = false; if (action == GLFW_PRESS) { if (key == GLFW_KEY_LEFT_ALT) { @@ -281,6 +312,7 @@ public class Display { Lwjgl3ify.LOG .info("[DEBUG-KEY] char window:{} codepoint:{} char:{}", window, codepoint, (char) codepoint); } + InputEvents.injectTextEvent(new InputEvents.TextEvent(String.valueOf((char) codepoint))); if (cancelNextChar) { // Char event being cancelled cancelNextChar = false; } else if (ingredientKeyEvent != null) { diff --git a/src/main/java/org/lwjglx/opengl/Drawable.java b/src/main/java/org/lwjglx/opengl/Drawable.java index ddd007e..1fff7f1 100644 --- a/src/main/java/org/lwjglx/opengl/Drawable.java +++ b/src/main/java/org/lwjglx/opengl/Drawable.java @@ -55,4 +55,8 @@ public interface Drawable { * @param properties The target properties buffer. It must have at least 4 positions remaining. */ void setCLSharingProperties(PointerBuffer properties) throws LWJGLException; + + default long getGlfwWindowId() { + return 0; + } } diff --git a/src/main/java/org/lwjglx/opengl/DrawableGL.java b/src/main/java/org/lwjglx/opengl/DrawableGL.java index 6291520..4f50c09 100644 --- a/src/main/java/org/lwjglx/opengl/DrawableGL.java +++ b/src/main/java/org/lwjglx/opengl/DrawableGL.java @@ -141,4 +141,11 @@ public class DrawableGL implements DrawableLWJGL { protected final void checkDestroyed() { if (context == null) throw new IllegalStateException("The Drawable has no context available."); } + + @Override + public long getGlfwWindowId() { + synchronized (GlobalLock.lock) { + return context.glfwWindow; + } + } } diff --git a/src/main/java/org/lwjglx/opengl/PixelFormat.java b/src/main/java/org/lwjglx/opengl/PixelFormat.java index 2345505..adaffb5 100644 --- a/src/main/java/org/lwjglx/opengl/PixelFormat.java +++ b/src/main/java/org/lwjglx/opengl/PixelFormat.java @@ -16,14 +16,17 @@ package org.lwjglx.opengl; /** - * This class describes pixel format properties for an OpenGL context. Instances of this class is used as arguments to - * Display.create(), Pbuffer.create() and AWTGLCanvas, to indicate minimum required properties. + * This class describes pixel format properties for an OpenGL context. Instances + * of this class is used as arguments to Display.create(), Pbuffer.create() and + * AWTGLCanvas, to indicate minimum required properties. *

- * Instants of this class are immutable. An example of the expected way to set the PixelFormat property values is the - * following: PixelFormat pf = new PixelFormat().withDepthBits(24).withSamples(4).withSRGB(true); + * Instants of this class are immutable. An example of the expected way to set + * the PixelFormat property values is the following: + * PixelFormat pf = new PixelFormat().withDepthBits(24).withSamples(4).withSRGB(true); *

- * WARNING: Some pixel formats are known to cause troubles on certain buggy drivers. Example: Under Windows, specifying - * samples != 0 will enable the ARB pixel format selection path, which could trigger a crash. + * WARNING: Some pixel formats are known to cause troubles on certain buggy drivers. + * Example: Under Windows, specifying samples != 0 will enable the ARB + * pixel format selection path, which could trigger a crash. * * @author elias_naur@sourceforge.net * @version $Revision$ @@ -145,7 +148,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new bits per pixel value. * * @param bpp the new bits per pixel value. - * * @return the new PixelFormat */ public PixelFormat withBitsPerPixel(final int bpp) { @@ -164,7 +166,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new alpha bits value. * * @param alpha the new alpha bits value. - * * @return the new PixelFormat */ public PixelFormat withAlphaBits(final int alpha) { @@ -183,7 +184,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new depth bits value. * * @param depth the new depth bits value. - * * @return the new PixelFormat */ public PixelFormat withDepthBits(final int depth) { @@ -202,7 +202,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new stencil bits value. * * @param stencil the new stencil bits value. - * * @return the new PixelFormat */ public PixelFormat withStencilBits(final int stencil) { @@ -221,7 +220,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new samples value. * * @param samples the new samples value. - * * @return the new PixelFormat */ public PixelFormat withSamples(final int samples) { @@ -238,7 +236,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * color samples value needs to be lower than or equal to the {@code samples} property. * * @param colorSamples the new color samples value. - * * @return the new PixelFormat */ public PixelFormat withCoverageSamples(final int colorSamples) { @@ -252,7 +249,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * @param colorSamples the new color samples value. This value must be lower than or equal to the coverage * samples value. * @param coverageSamples the new coverage samples value. - * * @return the new PixelFormat */ public PixelFormat withCoverageSamples(final int colorSamples, final int coverageSamples) { @@ -277,7 +273,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * value. * * @param num_aux_buffers the new auxiliary buffers value. - * * @return the new PixelFormat */ public PixelFormat withAuxBuffers(final int num_aux_buffers) { @@ -298,7 +293,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * accumulation buffer value. * * @param accum_bpp the new bits per pixel in the accumulation buffer value. - * * @return the new PixelFormat */ public PixelFormat withAccumulationBitsPerPixel(final int accum_bpp) { @@ -319,7 +313,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * accumulation buffer value. * * @param accum_alpha the new alpha bits in the accumulation buffer value. - * * @return the new PixelFormat */ public PixelFormat withAccumulationAlpha(final int accum_alpha) { @@ -339,7 +332,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new stereo value. * * @param stereo the new stereo value. - * * @return the new PixelFormat */ public PixelFormat withStereo(final boolean stereo) { @@ -357,7 +349,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * If floating_point is true, floating_point_packed will be reset to false. * * @param floating_point the new floating point value. - * * @return the new PixelFormat */ public PixelFormat withFloatingPoint(final boolean floating_point) { @@ -372,7 +363,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * value. If floating_point_packed is true, floating_point will be reset to false. * * @param floating_point_packed the new packed floating point value. - * * @return the new PixelFormat */ public PixelFormat withFloatingPointPacked(final boolean floating_point_packed) { @@ -390,7 +380,6 @@ public final class PixelFormat implements PixelFormatLWJGL { * Returns a new PixelFormat object with the same properties as this PixelFormat and the new sRGB value. * * @param sRGB the new floating point value. - * * @return the new PixelFormat */ public PixelFormat withSRGB(final boolean sRGB) { @@ -398,4 +387,5 @@ public final class PixelFormat implements PixelFormatLWJGL { pf.sRGB = sRGB; return pf; } + } diff --git a/src/main/java/org/lwjglx/util/input/ControllerAdapter.java b/src/main/java/org/lwjglx/util/input/ControllerAdapter.java new file mode 100644 index 0000000..5cfac02 --- /dev/null +++ b/src/main/java/org/lwjglx/util/input/ControllerAdapter.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.input; + +import org.lwjgl.input.Controller; + +/** + * Adapter for the Controller interface. It can be used as placeholder + * Controller, which doesn't do anything (eg if Controllers.create() fails and + * you don't want to take care of that). + * + * @author Onyx, Aho and all the other aliases... + */ +public class ControllerAdapter implements Controller { + + /** + * Get the name assigned to this controller. + * + * @return The name assigned to this controller + */ + public String getName() { + return "Dummy Controller"; + } + + /** + * Get the index of this controller in the collection + * + * @return The index of this controller in the collection + */ + public int getIndex() { + return 0; // -1 maybe? + } + + /** + * Retrieve the number of buttons available on this controller + * + * @return The number of butotns available on this controller + */ + public int getButtonCount() { + return 0; + } + + /** + * Get the name of the specified button. Be warned, often this is as + * exciting as "Button X" + * + * @param index The index of the button whose name should be retrieved + * @return The name of the button requested + */ + public String getButtonName(int index) { + return "button n/a"; + } + + /** + * Check if a button is currently pressed + * + * @param index The button to check + * @return True if the button is currently pressed + */ + public boolean isButtonPressed(int index) { + return false; + } + + /** + * Poll the controller for new data. This will also update events + */ + public void poll() {} + + /** + * Get the X-Axis value of the POV on this controller + * + * @return The X-Axis value of the POV on this controller + */ + public float getPovX() { + return 0f; + } + + /** + * Get the Y-Axis value of the POV on this controller + * + * @return The Y-Axis value of the POV on this controller + */ + public float getPovY() { + return 0f; + } + + /** + * Get the dead zone for a specified axis + * + * @param index The index of the axis for which to retrieve the dead zone + * @return The dead zone for the specified axis + */ + public float getDeadZone(int index) { + return 0f; + } + + /** + * Set the dead zone for the specified axis + * + * @param index The index of hte axis for which to set the dead zone + * @param zone The dead zone to use for the specified axis + */ + public void setDeadZone(int index, float zone) {} + + /** + * Retrieve the number of axes available on this controller. + * + * @return The number of axes available on this controller. + */ + public int getAxisCount() { + return 0; + } + + /** + * Get the name that's given to the specified axis + * + * @param index The index of the axis whose name should be retrieved + * @return The name of the specified axis. + */ + public String getAxisName(int index) { + return "axis n/a"; + } + + /** + * Retrieve the value thats currently available on a specified axis. The + * value will always be between 1.0 and -1.0 and will calibrate as values + * are passed read. It may be useful to get the player to wiggle the + * joystick from side to side to get the calibration right. + * + * @param index The index of axis to be read + * @return The value from the specified axis. + */ + public float getAxisValue(int index) { + return 0f; + } + + /** + * Get the value from the X axis if there is one. If no X axis is defined a + * zero value will be returned. + * + * @return The value from the X axis + */ + public float getXAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the X axis. + * + * @return The dead zone for the X axis + */ + public float getXAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the X axis + * + * @param zone The dead zone to use for the X axis + */ + public void setXAxisDeadZone(float zone) {} + + /** + * Get the value from the Y axis if there is one. If no Y axis is defined a + * zero value will be returned. + * + * @return The value from the Y axis + */ + public float getYAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the Y axis. + * + * @return The dead zone for the Y axis + */ + public float getYAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the Y axis + * + * @param zone The dead zone to use for the Y axis + */ + public void setYAxisDeadZone(float zone) {} + + /** + * Get the value from the Z axis if there is one. If no Z axis is defined a + * zero value will be returned. + * + * @return The value from the Z axis + */ + public float getZAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the Z axis. + * + * @return The dead zone for the Z axis + */ + public float getZAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the Z axis + * + * @param zone The dead zone to use for the Z axis + */ + public void setZAxisDeadZone(float zone) {} + + /** + * Get the value from the RX axis if there is one. If no RX axis is defined + * a zero value will be returned. + * + * @return The value from the RX axis + */ + public float getRXAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RX axis. + * + * @return The dead zone for the RX axis + */ + public float getRXAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RX axis + * + * @param zone The dead zone to use for the RX axis + */ + public void setRXAxisDeadZone(float zone) {} + + /** + * Get the value from the RY axis if there is one. If no RY axis is defined + * a zero value will be returned. + * + * @return The value from the RY axis + */ + public float getRYAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RY axis. + * + * @return The dead zone for the RY axis + */ + public float getRYAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RY axis + * + * @param zone The dead zone to use for the RY axis + */ + public void setRYAxisDeadZone(float zone) {} + + /** + * Get the value from the RZ axis if there is one. If no RZ axis is defined + * a zero value will be returned. + * + * @return The value from the RZ axis + */ + public float getRZAxisValue() { + return 0f; + } + + /** + * Get the dead zone for the RZ axis. + * + * @return The dead zone for the RZ axis + */ + public float getRZAxisDeadZone() { + return 0f; + } + + /** + * Set the dead zone for the RZ axis + * + * @param zone The dead zone to use for the RZ axis + */ + public void setRZAxisDeadZone(float zone) {} + + public int getRumblerCount() { + return 0; + } + + public String getRumblerName(int index) { + return "rumber n/a"; + } + + public void setRumblerStrength(int index, float strength) {} +} diff --git a/src/main/java/org/lwjglx/util/jinput/KeyMap.java b/src/main/java/org/lwjglx/util/jinput/KeyMap.java new file mode 100644 index 0000000..bed6825 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/KeyMap.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.jinput; + +import net.java.games.input.Component; + +import org.lwjgl.input.Keyboard; + +/** + * @author elias + */ +final class KeyMap { + + public static Component.Identifier.Key map(int lwjgl_key_code) { + switch (lwjgl_key_code) { + case Keyboard.KEY_ESCAPE: + return Component.Identifier.Key.ESCAPE; + case Keyboard.KEY_1: + return Component.Identifier.Key._1; + case Keyboard.KEY_2: + return Component.Identifier.Key._2; + case Keyboard.KEY_3: + return Component.Identifier.Key._3; + case Keyboard.KEY_4: + return Component.Identifier.Key._4; + case Keyboard.KEY_5: + return Component.Identifier.Key._5; + case Keyboard.KEY_6: + return Component.Identifier.Key._6; + case Keyboard.KEY_7: + return Component.Identifier.Key._7; + case Keyboard.KEY_8: + return Component.Identifier.Key._8; + case Keyboard.KEY_9: + return Component.Identifier.Key._9; + case Keyboard.KEY_0: + return Component.Identifier.Key._0; + case Keyboard.KEY_MINUS: + return Component.Identifier.Key.MINUS; + case Keyboard.KEY_EQUALS: + return Component.Identifier.Key.EQUALS; + case Keyboard.KEY_BACK: + return Component.Identifier.Key.BACK; + case Keyboard.KEY_TAB: + return Component.Identifier.Key.TAB; + case Keyboard.KEY_Q: + return Component.Identifier.Key.Q; + case Keyboard.KEY_W: + return Component.Identifier.Key.W; + case Keyboard.KEY_E: + return Component.Identifier.Key.E; + case Keyboard.KEY_R: + return Component.Identifier.Key.R; + case Keyboard.KEY_T: + return Component.Identifier.Key.T; + case Keyboard.KEY_Y: + return Component.Identifier.Key.Y; + case Keyboard.KEY_U: + return Component.Identifier.Key.U; + case Keyboard.KEY_I: + return Component.Identifier.Key.I; + case Keyboard.KEY_O: + return Component.Identifier.Key.O; + case Keyboard.KEY_P: + return Component.Identifier.Key.P; + case Keyboard.KEY_LBRACKET: + return Component.Identifier.Key.LBRACKET; + case Keyboard.KEY_RBRACKET: + return Component.Identifier.Key.RBRACKET; + case Keyboard.KEY_RETURN: + return Component.Identifier.Key.RETURN; + case Keyboard.KEY_LCONTROL: + return Component.Identifier.Key.LCONTROL; + case Keyboard.KEY_A: + return Component.Identifier.Key.A; + case Keyboard.KEY_S: + return Component.Identifier.Key.S; + case Keyboard.KEY_D: + return Component.Identifier.Key.D; + case Keyboard.KEY_F: + return Component.Identifier.Key.F; + case Keyboard.KEY_G: + return Component.Identifier.Key.G; + case Keyboard.KEY_H: + return Component.Identifier.Key.H; + case Keyboard.KEY_J: + return Component.Identifier.Key.J; + case Keyboard.KEY_K: + return Component.Identifier.Key.K; + case Keyboard.KEY_L: + return Component.Identifier.Key.L; + case Keyboard.KEY_SEMICOLON: + return Component.Identifier.Key.SEMICOLON; + case Keyboard.KEY_APOSTROPHE: + return Component.Identifier.Key.APOSTROPHE; + case Keyboard.KEY_GRAVE: + return Component.Identifier.Key.GRAVE; + case Keyboard.KEY_LSHIFT: + return Component.Identifier.Key.LSHIFT; + case Keyboard.KEY_BACKSLASH: + return Component.Identifier.Key.BACKSLASH; + case Keyboard.KEY_Z: + return Component.Identifier.Key.Z; + case Keyboard.KEY_X: + return Component.Identifier.Key.X; + case Keyboard.KEY_C: + return Component.Identifier.Key.C; + case Keyboard.KEY_V: + return Component.Identifier.Key.V; + case Keyboard.KEY_B: + return Component.Identifier.Key.B; + case Keyboard.KEY_N: + return Component.Identifier.Key.N; + case Keyboard.KEY_M: + return Component.Identifier.Key.M; + case Keyboard.KEY_COMMA: + return Component.Identifier.Key.COMMA; + case Keyboard.KEY_PERIOD: + return Component.Identifier.Key.PERIOD; + case Keyboard.KEY_SLASH: + return Component.Identifier.Key.SLASH; + case Keyboard.KEY_RSHIFT: + return Component.Identifier.Key.RSHIFT; + case Keyboard.KEY_MULTIPLY: + return Component.Identifier.Key.MULTIPLY; + case Keyboard.KEY_LMENU: + return Component.Identifier.Key.LALT; + case Keyboard.KEY_SPACE: + return Component.Identifier.Key.SPACE; + case Keyboard.KEY_CAPITAL: + return Component.Identifier.Key.CAPITAL; + case Keyboard.KEY_F1: + return Component.Identifier.Key.F1; + case Keyboard.KEY_F2: + return Component.Identifier.Key.F2; + case Keyboard.KEY_F3: + return Component.Identifier.Key.F3; + case Keyboard.KEY_F4: + return Component.Identifier.Key.F4; + case Keyboard.KEY_F5: + return Component.Identifier.Key.F5; + case Keyboard.KEY_F6: + return Component.Identifier.Key.F6; + case Keyboard.KEY_F7: + return Component.Identifier.Key.F7; + case Keyboard.KEY_F8: + return Component.Identifier.Key.F8; + case Keyboard.KEY_F9: + return Component.Identifier.Key.F9; + case Keyboard.KEY_F10: + return Component.Identifier.Key.F10; + case Keyboard.KEY_NUMLOCK: + return Component.Identifier.Key.NUMLOCK; + case Keyboard.KEY_SCROLL: + return Component.Identifier.Key.SCROLL; + case Keyboard.KEY_NUMPAD7: + return Component.Identifier.Key.NUMPAD7; + case Keyboard.KEY_NUMPAD8: + return Component.Identifier.Key.NUMPAD8; + case Keyboard.KEY_NUMPAD9: + return Component.Identifier.Key.NUMPAD9; + case Keyboard.KEY_SUBTRACT: + return Component.Identifier.Key.SUBTRACT; + case Keyboard.KEY_NUMPAD4: + return Component.Identifier.Key.NUMPAD4; + case Keyboard.KEY_NUMPAD5: + return Component.Identifier.Key.NUMPAD5; + case Keyboard.KEY_NUMPAD6: + return Component.Identifier.Key.NUMPAD6; + case Keyboard.KEY_ADD: + return Component.Identifier.Key.ADD; + case Keyboard.KEY_NUMPAD1: + return Component.Identifier.Key.NUMPAD1; + case Keyboard.KEY_NUMPAD2: + return Component.Identifier.Key.NUMPAD2; + case Keyboard.KEY_NUMPAD3: + return Component.Identifier.Key.NUMPAD3; + case Keyboard.KEY_NUMPAD0: + return Component.Identifier.Key.NUMPAD0; + case Keyboard.KEY_DECIMAL: + return Component.Identifier.Key.DECIMAL; + case Keyboard.KEY_F11: + return Component.Identifier.Key.F11; + case Keyboard.KEY_F12: + return Component.Identifier.Key.F12; + case Keyboard.KEY_F13: + return Component.Identifier.Key.F13; + case Keyboard.KEY_F14: + return Component.Identifier.Key.F14; + case Keyboard.KEY_F15: + return Component.Identifier.Key.F15; + case Keyboard.KEY_KANA: + return Component.Identifier.Key.KANA; + case Keyboard.KEY_CONVERT: + return Component.Identifier.Key.CONVERT; + case Keyboard.KEY_NOCONVERT: + return Component.Identifier.Key.NOCONVERT; + case Keyboard.KEY_YEN: + return Component.Identifier.Key.YEN; + case Keyboard.KEY_NUMPADEQUALS: + return Component.Identifier.Key.NUMPADEQUAL; + case Keyboard.KEY_CIRCUMFLEX: + return Component.Identifier.Key.CIRCUMFLEX; + case Keyboard.KEY_AT: + return Component.Identifier.Key.AT; + case Keyboard.KEY_COLON: + return Component.Identifier.Key.COLON; + case Keyboard.KEY_UNDERLINE: + return Component.Identifier.Key.UNDERLINE; + case Keyboard.KEY_KANJI: + return Component.Identifier.Key.KANJI; + case Keyboard.KEY_STOP: + return Component.Identifier.Key.STOP; + case Keyboard.KEY_AX: + return Component.Identifier.Key.AX; + case Keyboard.KEY_UNLABELED: + return Component.Identifier.Key.UNLABELED; + case Keyboard.KEY_NUMPADENTER: + return Component.Identifier.Key.NUMPADENTER; + case Keyboard.KEY_RCONTROL: + return Component.Identifier.Key.RCONTROL; + case Keyboard.KEY_NUMPADCOMMA: + return Component.Identifier.Key.NUMPADCOMMA; + case Keyboard.KEY_DIVIDE: + return Component.Identifier.Key.DIVIDE; + case Keyboard.KEY_SYSRQ: + return Component.Identifier.Key.SYSRQ; + case Keyboard.KEY_RMENU: + return Component.Identifier.Key.RALT; + case Keyboard.KEY_PAUSE: + return Component.Identifier.Key.PAUSE; + case Keyboard.KEY_HOME: + return Component.Identifier.Key.HOME; + case Keyboard.KEY_UP: + return Component.Identifier.Key.UP; + case Keyboard.KEY_PRIOR: + return Component.Identifier.Key.PAGEUP; + case Keyboard.KEY_LEFT: + return Component.Identifier.Key.LEFT; + case Keyboard.KEY_RIGHT: + return Component.Identifier.Key.RIGHT; + case Keyboard.KEY_END: + return Component.Identifier.Key.END; + case Keyboard.KEY_DOWN: + return Component.Identifier.Key.DOWN; + case Keyboard.KEY_NEXT: + return Component.Identifier.Key.PAGEDOWN; + case Keyboard.KEY_INSERT: + return Component.Identifier.Key.INSERT; + case Keyboard.KEY_DELETE: + return Component.Identifier.Key.DELETE; + case Keyboard.KEY_LMETA: + return Component.Identifier.Key.LWIN; + case Keyboard.KEY_RMETA: + return Component.Identifier.Key.RWIN; + case Keyboard.KEY_APPS: + return Component.Identifier.Key.APPS; + case Keyboard.KEY_POWER: + return Component.Identifier.Key.POWER; + case Keyboard.KEY_SLEEP: + return Component.Identifier.Key.SLEEP; + default: + return Component.Identifier.Key.UNKNOWN; + } + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java b/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java new file mode 100644 index 0000000..f08a024 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLEnvironmentPlugin.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.jinput; + +import net.java.games.input.Controller; +import net.java.games.input.ControllerEnvironment; +import net.java.games.util.plugins.Plugin; + +/** + * @author elias + */ +public class LWJGLEnvironmentPlugin extends ControllerEnvironment implements Plugin { + + private final Controller[] controllers; + + public LWJGLEnvironmentPlugin() { + this.controllers = new Controller[] { new LWJGLKeyboard(), new LWJGLMouse() }; + } + + public Controller[] getControllers() { + return controllers; + } + + public boolean isSupported() { + return true; + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java b/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java new file mode 100644 index 0000000..1d907c5 --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLKeyboard.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.jinput; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import net.java.games.input.AbstractComponent; +import net.java.games.input.Component; +import net.java.games.input.Controller; +import net.java.games.input.Event; +import net.java.games.input.Keyboard; +import net.java.games.input.Rumbler; + +/** + * @author elias + */ +final class LWJGLKeyboard extends Keyboard { + + LWJGLKeyboard() { + super("LWJGLKeyboard", createComponents(), new Controller[] {}, new Rumbler[] {}); + } + + private static Component[] createComponents() { + List components = new ArrayList(); + Field[] vkey_fields = org.lwjglx.input.Keyboard.class.getFields(); + for (Field vkey_field : vkey_fields) { + try { + if (Modifier.isStatic(vkey_field.getModifiers()) && vkey_field.getType() == int.class + && vkey_field.getName() + .startsWith("KEY_")) { + int vkey_code = vkey_field.getInt(null); + Component.Identifier.Key key_id = KeyMap.map(vkey_code); + if (key_id != Component.Identifier.Key.UNKNOWN) components.add(new Key(key_id, vkey_code)); + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + return components.toArray(new Component[components.size()]); + } + + public synchronized void pollDevice() throws IOException { + if (!org.lwjglx.input.Keyboard.isCreated()) return; + org.lwjglx.input.Keyboard.poll(); + for (Component component : getComponents()) { + Key key = (Key) component; + key.update(); + } + } + + protected synchronized boolean getNextDeviceEvent(Event event) throws IOException { + if (!org.lwjglx.input.Keyboard.isCreated()) return false; + if (!org.lwjglx.input.Keyboard.next()) return false; + int lwjgl_key = org.lwjglx.input.Keyboard.getEventKey(); + if (lwjgl_key == org.lwjglx.input.Keyboard.KEY_NONE) return false; + Component.Identifier.Key key_id = KeyMap.map(lwjgl_key); + if (key_id == null) return false; + Component key = getComponent(key_id); + if (key == null) return false; + float value = org.lwjglx.input.Keyboard.getEventKeyState() ? 1 : 0; + event.set(key, value, org.lwjglx.input.Keyboard.getEventNanoseconds()); + return true; + } + + private static final class Key extends AbstractComponent { + + private final int lwjgl_key; + private float value; + + Key(Identifier.Key key_id, int lwjgl_key) { + super(key_id.getName(), key_id); + this.lwjgl_key = lwjgl_key; + } + + public void update() { + this.value = org.lwjglx.input.Keyboard.isKeyDown(lwjgl_key) ? 1 : 0; + } + + protected float poll() { + return value; + } + + public boolean isRelative() { + return false; + } + + public boolean isAnalog() { + return false; + } + } +} diff --git a/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java b/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java new file mode 100644 index 0000000..54faf1d --- /dev/null +++ b/src/main/java/org/lwjglx/util/jinput/LWJGLMouse.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.jinput; + +import java.io.IOException; + +import net.java.games.input.AbstractComponent; +import net.java.games.input.Component; +import net.java.games.input.Controller; +import net.java.games.input.Event; +import net.java.games.input.Mouse; +import net.java.games.input.Rumbler; + +/** + * @author elias + */ +final class LWJGLMouse extends Mouse { + + private static final int EVENT_X = 1; + private static final int EVENT_Y = 2; + private static final int EVENT_WHEEL = 3; + private static final int EVENT_BUTTON = 4; + private static final int EVENT_DONE = 5; + + private int event_state = EVENT_DONE; + + LWJGLMouse() { + super("LWJGLMouse", createComponents(), new Controller[] {}, new Rumbler[] {}); + } + + private static Component[] createComponents() { + return new Component[] { new Axis(Component.Identifier.Axis.X), new Axis(Component.Identifier.Axis.Y), + new Axis(Component.Identifier.Axis.Z), new Button(Component.Identifier.Button.LEFT), + new Button(Component.Identifier.Button.MIDDLE), new Button(Component.Identifier.Button.RIGHT) }; + } + + public synchronized void pollDevice() throws IOException { + if (!org.lwjglx.input.Mouse.isCreated()) return; + org.lwjglx.input.Mouse.poll(); + for (int i = 0; i < 3; i++) setButtonState(i); + } + + private Button map(int lwjgl_button) { + switch (lwjgl_button) { + case 0: + return (Button) getLeft(); + case 1: + return (Button) getRight(); + case 2: + return (Button) getMiddle(); + default: + return null; + } + } + + private void setButtonState(int lwjgl_button) { + Button button = map(lwjgl_button); + if (button != null) button.setValue(org.lwjglx.input.Mouse.isButtonDown(lwjgl_button) ? 1 : 0); + } + + protected synchronized boolean getNextDeviceEvent(Event event) throws IOException { + if (!org.lwjglx.input.Mouse.isCreated()) return false; + while (true) { + long nanos = org.lwjglx.input.Mouse.getEventNanoseconds(); + switch (event_state) { + case EVENT_X: + event_state = EVENT_Y; + int dx = org.lwjglx.input.Mouse.getEventDX(); + if (dx != 0) { + event.set(getX(), dx, nanos); + return true; + } + break; + case EVENT_Y: + event_state = EVENT_WHEEL; + /* + * We must negate the y coord since lwjgl uses the + * OpenGL coordinate system + */ + int dy = -org.lwjglx.input.Mouse.getEventDY(); + if (dy != 0) { + event.set(getY(), dy, nanos); + return true; + } + break; + case EVENT_WHEEL: + event_state = EVENT_BUTTON; + int dwheel = org.lwjglx.input.Mouse.getEventDWheel(); + if (dwheel != 0) { + event.set(getWheel(), dwheel, nanos); + return true; + } + break; + case EVENT_BUTTON: + event_state = EVENT_DONE; + int lwjgl_button = org.lwjglx.input.Mouse.getEventButton(); + if (lwjgl_button != -1) { + Button button = map(lwjgl_button); + if (button != null) { + event.set(button, org.lwjglx.input.Mouse.getEventButtonState() ? 1f : 0f, nanos); + return true; + } + } + break; + case EVENT_DONE: + if (!org.lwjglx.input.Mouse.next()) return false; + event_state = EVENT_X; + break; + default: + break; + } + } + } + + static final class Axis extends AbstractComponent { + + Axis(Identifier.Axis axis_id) { + super(axis_id.getName(), axis_id); + } + + public boolean isRelative() { + return true; + } + + protected float poll() throws IOException { + return 0; + } + + public boolean isAnalog() { + return true; + } + } + + static final class Button extends AbstractComponent { + + private float value; + + Button(Identifier.Button button_id) { + super(button_id.getName(), button_id); + } + + void setValue(float value) { + this.value = value; + } + + protected float poll() throws IOException { + return value; + } + + public boolean isRelative() { + return false; + } + + public boolean isAnalog() { + return false; + } + } +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java b/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java new file mode 100644 index 0000000..088fcbc --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheLinePad.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When this annotation is used on a field, automatic cache-line-sized padding + * will be inserted around the field. This is useful in multi-threaded algorithms + * to avoid cache line false sharing. The annotation defaults to padding after + * the field, but can be changed to before or both before and after. It can be + * applied to both mapped object fields and POJO primitive fields. + * + * @author Spasi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface CacheLinePad { + + /** + * When true, cache-line padding will be inserted before the field. + * + * @return true if cache-line padding will be inserted before the field + */ + boolean before() default false; + + /** + * When true, cache-line padding will be inserted after the field. + * + * @return true if cache-line padding will be inserted after the field + */ + boolean after() default true; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java b/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java new file mode 100644 index 0000000..3fe5c9d --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheLineSize.java @@ -0,0 +1,146 @@ +package org.lwjglx.util.mapped; + +import static org.lwjglx.util.mapped.MappedHelper.ivget; +import static org.lwjglx.util.mapped.MappedHelper.ivput; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * This micro-benchmark tries to detect the CPU's cache line size. This is + * done by exploiting cache line false sharing in multi-threaded code: + * When 2 threads simultaneously access the same cache line (and at least + * 1 access is a write), performance drops considerably. We detect this + * performance drop while decreasing the memory padding in every test step. + * + * @author Spasi + */ +final class CacheLineSize { + + private CacheLineSize() {} + + static int getCacheLineSize() { + final int THREADS = 2; + final int REPEATS = 100000 * THREADS; + final int LOCAL_REPEATS = REPEATS / THREADS; + + // Detection will start from CacheLineMaxSize bytes. + final int MAX_SIZE = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineMaxSize", 1024) / 4; // in + // # + // of + // integers + // Detection will stop when the execution time increases by more than CacheLineTimeThreshold %. + final double TIME_THRESHOLD = 1.0 + + LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineTimeThreshold", 50) / 100.0; + + final ExecutorService executorService = Executors.newFixedThreadPool(THREADS); + final ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); + + try { + // We need to use a NIO buffer in order to guarantee memory alignment. + final IntBuffer memory = getMemory(MAX_SIZE); + + // -- WARMUP -- + + final int WARMUP = 10; + for (int i = 0; i < WARMUP; i++) doTest(THREADS, LOCAL_REPEATS, 0, memory, completionService); + + // -- CACHE LINE SIZE DETECTION -- + + long totalTime = 0; + int count = 0; + int cacheLineSize = 64; // fallback to the most common size these days + boolean found = false; + for (int i = MAX_SIZE; i >= 1; i >>= 1) { + final long time = doTest(THREADS, LOCAL_REPEATS, i, memory, completionService); + if (totalTime > 0) { // Ignore first run + final long avgTime = totalTime / count; + if ((double) time / (double) avgTime > TIME_THRESHOLD) { // Try to detect a noticeable jump in + // execution time + cacheLineSize = (i << 1) * 4; + found = true; + break; + } + } + totalTime += time; + count++; + } + + if (LWJGLUtil.DEBUG) { + if (found) LWJGLUtil.log("Cache line size detected: " + cacheLineSize + " bytes"); + else LWJGLUtil.log("Failed to detect cache line size, assuming " + cacheLineSize + " bytes"); + } + + return cacheLineSize; + } finally { + executorService.shutdown(); + } + } + + public static void main(String[] args) { + CacheUtil.getCacheLineSize(); + } + + static long memoryLoop(final int index, final int repeats, final IntBuffer memory, final int padding) { + final long address = MemoryUtil.getAddress(memory) + (index * padding * 4); + + final long time = System.nanoTime(); + for (int i = 0; i < repeats; i++) { + // Use volatile access to avoid server VM optimizations. + ivput(ivget(address) + 1, address); + } + + return System.nanoTime() - time; + } + + private static IntBuffer getMemory(final int START_SIZE) { + final int PAGE_SIZE = MappedObjectUnsafe.INSTANCE.pageSize(); + + final ByteBuffer buffer = ByteBuffer.allocateDirect((START_SIZE * 4) + PAGE_SIZE) + .order(ByteOrder.nativeOrder()); + + // Align to page and, consequently, to cache line. Otherwise results will be inconsistent. + if (MemoryUtil.getAddress(buffer) % PAGE_SIZE != 0) { + // Round up to page boundary + buffer.position(PAGE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (PAGE_SIZE - 1))); + } + + return buffer.asIntBuffer(); + } + + private static long doTest(final int threads, final int repeats, final int padding, final IntBuffer memory, + final ExecutorCompletionService completionService) { + for (int i = 0; i < threads; i++) submitTest(completionService, i, repeats, memory, padding); + return waitForResults(threads, completionService); + } + + private static void submitTest(final ExecutorCompletionService completionService, final int index, + final int repeats, final IntBuffer memory, final int padding) { + completionService.submit(new Callable() { + + public Long call() throws Exception { + return memoryLoop(index, repeats, memory, padding); + } + }); + } + + private static long waitForResults(final int count, final ExecutorCompletionService completionService) { + try { + long totalTime = 0; + for (int i = 0; i < count; i++) totalTime += completionService.take() + .get(); + return totalTime; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/CacheUtil.java b/src/main/java/org/lwjglx/util/mapped/CacheUtil.java new file mode 100644 index 0000000..46d023f --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/CacheUtil.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; +import org.lwjglx.PointerBuffer; + +/** + * This class provides utility methods for allocating cache-line-aligned + * NIO buffers. The CPU cache line size is detected using a micro-benchmark + * that exploits the performation degredation that occurs when different + * threads write to different locations of the same cache line. The detection + * should be reasonably robust on both the server and client VM, but there + * are a few system properties that can be used to tune it. + * + * @author Spasi + */ +public final class CacheUtil { + + private static final int CACHE_LINE_SIZE; + + static { + final Integer size = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineSize"); // forces a + // specific cache + // line size + + if (size != null) { + if (size < 1) throw new IllegalStateException("Invalid CacheLineSize specified: " + size); + CACHE_LINE_SIZE = size; + } else if (Runtime.getRuntime() + .availableProcessors() == 1) { // We cannot use false sharing to detect it + /* + * Spasi: + * I have implemented a single-threaded benchmark for this, but it requires + * lots of memory allocations and could not tune it for both the client and + * server VM. It's not a big deal anyway, 64 bytes should be ok for any + * single-core CPU. + */ + if (LWJGLUtil.DEBUG) + LWJGLUtil.log("Cannot detect cache line size on single-core CPUs, assuming 64 bytes."); + CACHE_LINE_SIZE = 64; + } else CACHE_LINE_SIZE = CacheLineSize.getCacheLineSize(); + } + + private CacheUtil() {} + + /** + * Returns the CPU cache line size, in number of bytes. + * + * @return the cache line size + */ + public static int getCacheLineSize() { + return CACHE_LINE_SIZE; + } + + /** + * Construct a direct, native-ordered and cache-line-aligned bytebuffer with the specified size. + * + * @param size The size, in bytes + * + * @return a ByteBuffer + */ + public static ByteBuffer createByteBuffer(int size) { + ByteBuffer buffer = ByteBuffer.allocateDirect(size + CACHE_LINE_SIZE); + + // Align to cache line. + if (MemoryUtil.getAddress(buffer) % CACHE_LINE_SIZE != 0) { + // Round up to cache line boundary + buffer.position(CACHE_LINE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (CACHE_LINE_SIZE - 1))); + } + + buffer.limit(buffer.position() + size); + return buffer.slice() + .order(ByteOrder.nativeOrder()); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned shortbuffer with the specified number + * of elements. + * + * @param size The size, in shorts + * + * @return a ShortBuffer + */ + public static ShortBuffer createShortBuffer(int size) { + return createByteBuffer(size << 1).asShortBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned charbuffer with the specified number + * of elements. + * + * @param size The size, in chars + * + * @return an CharBuffer + */ + public static CharBuffer createCharBuffer(int size) { + return createByteBuffer(size << 1).asCharBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned intbuffer with the specified number + * of elements. + * + * @param size The size, in ints + * + * @return an IntBuffer + */ + public static IntBuffer createIntBuffer(int size) { + return createByteBuffer(size << 2).asIntBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned longbuffer with the specified number + * of elements. + * + * @param size The size, in longs + * + * @return an LongBuffer + */ + public static LongBuffer createLongBuffer(int size) { + return createByteBuffer(size << 3).asLongBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned floatbuffer with the specified number + * of elements. + * + * @param size The size, in floats + * + * @return a FloatBuffer + */ + public static FloatBuffer createFloatBuffer(int size) { + return createByteBuffer(size << 2).asFloatBuffer(); + } + + /** + * Construct a direct, native-ordered and cache-line-aligned doublebuffer with the specified number + * of elements. + * + * @param size The size, in floats + * + * @return a FloatBuffer + */ + public static DoubleBuffer createDoubleBuffer(int size) { + return createByteBuffer(size << 3).asDoubleBuffer(); + } + + /** + * Construct a cache-line-aligned PointerBuffer with the specified number + * of elements. + * + * @param size The size, in memory addresses + * + * @return a PointerBuffer + */ + public static PointerBuffer createPointerBuffer(int size) { + return new PointerBuffer(createByteBuffer(size * PointerBuffer.getPointerSize())); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedField.java b/src/main/java/org/lwjglx/util/mapped/MappedField.java new file mode 100644 index 0000000..6792102 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedField.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation can be used on fields of {@link MappedObject} subclasses, + * to manually specify byte offsets and lengths. This is useful when the + * mapped fields require custom alignment. {@link java.nio.ByteBuffer} + * fields are required to have this annotation with a hardcoded byte length. + * + * @author Riven + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface MappedField { + + /** + * Specifies the field byte offset within the mapped object. + * + * @return the field byte offset + */ + long byteOffset() default -1; + + /** + * Specifies the field byte length. Required for {@link java.nio.ByteBuffer} fields. + * + * @return the field byte length + */ + long byteLength() default -1; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedForeach.java b/src/main/java/org/lwjglx/util/mapped/MappedForeach.java new file mode 100644 index 0000000..ce24455 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedForeach.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.util.Iterator; + +/** + * Iterable implementation for {@link MappedObject}. + * + * @author Riven + */ +final class MappedForeach implements Iterable { + + final T mapped; + final int elementCount; + + MappedForeach(T mapped, int elementCount) { + this.mapped = mapped; + this.elementCount = elementCount; + } + + public Iterator iterator() { + return new Iterator() { + + private int index; + + public boolean hasNext() { + return this.index < (MappedForeach.this.elementCount); + } + + public T next() { + mapped.setViewAddress(mapped.getViewAddress(this.index++)); + return mapped; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedHelper.java b/src/main/java/org/lwjglx/util/mapped/MappedHelper.java new file mode 100644 index 0000000..a9743c0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedHelper.java @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import static org.lwjglx.util.mapped.MappedObjectUnsafe.*; + +import java.nio.ByteBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * [INTERNAL USE ONLY] + *

+ * Helper class used by the bytecode transformer. + * + * @author Riven + */ +public class MappedHelper { + + public static void setup(MappedObject mo, ByteBuffer buffer, int align, int sizeof) { + if (LWJGLUtil.CHECKS && mo.baseAddress != 0L) + throw new IllegalStateException("this method should not be called by user-code"); + + if (LWJGLUtil.CHECKS && !buffer.isDirect()) throw new IllegalArgumentException("bytebuffer must be direct"); + mo.preventGC = buffer; + + if (LWJGLUtil.CHECKS && align <= 0) throw new IllegalArgumentException("invalid alignment"); + + if (LWJGLUtil.CHECKS && (sizeof <= 0 || sizeof % align != 0)) + throw new IllegalStateException("sizeof not a multiple of alignment"); + + long addr = MemoryUtil.getAddress(buffer); + if (LWJGLUtil.CHECKS && addr % align != 0) + throw new IllegalStateException("buffer address not aligned on " + align + " bytes"); + + mo.baseAddress = mo.viewAddress = addr; + } + + public static void checkAddress(long viewAddress, MappedObject mapped) { + mapped.checkAddress(viewAddress); + } + + public static void put_views(MappedSet2 set, int view) { + set.view(view); + } + + public static void put_views(MappedSet3 set, int view) { + set.view(view); + } + + public static void put_views(MappedSet4 set, int view) { + set.view(view); + } + + public static void put_view(MappedObject mapped, int view, int sizeof) { + mapped.setViewAddress(mapped.baseAddress + view * sizeof); + } + + public static int get_view(MappedObject mapped, int sizeof) { + return (int) (mapped.viewAddress - mapped.baseAddress) / sizeof; + } + + public static void put_view_shift(MappedObject mapped, int view, int sizeof_shift) { + mapped.setViewAddress(mapped.baseAddress + (view << sizeof_shift)); + } + + public static int get_view_shift(MappedObject mapped, int sizeof_shift) { + return ((int) (mapped.viewAddress - mapped.baseAddress)) >> sizeof_shift; + } + + public static void put_view_next(MappedObject mapped, int sizeof) { + mapped.setViewAddress(mapped.viewAddress + sizeof); + } + + public static MappedObject dup(MappedObject src, MappedObject dst) { + dst.baseAddress = src.baseAddress; + dst.viewAddress = src.viewAddress; + dst.preventGC = src.preventGC; + return dst; + } + + public static MappedObject slice(MappedObject src, MappedObject dst) { + dst.baseAddress = src.viewAddress; // ! + dst.viewAddress = src.viewAddress; + dst.preventGC = src.preventGC; + return dst; + } + + public static void copy(MappedObject src, MappedObject dst, int bytes) { + if (MappedObject.CHECKS) { + src.checkRange(bytes); + dst.checkRange(bytes); + } + + INSTANCE.copyMemory(src.viewAddress, dst.viewAddress, bytes); + } + + public static ByteBuffer newBuffer(long address, int capacity) { + return MappedObjectUnsafe.newBuffer(address, capacity); + } + + // ---- primitive fields read/write + + // byte + + public static void bput(byte value, long addr) { + INSTANCE.putByte(addr, value); + } + + public static void bput(MappedObject mapped, byte value, int fieldOffset) { + INSTANCE.putByte(mapped.viewAddress + fieldOffset, value); + } + + public static byte bget(long addr) { + return INSTANCE.getByte(addr); + } + + public static byte bget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getByte(mapped.viewAddress + fieldOffset); + } + + public static void bvput(byte value, long addr) { + INSTANCE.putByteVolatile(null, addr, value); + } + + public static void bvput(MappedObject mapped, byte value, int fieldOffset) { + INSTANCE.putByteVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static byte bvget(long addr) { + return INSTANCE.getByteVolatile(null, addr); + } + + public static byte bvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getByteVolatile(null, mapped.viewAddress + fieldOffset); + } + + // short + + public static void sput(short value, long addr) { + INSTANCE.putShort(addr, value); + } + + public static void sput(MappedObject mapped, short value, int fieldOffset) { + INSTANCE.putShort(mapped.viewAddress + fieldOffset, value); + } + + public static short sget(long addr) { + return INSTANCE.getShort(addr); + } + + public static short sget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getShort(mapped.viewAddress + fieldOffset); + } + + public static void svput(short value, long addr) { + INSTANCE.putShortVolatile(null, addr, value); + } + + public static void svput(MappedObject mapped, short value, int fieldOffset) { + INSTANCE.putShortVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static short svget(long addr) { + return INSTANCE.getShortVolatile(null, addr); + } + + public static short svget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getShortVolatile(null, mapped.viewAddress + fieldOffset); + } + + // char + + public static void cput(char value, long addr) { + INSTANCE.putChar(addr, value); + } + + public static void cput(MappedObject mapped, char value, int fieldOffset) { + INSTANCE.putChar(mapped.viewAddress + fieldOffset, value); + } + + public static char cget(long addr) { + return INSTANCE.getChar(addr); + } + + public static char cget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getChar(mapped.viewAddress + fieldOffset); + } + + public static void cvput(char value, long addr) { + INSTANCE.putCharVolatile(null, addr, value); + } + + public static void cvput(MappedObject mapped, char value, int fieldOffset) { + INSTANCE.putCharVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static char cvget(long addr) { + return INSTANCE.getCharVolatile(null, addr); + } + + public static char cvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getCharVolatile(null, mapped.viewAddress + fieldOffset); + } + + // int + + public static void iput(int value, long addr) { + INSTANCE.putInt(addr, value); + } + + public static void iput(MappedObject mapped, int value, int fieldOffset) { + INSTANCE.putInt(mapped.viewAddress + fieldOffset, value); + } + + public static int iget(long address) { + return INSTANCE.getInt(address); + } + + public static int iget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getInt(mapped.viewAddress + fieldOffset); + } + + public static void ivput(int value, long addr) { + INSTANCE.putIntVolatile(null, addr, value); + } + + public static void ivput(MappedObject mapped, int value, int fieldOffset) { + INSTANCE.putIntVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static int ivget(long address) { + return INSTANCE.getIntVolatile(null, address); + } + + public static int ivget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getIntVolatile(null, mapped.viewAddress + fieldOffset); + } + + // float + + public static void fput(float value, long addr) { + INSTANCE.putFloat(addr, value); + } + + public static void fput(MappedObject mapped, float value, int fieldOffset) { + INSTANCE.putFloat(mapped.viewAddress + fieldOffset, value); + } + + public static float fget(long addr) { + return INSTANCE.getFloat(addr); + } + + public static float fget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getFloat(mapped.viewAddress + fieldOffset); + } + + public static void fvput(float value, long addr) { + INSTANCE.putFloatVolatile(null, addr, value); + } + + public static void fvput(MappedObject mapped, float value, int fieldOffset) { + INSTANCE.putFloatVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static float fvget(long addr) { + return INSTANCE.getFloatVolatile(null, addr); + } + + public static float fvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getFloatVolatile(null, mapped.viewAddress + fieldOffset); + } + + // long + + public static void jput(long value, long addr) { + INSTANCE.putLong(addr, value); + } + + public static void jput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putLong(mapped.viewAddress + fieldOffset, value); + } + + public static long jget(long addr) { + return INSTANCE.getLong(addr); + } + + public static long jget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getLong(mapped.viewAddress + fieldOffset); + } + + public static void jvput(long value, long addr) { + INSTANCE.putLongVolatile(null, addr, value); + } + + public static void jvput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putLongVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static long jvget(long addr) { + return INSTANCE.getLongVolatile(null, addr); + } + + public static long jvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getLongVolatile(null, mapped.viewAddress + fieldOffset); + } + + // address + + public static void aput(long value, long addr) { + INSTANCE.putAddress(addr, value); + } + + public static void aput(MappedObject mapped, long value, int fieldOffset) { + INSTANCE.putAddress(mapped.viewAddress + fieldOffset, value); + } + + public static long aget(long addr) { + return INSTANCE.getAddress(addr); + } + + public static long aget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getAddress(mapped.viewAddress + fieldOffset); + } + + // double + + public static void dput(double value, long addr) { + INSTANCE.putDouble(addr, value); + } + + public static void dput(MappedObject mapped, double value, int fieldOffset) { + INSTANCE.putDouble(mapped.viewAddress + fieldOffset, value); + } + + public static double dget(long addr) { + return INSTANCE.getDouble(addr); + } + + public static double dget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getDouble(mapped.viewAddress + fieldOffset); + } + + public static void dvput(double value, long addr) { + INSTANCE.putDoubleVolatile(null, addr, value); + } + + public static void dvput(MappedObject mapped, double value, int fieldOffset) { + INSTANCE.putDoubleVolatile(null, mapped.viewAddress + fieldOffset, value); + } + + public static double dvget(long addr) { + return INSTANCE.getDoubleVolatile(null, addr); + } + + public static double dvget(MappedObject mapped, int fieldOffset) { + return INSTANCE.getDoubleVolatile(null, mapped.viewAddress + fieldOffset); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObject.java b/src/main/java/org/lwjglx/util/mapped/MappedObject.java new file mode 100644 index 0000000..c3b9512 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObject.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; + +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; + +/** + * Base superclass of all mapped objects. Classes that require + * data mapping should extend this class and registered with + * {@link MappedObjectTransformer#register(Class)}. + *

+ * Subclasses may only specify the default constructor. Any code + * inside that constructor is optional, but will not run when the + * view is instantiated, see {@link #runViewConstructor()}. + *

+ * Bounds checking may be enabled through a JVM system property: org.lwjglx.util.mapped.Checks=true + * + * @author Riven + */ +public abstract class MappedObject { + + static final boolean CHECKS = LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.Checks"); + + protected MappedObject() { + // + } + + /** The mapped object base memory address, in bytes. Read-only. */ + public long baseAddress; + + /** The mapped object view memory address, in bytes. Read-only. */ + public long viewAddress; + + /** The mapped buffer. */ + ByteBuffer preventGC; + + /** + * Holds the value of sizeof of the sub-type of this MappedObject
+ *
+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.SIZEOF will yield 8 (2 floats)
+ * Vec3.SIZEOF will yield 12 (3 floats)
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + public static int SIZEOF = -1; // any method that calls these field will have its call-site modified ('final' per + // subtype) + + /** + * The mapped object view offset, in elements. Read/write. + * This is a virtual field, used as a convenient getter/setter for {@see viewAddress}. + */ + public int view; + + protected final long getViewAddress(final int view) { + // No call-site modification for this, we override in every subclass instead, + // so that we can use it in MappedForeach. + throw new InternalError("type not registered"); + } + + public final void setViewAddress(final long address) { + if (CHECKS) checkAddress(address); + this.viewAddress = address; + } + + final void checkAddress(final long address) { + final long base = MemoryUtil.getAddress0(preventGC); + final int offset = (int) (address - base); + if (address < base || preventGC.capacity() < (offset + getSizeof())) + throw new IndexOutOfBoundsException(Integer.toString(offset / getSizeof())); + } + + final void checkRange(final int bytes) { + if (bytes < 0) throw new IllegalArgumentException(); + + if (preventGC.capacity() < (viewAddress - MemoryUtil.getAddress0(preventGC) + bytes)) + throw new BufferOverflowException(); + } + + /** The mapped object memory alignment, in bytes. Read-only. */ + /** + * Returns the mapped object memory alignment, in bytes. + * + * @return the memory alignment + */ + public final int getAlign() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Returns the mapped object memory sizeof, in bytes. + * + * @return the sizeof value + */ + public final int getSizeof() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Returns the number of mapped objects that fit in the mapped buffer. + * + * @return the mapped object capacity + */ + public final int capacity() { + // No call-site modification for this, we override in every subclass instead. + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region of the specified direct ByteBuffer. + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.map(buffer) will return a mapped Vec2 instance.
+ * Vec3.map(buffer) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T map(ByteBuffer bb) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region specified. This is useful for mapping + * arbitrary regions in memory, e.g. OpenCL CLMem objects, without creating a ByteBuffer first. + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.map(buffer) will return a mapped Vec2 instance.
+ * Vec3.map(buffer) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T map(long address, int capacity) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a MappedObject instance, mapping the memory region of an allocated direct ByteBuffer with a capacity of + * elementCount*SIZEOF + *

+ * The behavior of this (transformed) method does not follow the normal Java behavior.
+ * Vec2.malloc(int) will return a mapped Vec2 instance.
+ * Vec3.malloc(int) will return a mapped Vec3 instance.
+ * This (required) notation might cause compiler warnings, which can be suppressed + * with @SuppressWarnings("static-access").
+ * Using Java 5.0's static-import on this method will break functionality. + */ + @SuppressWarnings("unused") + public static T malloc(int elementCount) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates an identical new MappedObject instance, comparable to the + * contract of {@link ByteBuffer#duplicate}. This is useful when more than one + * views of the mapped object are required at the same time, e.g. in + * multithreaded access. + */ + public final T dup() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates a new MappedObject instance, with a base offset equal to + * the offset of the current view, comparable to the contract of {@link ByteBuffer#slice}. + */ + public final T slice() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Any code in the default constructor will not run automatically. This method + * can be used to execute that code on the current view. + */ + public final void runViewConstructor() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** Moves the current view to the next element. */ + public final void next() { + // No call-site modification for this, we override in every subclass instead, + // so that we can use it in MappedSetX. + throw new InternalError("type not registered"); + } + + /** + * Copies and amount of SIZEOF - padding bytes, from the current + * mapped object, to the specified mapped object. + */ + @SuppressWarnings("unused") + public final void copyTo(T target) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Copies and amount of SIZEOF * instances bytes, from the + * current mapped object, to the specified mapped object. Note that + * this includes any padding bytes that are part of SIZEOF. + */ + @SuppressWarnings("unused") + public final void copyRange(T target, int instances) { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Creates an {@link Iterable} that will step through + * capacity() views, leaving the view at + * the last valid value.
+ *

+ * For convenience you are encouraged to static-import this specific method: + * import static org.lwjglx.util.mapped.MappedObject.foreach; + */ + public static Iterable foreach(T mapped) { + return foreach(mapped, mapped.capacity()); + } + + /** + * Creates an {@link Iterable} that will step through + * elementCount views, leaving the view at + * the last valid value.
+ *

+ * For convenience you are encouraged to static-import this specific method: + * import static org.lwjglx.util.mapped.MappedObject.foreach; + */ + public static Iterable foreach(T mapped, int elementCount) { + return new MappedForeach(mapped, elementCount); + } + + @SuppressWarnings("unused") + public final T[] asArray() { + // any method that calls this method will have its call-site modified + throw new InternalError("type not registered"); + } + + /** + * Returns the {@link ByteBuffer} that backs this mapped object. + * + * @return the backing buffer + */ + public final ByteBuffer backingByteBuffer() { + return this.preventGC; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java new file mode 100644 index 0000000..2435d3a --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectClassLoader.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URLClassLoader; + +import org.lwjglx.LWJGLUtil; + +/** + * This classloader is responsible for applying the bytecode transformation to mapped objects. + * The transformation can either be applied using a Java agent, or with the convenient {@link #fork} method. + * + * @author Riven + */ +public class MappedObjectClassLoader extends URLClassLoader { + + static final String MAPPEDOBJECT_PACKAGE_PREFIX = MappedObjectClassLoader.class.getPackage() + .getName() + "."; + + static boolean FORKED; + + /** + * Forks the specified class containing a main method, passing the specified arguments. See + * org.lwjglx.test.mapped.TestMappedObject for example usage. + * + * @param mainClass the class containing the main method + * @param args the arguments to pass + * + * @return true if the fork was successful. + */ + public static boolean fork(Class mainClass, String[] args) { + if (FORKED) { + return false; + } + + FORKED = true; + + try { + MappedObjectClassLoader loader = new MappedObjectClassLoader(mainClass); + loader.loadMappedObject(); + + Class replacedMainClass = loader.loadClass(mainClass.getName()); + Method mainMethod = replacedMainClass.getMethod("main", String[].class); + mainMethod.invoke(null, new Object[] { args }); + } catch (InvocationTargetException exc) { + Thread.currentThread() + .getUncaughtExceptionHandler() + .uncaughtException(Thread.currentThread(), exc.getCause()); + } catch (Throwable cause) { + throw new Error("failed to fork", cause); + } + + return true; + } + + private MappedObjectClassLoader(Class mainClass) { + super(((URLClassLoader) mainClass.getClassLoader()).getURLs()); + } + + protected synchronized Class loadMappedObject() throws ClassNotFoundException { + final String name = MappedObject.class.getName(); + String className = name.replace('.', '/'); + + byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class"))); + + long t0 = System.nanoTime(); + bytecode = MappedObjectTransformer.transformMappedObject(bytecode); + long t1 = System.nanoTime(); + total_time_transforming += (t1 - t0); + + if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1); + + Class clazz = super.defineClass(name, bytecode, 0, bytecode.length); + resolveClass(clazz); + return clazz; + } + + private static long total_time_transforming; + + @Override + protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (name.startsWith("java.") || name.startsWith("javax.") + || name.startsWith("sun.") + || name.startsWith("sunw.") + || name.startsWith("org.objectweb.asm.")) return super.loadClass(name, resolve); + + final String className = name.replace('.', '/'); + final boolean inThisPackage = name.startsWith(MAPPEDOBJECT_PACKAGE_PREFIX); + + if (inThisPackage && (name.equals(MappedObjectClassLoader.class.getName()) + || name.equals((MappedObjectTransformer.class.getName())) + || name.equals((CacheUtil.class.getName())))) return super.loadClass(name, resolve); + + byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class"))); + + // Classes in this package do not get transformed, but need to go through here because we have transformed + // MappedObject. + if (!(inThisPackage && name.substring(MAPPEDOBJECT_PACKAGE_PREFIX.length()) + .indexOf('.') == -1)) { + long t0 = System.nanoTime(); + final byte[] newBytecode = MappedObjectTransformer.transformMappedAPI(className, bytecode); + long t1 = System.nanoTime(); + + total_time_transforming += (t1 - t0); + + if (bytecode != newBytecode) { + bytecode = newBytecode; + if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1); + } + } + + Class clazz = super.defineClass(name, bytecode, 0, bytecode.length); + if (resolve) resolveClass(clazz); + return clazz; + } + + private static void printActivity(final String className, final long t0, final long t1) { + final StringBuilder msg = new StringBuilder(MappedObjectClassLoader.class.getSimpleName() + ": " + className); + + if (MappedObjectTransformer.PRINT_TIMING) msg.append( + "\n\ttransforming took " + (t1 - t0) / 1000 + + " micros (total: " + + (total_time_transforming / 1000 / 1000) + + "ms)"); + + LWJGLUtil.log(msg); + } + + private static byte[] readStream(InputStream in) { + byte[] bytecode = new byte[256]; + int len = 0; + try { + while (true) { + if (bytecode.length == len) bytecode = copyOf(bytecode, len * 2); + int got = in.read(bytecode, len, bytecode.length - len); + if (got == -1) break; + len += got; + } + } catch (IOException exc) { + // stop! + } finally { + try { + in.close(); + } catch (IOException exc) { + // ignore... + } + } + return copyOf(bytecode, len); + } + + private static byte[] copyOf(byte[] original, int newLength) { + byte[] copy = new byte[newLength]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java new file mode 100644 index 0000000..f73d513 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectTransformer.java @@ -0,0 +1,1530 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; +import static org.objectweb.asm.Opcodes.*; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; + +import org.lwjglx.BufferUtils; +import org.lwjglx.LWJGLUtil; +import org.lwjglx.MemoryUtil; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.IntInsnNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.AnalyzerException; +import org.objectweb.asm.tree.analysis.BasicValue; +import org.objectweb.asm.tree.analysis.Frame; +import org.objectweb.asm.tree.analysis.SimpleVerifier; +import org.objectweb.asm.util.TraceClassVisitor; + +import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; + +/** + * This class implements the bytecode transformation that mapped object go through. + * Mapped object classes need to first be registered with the transformer, see {@link #register(Class)}. + *

+ * The transformer supports some debugging tools, enabled through JVM system properties:
+ * org.lwjglx.util.mapped.PrintTiming=true, prints timing information for the transformation step.
+ * org.lwjglx.util.mapped.PrintActivity=true, prints activity information.
+ * org.lwjglx.util.mapped.PrintBytecode=true, prints the transformed bytecode.
+ * org.lwjglx.util.Debug must also be set to true for the above to work. + * + * @author Riven + */ +public class MappedObjectTransformer { + + static final boolean PRINT_ACTIVITY = LWJGLUtil.DEBUG + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintActivity"); + static final boolean PRINT_TIMING = PRINT_ACTIVITY + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintTiming"); + static final boolean PRINT_BYTECODE = LWJGLUtil.DEBUG + && LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.PrintBytecode"); + + static final Map className_to_subtype; + + static final String MAPPED_OBJECT_JVM = jvmClassName(MappedObject.class); + static final String MAPPED_HELPER_JVM = jvmClassName(MappedHelper.class); + + static final String MAPPEDSET_PREFIX = jvmClassName(MappedSet.class); + static final String MAPPED_SET2_JVM = jvmClassName(MappedSet2.class); + static final String MAPPED_SET3_JVM = jvmClassName(MappedSet3.class); + static final String MAPPED_SET4_JVM = jvmClassName(MappedSet4.class); + + static final String CACHE_LINE_PAD_JVM = "L" + jvmClassName(CacheLinePad.class) + ";"; + + // Public methods + static final String VIEWADDRESS_METHOD_NAME = "getViewAddress"; + static final String NEXT_METHOD_NAME = "next"; + static final String ALIGN_METHOD_NAME = "getAlign"; + static final String SIZEOF_METHOD_NAME = "getSizeof"; + static final String CAPACITY_METHOD_NAME = "capacity"; // Used for .asArray().length + + // Internal methods + static final String VIEW_CONSTRUCTOR_NAME = "constructView$LWJGL"; // Used by runViewConstructor + + static final Map OPCODE_TO_NAME = new HashMap(); + static final Map INSNTYPE_TO_NAME = new HashMap(); + + static boolean is_currently_computing_frames; + + static { + getClassEnums(Opcodes.class, OPCODE_TO_NAME, "V1_", "ACC_", "T_", "F_", "MH_"); + getClassEnums(AbstractInsnNode.class, INSNTYPE_TO_NAME); + + className_to_subtype = new HashMap(); + + { + // HACK: required for mapped.view++ + // + // because the compiler generates: + // => GETFIELD MappedObject.view + // => ICONST_1 + // => IADD + // => PUTFIELD MyMappedType.view + // + // instead of: + // => GETFIELD MyMappedType.view + // => ICONST_1 + // => IADD + // => PUTFIELD MyMappedType.view + // + className_to_subtype + .put(MAPPED_OBJECT_JVM, new MappedSubtypeInfo(MAPPED_OBJECT_JVM, null, -1, -1, -1, false)); + } + + final String vmName = System.getProperty("java.vm.name"); + if (vmName != null && !vmName.contains("Server")) { + System.err.println( + "Warning: " + MappedObject.class.getSimpleName() + + "s have inferiour performance on Client VMs, please consider switching to a Server VM."); + } + } + + /** + * Registers a class as a mapped object. + * The class must extend {@link MappedObject} and be annotated with {@link MappedField}. + * + * @param type the mapped object class. + */ + public static void register(Class type) { + if (MappedObjectClassLoader.FORKED) return; + + final MappedType mapped = type.getAnnotation(MappedType.class); + + if (mapped != null && mapped.padding() < 0) + throw new ClassFormatError("Invalid mapped type padding: " + mapped.padding()); + + if (type.getEnclosingClass() != null && !Modifier.isStatic(type.getModifiers())) + throw new InternalError("only top-level or static inner classes are allowed"); + + final String className = jvmClassName(type); + final Map fields = new HashMap(); + + long sizeof = 0; + for (Field field : type.getDeclaredFields()) { + FieldInfo fieldInfo = registerField( + mapped == null || mapped.autoGenerateOffsets(), + className, + sizeof, + field); + if (fieldInfo == null) continue; + + fields.put(field.getName(), fieldInfo); + + sizeof = Math.max(sizeof, fieldInfo.offset + fieldInfo.lengthPadded); + } + + int align = 4; + int padding = 0; + boolean cacheLinePadded = false; + + if (mapped != null) { + align = mapped.align(); + if (mapped.cacheLinePadding()) { + if (mapped.padding() != 0) throw new ClassFormatError( + "Mapped type padding cannot be specified together with cacheLinePadding."); + + final int cacheLineMod = (int) (sizeof % CacheUtil.getCacheLineSize()); + if (cacheLineMod != 0) padding = CacheUtil.getCacheLineSize() - cacheLineMod; + + cacheLinePadded = true; + } else padding = mapped.padding(); + } + + sizeof += padding; + + final MappedSubtypeInfo mappedType = new MappedSubtypeInfo( + className, + fields, + (int) sizeof, + align, + padding, + cacheLinePadded); + if (className_to_subtype.put(className, mappedType) != null) + throw new InternalError("duplicate mapped type: " + mappedType.className); + } + + private static FieldInfo registerField(final boolean autoGenerateOffsets, final String className, + long advancingOffset, final Field field) { + if (Modifier.isStatic(field.getModifiers())) // static fields are never mapped + return null; + + // we only support primitives and ByteBuffers + if (!field.getType() + .isPrimitive() && field.getType() != ByteBuffer.class) + throw new ClassFormatError( + "field '" + className + "." + field.getName() + "' not supported: " + field.getType()); + + MappedField meta = field.getAnnotation(MappedField.class); + if (meta == null && !autoGenerateOffsets) throw new ClassFormatError( + "field '" + className + + "." + + field.getName() + + "' missing annotation " + + MappedField.class.getName() + + ": " + + className); + + Pointer pointer = field.getAnnotation(Pointer.class); + if (pointer != null && field.getType() != long.class) throw new ClassFormatError( + "The @Pointer annotation can only be used on long fields. @Pointer field found: " + className + + "." + + field.getName() + + ": " + + field.getType()); + + if (Modifier.isVolatile(field.getModifiers()) && (pointer != null || field.getType() == ByteBuffer.class)) + throw new ClassFormatError( + "The volatile keyword is not supported for @Pointer or ByteBuffer fields. Volatile field found: " + + className + + "." + + field.getName() + + ": " + + field.getType()); + + // quick hack + long byteLength; + if (field.getType() == long.class || field.getType() == double.class) { + if (pointer == null) byteLength = 8; + else byteLength = MappedObjectUnsafe.INSTANCE.addressSize(); + } else if (field.getType() == double.class) byteLength = 8; + else if (field.getType() == int.class || field.getType() == float.class) byteLength = 4; + else if (field.getType() == char.class || field.getType() == short.class) byteLength = 2; + else if (field.getType() == byte.class) byteLength = 1; + else if (field.getType() == ByteBuffer.class) { + byteLength = meta.byteLength(); + if (byteLength < 0) throw new IllegalStateException( + "invalid byte length for mapped ByteBuffer field: " + className + + "." + + field.getName() + + " [length=" + + byteLength + + "]"); + } else throw new ClassFormatError( + field.getType() + .getName()); + + if (field.getType() != ByteBuffer.class && (advancingOffset % byteLength) != 0) + throw new IllegalStateException("misaligned mapped type: " + className + "." + field.getName()); + + CacheLinePad pad = field.getAnnotation(CacheLinePad.class); + + long byteOffset = advancingOffset; + if (meta != null && meta.byteOffset() != -1) { + if (meta.byteOffset() < 0) throw new ClassFormatError( + "Invalid field byte offset: " + className + + "." + + field.getName() + + " [byteOffset=" + + meta.byteOffset() + + "]"); + if (pad != null) throw new ClassFormatError( + "A field byte offset cannot be specified together with cache-line padding: " + className + + "." + + field.getName()); + + byteOffset = meta.byteOffset(); + } + + long byteLengthPadded = byteLength; + if (pad != null) { + // Pad before + if (pad.before() && byteOffset % CacheUtil.getCacheLineSize() != 0) + byteOffset += CacheUtil.getCacheLineSize() - (byteOffset & (CacheUtil.getCacheLineSize() - 1)); + + // Pad after + if (pad.after() && (byteOffset + byteLength) % CacheUtil.getCacheLineSize() != 0) + byteLengthPadded += CacheUtil.getCacheLineSize() + - (byteOffset + byteLength) % CacheUtil.getCacheLineSize(); + + assert !pad.before() || (byteOffset % CacheUtil.getCacheLineSize() == 0); + assert !pad.after() || ((byteOffset + byteLengthPadded) % CacheUtil.getCacheLineSize() == 0); + } + + if (PRINT_ACTIVITY) LWJGLUtil.log( + MappedObjectTransformer.class.getSimpleName() + ": " + + className + + "." + + field.getName() + + " [type=" + + field.getType() + .getSimpleName() + + ", offset=" + + byteOffset + + "]"); + + return new FieldInfo( + byteOffset, + byteLength, + byteLengthPadded, + Type.getType(field.getType()), + Modifier.isVolatile(field.getModifiers()), + pointer != null); + } + + /** Removes final from methods that will be overriden by subclasses. */ + static byte[] transformMappedObject(byte[] bytecode) { + final ClassWriter cw = new ClassWriter(0); + + ClassVisitor cv = new ClassVisitor(RetroFuturaBootstrap.API.newestAsmVersion(), cw) { + + private final String[] DEFINALIZE_LIST = { VIEWADDRESS_METHOD_NAME, NEXT_METHOD_NAME, ALIGN_METHOD_NAME, + SIZEOF_METHOD_NAME, CAPACITY_METHOD_NAME, }; + + public MethodVisitor visitMethod(int access, final String name, final String desc, final String signature, + final String[] exceptions) { + for (String method : DEFINALIZE_LIST) { + if (name.equals(method)) { + access &= ~ACC_FINAL; + break; + } + } + return super.visitMethod(access, name, desc, signature, exceptions); + } + }; + + new ClassReader(bytecode).accept(cv, 0); + return cw.toByteArray(); + } + + static byte[] transformMappedAPI(final String className, byte[] bytecode) { + final ClassWriter cw = new ClassWriter(COMPUTE_FRAMES) { + + @Override + protected String getCommonSuperClass(String a, String b) { + // HACK: prevent user-code static-initialization-blocks to be executed + if (is_currently_computing_frames && !a.startsWith("java/") || !b.startsWith("java/")) + return "java/lang/Object"; + + return super.getCommonSuperClass(a, b); + } + + }; + + final TransformationAdapter ta = new TransformationAdapter(cw, className); + + ClassVisitor cv = ta; + if (className_to_subtype.containsKey(className)) // Do a first pass to generate address getters + cv = getMethodGenAdapter(className, cv); + + new ClassReader(bytecode).accept(cv, ClassReader.SKIP_FRAMES); + + if (!ta.transformed) return bytecode; + + bytecode = cw.toByteArray(); + if (PRINT_BYTECODE) printBytecode(bytecode); + + return bytecode; + } + + private static ClassVisitor getMethodGenAdapter(final String className, final ClassVisitor cv) { + return new ClassVisitor(RetroFuturaBootstrap.API.newestAsmVersion(), cv) { + + @Override + public void visitEnd() { + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + + generateViewAddressGetter(); + generateCapacity(); + generateAlignGetter(mappedSubtype); + generateSizeofGetter(); + generateNext(); + + for (String fieldName : mappedSubtype.fields.keySet()) { + final FieldInfo field = mappedSubtype.fields.get(fieldName); + + if (field.type.getDescriptor() + .length() > 1) { // ByteBuffer, getter only + generateByteBufferGetter(fieldName, field); + } else { + generateFieldGetter(fieldName, field); + generateFieldSetter(fieldName, field); + } + } + + super.visitEnd(); + } + + private void generateViewAddressGetter() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, VIEWADDRESS_METHOD_NAME, "(I)J", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "baseAddress", "J"); + mv.visitVarInsn(ILOAD, 1); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IMUL); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + if (MappedObject.CHECKS) { + mv.visitInsn(DUP2); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "checkAddress", + "(JL" + MAPPED_OBJECT_JVM + ";)V"); + } + mv.visitInsn(LRETURN); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateCapacity() { + // return (backingByteBuffer().capacity() + (int)(MemoryUtil.getAddress0(backingByteBuffer()) - + // baseAddress)) / SIZEOF; + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, CAPACITY_METHOD_NAME, "()I", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKEVIRTUAL, + MAPPED_OBJECT_JVM, + "backingByteBuffer", + "()L" + jvmClassName(ByteBuffer.class) + ";"); + mv.visitInsn(DUP); + mv.visitMethodInsn(INVOKEVIRTUAL, jvmClassName(ByteBuffer.class), "capacity", "()I"); + mv.visitInsn(SWAP); + mv.visitMethodInsn( + INVOKESTATIC, + jvmClassName(MemoryUtil.class), + "getAddress0", + "(L" + jvmClassName(Buffer.class) + ";)J"); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "baseAddress", "J"); + mv.visitInsn(LSUB); + mv.visitInsn(L2I); + mv.visitInsn(IADD); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IDIV); + mv.visitInsn(IRETURN); + mv.visitMaxs(3, 1); + mv.visitEnd(); + } + + private void generateAlignGetter(final MappedSubtypeInfo mappedSubtype) { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, ALIGN_METHOD_NAME, "()I", null, null); + mv.visitCode(); + visitIntNode(mv, mappedSubtype.sizeof); + mv.visitInsn(IRETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + } + + private void generateSizeofGetter() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, SIZEOF_METHOD_NAME, "()I", null, null); + mv.visitCode(); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(IRETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + } + + private void generateNext() { + MethodVisitor mv = super.visitMethod(ACC_PUBLIC, NEXT_METHOD_NAME, "()V", null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitInsn(DUP); + mv.visitFieldInsn(GETFIELD, MAPPED_OBJECT_JVM, "viewAddress", "J"); + mv.visitFieldInsn(GETSTATIC, className, "SIZEOF", "I"); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn(INVOKEVIRTUAL, className, "setViewAddress", "(J)V"); + mv.visitInsn(RETURN); + mv.visitMaxs(3, 1); + mv.visitEnd(); + } + + private void generateByteBufferGetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + getterName(fieldName), + "(L" + className + ";I)" + field.type.getDescriptor(), + null, + null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + visitIntNode(mv, (int) field.length); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";"); + mv.visitInsn(ARETURN); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateFieldGetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + getterName(fieldName), + "(L" + className + ";I)" + field.type.getDescriptor(), + null, + null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "get", + "(J)" + field.type.getDescriptor()); + mv.visitInsn(field.type.getOpcode(IRETURN)); + mv.visitMaxs(3, 2); + mv.visitEnd(); + } + + private void generateFieldSetter(final String fieldName, final FieldInfo field) { + MethodVisitor mv = super.visitMethod( + ACC_PUBLIC | ACC_STATIC, + setterName(fieldName), + "(L" + className + ";I" + field.type.getDescriptor() + ")V", + null, + null); + mv.visitCode(); + int load = 0; + switch (field.type.getSort()) { + case Type.BOOLEAN: + case Type.CHAR: + case Type.BYTE: + case Type.SHORT: + case Type.INT: + load = ILOAD; + break; + case Type.FLOAT: + load = FLOAD; + break; + case Type.LONG: + load = LLOAD; + break; + case Type.DOUBLE: + load = DLOAD; + break; + } + mv.visitVarInsn(load, 2); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, className, VIEWADDRESS_METHOD_NAME, "(I)J"); + visitIntNode(mv, (int) field.offset); + mv.visitInsn(I2L); + mv.visitInsn(LADD); + mv.visitMethodInsn( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "put", + "(" + field.type.getDescriptor() + "J)V"); + mv.visitInsn(RETURN); + mv.visitMaxs(4, 4); + mv.visitEnd(); + } + + }; + } + + private static class TransformationAdapter extends ClassVisitor { + + final String className; + + boolean transformed; + + TransformationAdapter(final ClassVisitor cv, final String className) { + super(RetroFuturaBootstrap.API.newestAsmVersion(), cv); + this.className = className; + } + + @Override + public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, + final Object value) { + // remove redirected fields + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + if (mappedSubtype != null && mappedSubtype.fields.containsKey(name)) { + if (PRINT_ACTIVITY) LWJGLUtil.log( + MappedObjectTransformer.class + .getSimpleName() + ": discarding field: " + className + "." + name + ":" + desc); + return null; + } + + if ((access & ACC_STATIC) == 0) { + return new FieldNode(access, name, desc, signature, value) { + + public void visitEnd() { + if (visibleAnnotations == null) { // early-out + accept(cv); + return; + } + + boolean before = false; + boolean after = false; + int byteLength = 0; + for (AnnotationNode pad : visibleAnnotations) { + if (CACHE_LINE_PAD_JVM.equals(pad.desc)) { + if ("J".equals(desc) || "D".equals(desc)) byteLength = 8; + else if ("I".equals(desc) || "F".equals(desc)) byteLength = 4; + else if ("S".equals(desc) || "C".equals(desc)) byteLength = 2; + else if ("B".equals(desc) || "Z".equals(desc)) byteLength = 1; + else throw new ClassFormatError( + "The @CacheLinePad annotation cannot be used on non-primitive fields: " + className + + "." + + name); + + transformed = true; + + after = true; + if (pad.values != null) { + for (int i = 0; i < pad.values.size(); i += 2) { + final boolean value = pad.values.get(i + 1) + .equals(Boolean.TRUE); + if ("before".equals(pad.values.get(i))) before = value; + else after = value; + } + } + break; + } + } + + /* + * We make the fields public to force the JVM to keep the fields in the object. + * Instead of using only longs or integers, we use the same type as the original + * field. That's because modern JVMs usually reorder fields by type: + * longs, then doubles, then integers, then booleans, etc. This way it's more + * likely that the padding will work as expected. + */ + + if (before) { + final int count = CacheUtil.getCacheLineSize() / byteLength - 1; + for (int i = count; i >= 1; i--) cv.visitField( + access | ACC_PUBLIC | ACC_SYNTHETIC, + name + "$PAD_" + i, + desc, + signature, + null); + } + + accept(cv); + + if (after) { + final int count = CacheUtil.getCacheLineSize() / byteLength - 1; + for (int i = 1; i <= count; i++) cv.visitField( + access | ACC_PUBLIC | ACC_SYNTHETIC, + name + "$PAD" + i, + desc, + signature, + null); + } + } + }; + } else return super.visitField(access, name, desc, signature, value); + } + + @Override + public MethodVisitor visitMethod(final int access, String name, final String desc, final String signature, + final String[] exceptions) { + // Move MappedSubtype constructors to another method + if ("".equals(name)) { + final MappedSubtypeInfo mappedSubtype = className_to_subtype.get(className); + if (mappedSubtype != null) { + if (!"()V".equals(desc)) + throw new ClassFormatError(className + " can only have a default constructor, found: " + desc); + + final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn(INVOKESPECIAL, MAPPED_OBJECT_JVM, "", "()V"); + mv.visitInsn(RETURN); + mv.visitMaxs(0, 0); + + // put the method body in another method + name = VIEW_CONSTRUCTOR_NAME; + } + } + + final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + return new MethodNode(access, name, desc, signature, exceptions) { + + /** + * When true, the method has touched a mapped object and needs to be transformed. We track this + * so we can skip the expensive frame analysis and tree API usage. + */ + boolean needsTransformation; + + @Override + public void visitMaxs(int a, int b) { + try { + is_currently_computing_frames = true; + super.visitMaxs(a, b); + } finally { + is_currently_computing_frames = false; + } + } + + @Override + public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { + if (className_to_subtype.containsKey(owner) || owner.startsWith(MAPPEDSET_PREFIX)) + needsTransformation = true; + + super.visitFieldInsn(opcode, owner, name, desc); + } + + @Override + public void visitMethodInsn(final int opcode, final String owner, final String name, + final String desc) { + if (className_to_subtype.containsKey(owner)) needsTransformation = true; + + super.visitMethodInsn(opcode, owner, name, desc); + } + + @Override + public void visitEnd() { + if (needsTransformation) { // Early-out for methods that do not touch a mapped object. + // System.err.println("\nTRANSFORMING: " + className + "." + name + desc); + transformed = true; + try { + transformMethod(analyse()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // Pass the instruction stream to the adapter's MethodVisitor + accept(mv); + } + + private Frame[] analyse() throws AnalyzerException { + final Analyzer a = new Analyzer(new SimpleVerifier()); + a.analyze(className, this); + return a.getFrames(); + } + + private void transformMethod(final Frame[] frames) { + final InsnList instructions = this.instructions; + + final Map arrayVars = new HashMap(); + + /* + * We need this map because we insert/remove instructions from the stream and we need a way + * to match each original instruction with the corresponding frame. + * TODO: Can we keep track of everything more efficiently without a map? + */ + final Map> frameMap = new HashMap>(); + for (int i = 0; i < frames.length; i++) frameMap.put(instructions.get(i), frames[i]); + + for (int i = 0; i < instructions.size(); i++) { // f is a separate cursor for frames + final AbstractInsnNode instruction = instructions.get(i); + + // System.out.println("MAIN LOOP #" + i + " - " + getOpcodeName(instruction)); + + switch (instruction.getType()) { + case AbstractInsnNode.VAR_INSN: + if (instruction.getOpcode() == ALOAD) { + VarInsnNode varInsn = (VarInsnNode) instruction; + final MappedSubtypeInfo mappedSubtype = arrayVars.get(varInsn.var); + if (mappedSubtype != null) i = transformArrayAccess( + instructions, + i, + frameMap, + varInsn, + mappedSubtype, + varInsn.var); + } + break; + case AbstractInsnNode.FIELD_INSN: + FieldInsnNode fieldInsn = (FieldInsnNode) instruction; + + final InsnList list = transformFieldAccess(fieldInsn); + if (list != null) i = replace(instructions, i, instruction, list); + + break; + case AbstractInsnNode.METHOD_INSN: + MethodInsnNode methodInsn = (MethodInsnNode) instruction; + final MappedSubtypeInfo mappedType = className_to_subtype.get(methodInsn.owner); + if (mappedType != null) i = transformMethodCall( + instructions, + i, + frameMap, + methodInsn, + mappedType, + arrayVars); + break; + } + } + } + }; + } + } + + static int transformMethodCall(final InsnList instructions, int i, + final Map> frameMap, final MethodInsnNode methodInsn, + final MappedSubtypeInfo mappedType, final Map arrayVars) { + switch (methodInsn.getOpcode()) { + case INVOKEVIRTUAL: + if ("asArray".equals(methodInsn.name) && methodInsn.desc.equals("()[L" + MAPPED_OBJECT_JVM + ";")) { + // Go forward and store the local variable index. + // We only allow this pattern: INVOKEVIRTUAL -> CHECKCAST -> ASTORE. + // We remove the first two and store the target MappedSubtype in the ASTORE variable + AbstractInsnNode nextInstruction; + checkInsnAfterIsArray(nextInstruction = methodInsn.getNext(), CHECKCAST); + checkInsnAfterIsArray(nextInstruction = nextInstruction.getNext(), ASTORE); + + final Frame frame = frameMap.get(nextInstruction); + final String targetType = frame.getStack(frame.getStackSize() - 1) + .getType() + .getElementType() + .getInternalName(); + if (!methodInsn.owner.equals(targetType)) { + /* + * This may happen with the current API, like so: + * MappedA foo = MappedA.malloc(...); + * MappedB[] cursor = foo.asArray(); + * We have to parameterize MappedObject to avoid this. + */ + throw new ClassCastException("Source: " + methodInsn.owner + " - Target: " + targetType); + } + + final VarInsnNode varInstruction = (VarInsnNode) nextInstruction; + + arrayVars.put(varInstruction.var, mappedType); + + instructions.remove(methodInsn.getNext()); // Remove CHECKCAST + instructions.remove(methodInsn); // Remove INVOKEVIRTUAL + } + + if ("dup".equals(methodInsn.name) && methodInsn.desc.equals("()L" + MAPPED_OBJECT_JVM + ";")) { + i = replace(instructions, i, methodInsn, generateDupInstructions(methodInsn)); + break; + } + + if ("slice".equals(methodInsn.name) && methodInsn.desc.equals("()L" + MAPPED_OBJECT_JVM + ";")) { + i = replace(instructions, i, methodInsn, generateSliceInstructions(methodInsn)); + break; + } + + if ("runViewConstructor".equals(methodInsn.name) && "()V".equals(methodInsn.desc)) { + i = replace(instructions, i, methodInsn, generateRunViewConstructorInstructions(methodInsn)); + break; + } + + if ("copyTo".equals(methodInsn.name) && methodInsn.desc.equals("(L" + MAPPED_OBJECT_JVM + ";)V")) { + i = replace(instructions, i, methodInsn, generateCopyToInstructions(mappedType)); + break; + } + + if ("copyRange".equals(methodInsn.name) && methodInsn.desc.equals("(L" + MAPPED_OBJECT_JVM + ";I)V")) { + i = replace(instructions, i, methodInsn, generateCopyRangeInstructions(mappedType)); + break; + } + + break; + case INVOKESPECIAL: + // super() in VIEW_CONSTRUCTOR_NAME, remove + if (methodInsn.owner.equals(MAPPED_OBJECT_JVM) && "".equals(methodInsn.name) + && "()V".equals(methodInsn.desc)) { + instructions.remove(methodInsn.getPrevious()); // ALOAD + instructions.remove(methodInsn); // INVOKESPECIAL + + i -= 2; + } + break; + case INVOKESTATIC: + boolean isMapDirectMethod = "map".equals(methodInsn.name) + && methodInsn.desc.equals("(JI)L" + MAPPED_OBJECT_JVM + ";"); + boolean isMapBufferMethod = "map".equals(methodInsn.name) + && methodInsn.desc.equals("(Ljava/nio/ByteBuffer;)L" + MAPPED_OBJECT_JVM + ";"); + boolean isMallocMethod = "malloc".equals(methodInsn.name) + && methodInsn.desc.equals("(I)L" + MAPPED_OBJECT_JVM + ";"); + + if ((isMapDirectMethod || isMapBufferMethod) || isMallocMethod) i = replace( + instructions, + i, + methodInsn, + generateMapInstructions(mappedType, methodInsn.owner, isMapDirectMethod, isMallocMethod)); + break; + } + + return i; + } + + private static InsnList generateCopyRangeInstructions(final MappedSubtypeInfo mappedType) { + final InsnList list = new InsnList(); + + // stack: instances, target, this + list.add(getIntNode(mappedType.sizeof)); + // stack: sizeof, instances, target, this + list.add(new InsnNode(IMUL)); + // stack: bytes, target, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "copy", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";I)V")); + // stack: - + + return list; + } + + private static InsnList generateCopyToInstructions(final MappedSubtypeInfo mappedType) { + final InsnList list = new InsnList(); + + // stack: target, this + list.add(getIntNode(mappedType.sizeof - mappedType.padding)); + // stack: sizeof, target, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "copy", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";I)V")); + // stack: - + + return list; + } + + private static InsnList generateRunViewConstructorInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new InsnNode(DUP)); + // stack: this, this + list.add(new MethodInsnNode(INVOKEVIRTUAL, methodInsn.owner, VIEW_CONSTRUCTOR_NAME, "()V")); + // stack: this + + return list; + } + + private static InsnList generateSliceInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new TypeInsnNode(NEW, methodInsn.owner)); + // stack: new, this + list.add(new InsnNode(DUP)); + // stack: new, new, this + list.add(new MethodInsnNode(INVOKESPECIAL, methodInsn.owner, "", "()V")); + // stack: new, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "slice", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";)L" + MAPPED_OBJECT_JVM + ";")); + // stack: new + + return list; + } + + private static InsnList generateDupInstructions(final MethodInsnNode methodInsn) { + final InsnList list = new InsnList(); + + // stack: this + list.add(new TypeInsnNode(NEW, methodInsn.owner)); + // stack: new, this + list.add(new InsnNode(DUP)); + // stack: new, new, this + list.add(new MethodInsnNode(INVOKESPECIAL, methodInsn.owner, "", "()V")); + // stack: new, this + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "dup", + "(L" + MAPPED_OBJECT_JVM + ";L" + MAPPED_OBJECT_JVM + ";)L" + MAPPED_OBJECT_JVM + ";")); + // stack: new + + return list; + } + + private static InsnList generateMapInstructions(final MappedSubtypeInfo mappedType, final String className, + final boolean mapDirectMethod, final boolean mallocMethod) { + final InsnList trg = new InsnList(); + + if (mallocMethod) { + // stack: count + trg.add(getIntNode(mappedType.sizeof)); + // stack: sizeof, count + trg.add(new InsnNode(IMUL)); + // stack: bytes + trg.add( + new MethodInsnNode( + INVOKESTATIC, + mappedType.cacheLinePadded ? jvmClassName(CacheUtil.class) : jvmClassName(BufferUtils.class), + "createByteBuffer", + "(I)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + } else if (mapDirectMethod) { + // stack: capacity, address + trg.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + } + + // stack: buffer + trg.add(new TypeInsnNode(NEW, className)); + // stack: new, buffer + trg.add(new InsnNode(DUP)); + // stack: new, new, buffer + trg.add(new MethodInsnNode(INVOKESPECIAL, className, "", "()V")); + // stack: new, buffer + trg.add(new InsnNode(DUP_X1)); + // stack: new, buffer, new + trg.add(new InsnNode(SWAP)); + // stack: buffer, new, new + trg.add(getIntNode(mappedType.align)); + // stack: int, buffer, new, new + trg.add(getIntNode(mappedType.sizeof)); + // stack: int, int, buffer, new, new + trg.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "setup", + "(L" + MAPPED_OBJECT_JVM + ";Ljava/nio/ByteBuffer;II)V")); + // stack: new + + return trg; + } + + static InsnList transformFieldAccess(final FieldInsnNode fieldInsn) { + final MappedSubtypeInfo mappedSubtype; + mappedSubtype = className_to_subtype.get(fieldInsn.owner); + if (mappedSubtype == null) { // early out + // MappedSet.view + outer: if ("view".equals(fieldInsn.name) && fieldInsn.owner.startsWith(MAPPEDSET_PREFIX)) + return generateSetViewInstructions(fieldInsn); + + return null; // early out + } + + if ("SIZEOF".equals(fieldInsn.name)) return generateSIZEOFInstructions(fieldInsn, mappedSubtype); + + if ("view".equals(fieldInsn.name)) return generateViewInstructions(fieldInsn, mappedSubtype); + + if ("baseAddress".equals(fieldInsn.name) || "viewAddress".equals(fieldInsn.name)) { + return generateAddressInstructions(fieldInsn); + } + + final FieldInfo field = mappedSubtype.fields.get(fieldInsn.name); + if (field == null) // early out + return null; + + // now we're going to transform ByteBuffer-typed field access + if (fieldInsn.desc.equals("L" + jvmClassName(ByteBuffer.class) + ";")) + return generateByteBufferInstructions(fieldInsn, mappedSubtype, field.offset); + + // we're now going to transform the field access + return generateFieldInstructions(fieldInsn, field); + } + + private static InsnList generateSetViewInstructions(final FieldInsnNode fieldInsn) { + if (fieldInsn.getOpcode() == GETFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + if (fieldInsn.getOpcode() != PUTFIELD) throw new InternalError(); + + final InsnList list = new InsnList(); + + // stack: index, this + if (MAPPED_SET2_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET2_JVM + ";I)V")); + else if (MAPPED_SET3_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET3_JVM + ";I)V")); + else if (MAPPED_SET4_JVM.equals(fieldInsn.owner)) + list.add(new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "put_views", "(L" + MAPPED_SET4_JVM + ";I)V")); + else throw new InternalError(); + // stack: - + + return list; + } + + private static InsnList generateSIZEOFInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype) { + if (!"I".equals(fieldInsn.desc)) throw new InternalError(); + + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == GETSTATIC) { + list.add(getIntNode(mappedSubtype.sizeof)); + return list; + } + + if (fieldInsn.getOpcode() == PUTSTATIC) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + throw new InternalError(); + } + + private static InsnList generateViewInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype) { + if (!"I".equals(fieldInsn.desc)) throw new InternalError(); + + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == GETFIELD) { + if (mappedSubtype.sizeof_shift != 0) { + // stack: instance + list.add(getIntNode(mappedSubtype.sizeof_shift)); + // stack: sizeof, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "get_view_shift", + "(L" + MAPPED_OBJECT_JVM + ";I)I")); + // stack: view + } else { + // stack: instance + list.add(getIntNode(mappedSubtype.sizeof)); + // stack: sizeof, instance + list.add( + new MethodInsnNode(INVOKESTATIC, MAPPED_HELPER_JVM, "get_view", "(L" + MAPPED_OBJECT_JVM + ";I)I")); + // stack: view + } + return list; + } + + if (fieldInsn.getOpcode() == PUTFIELD) { + if (mappedSubtype.sizeof_shift != 0) { + // stack: view, instance + list.add(getIntNode(mappedSubtype.sizeof_shift)); + // stack: sizeof, view, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "put_view_shift", + "(L" + MAPPED_OBJECT_JVM + ";II)V")); + // stack: - + } else { + // stack: view, instance + list.add(getIntNode(mappedSubtype.sizeof)); + // stack: sizeof, view, instance + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "put_view", + "(L" + MAPPED_OBJECT_JVM + ";II)V")); + // stack: - + } + return list; + } + + throw new InternalError(); + } + + private static InsnList generateAddressInstructions(final FieldInsnNode fieldInsn) { + if (!"J".equals(fieldInsn.desc)) throw new IllegalStateException(); + + if (fieldInsn.getOpcode() == GETFIELD) // do not change a thing + return null; + + if (fieldInsn.getOpcode() == PUTFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + throw new InternalError(); + } + + private static InsnList generateByteBufferInstructions(final FieldInsnNode fieldInsn, + final MappedSubtypeInfo mappedSubtype, final long fieldOffset) { + if (fieldInsn.getOpcode() == PUTFIELD) throwAccessErrorOnReadOnlyField(fieldInsn.owner, fieldInsn.name); + + if (fieldInsn.getOpcode() == GETFIELD) { + final InsnList list = new InsnList(); + + // stack: ref + list.add(new FieldInsnNode(GETFIELD, mappedSubtype.className, "viewAddress", "J")); + // stack: long + list.add(new LdcInsnNode(fieldOffset)); + // stack: long, long + list.add(new InsnNode(LADD)); + // stack: long + list.add(new LdcInsnNode(mappedSubtype.fields.get(fieldInsn.name).length)); + // stack: long, long + list.add(new InsnNode(L2I)); + // stack: int, long + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + "newBuffer", + "(JI)L" + jvmClassName(ByteBuffer.class) + ";")); + // stack: buffer + + return list; + } + + throw new InternalError(); + } + + private static InsnList generateFieldInstructions(final FieldInsnNode fieldInsn, final FieldInfo field) { + final InsnList list = new InsnList(); + + if (fieldInsn.getOpcode() == PUTFIELD) { + // stack: value, ref + list.add(getIntNode((int) field.offset)); + // stack: fieldOffset, value, ref + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "put", + "(L" + MAPPED_OBJECT_JVM + ";" + fieldInsn.desc + "I)V")); + // stack - + return list; + } + + if (fieldInsn.getOpcode() == GETFIELD) { + // stack: ref + list.add(getIntNode((int) field.offset)); + // stack: fieldOffset, ref + list.add( + new MethodInsnNode( + INVOKESTATIC, + MAPPED_HELPER_JVM, + field.getAccessType() + "get", + "(L" + MAPPED_OBJECT_JVM + ";I)" + fieldInsn.desc)); + // stack: - + return list; + } + + throw new InternalError(); + } + + static int transformArrayAccess(final InsnList instructions, int i, + final Map> frameMap, final VarInsnNode loadInsn, + final MappedSubtypeInfo mappedSubtype, final int var) { + // We need to go forward in time to find how we use the array var + final int loadStackSize = frameMap.get(loadInsn) + .getStackSize() + 1; + + AbstractInsnNode nextInsn = loadInsn; + + while (true) { + nextInsn = nextInsn.getNext(); + if (nextInsn == null) throw new InternalError(); + + Frame frame = frameMap.get(nextInsn); + if (frame == null) continue; + + int stackSize = frame.getStackSize(); + + if (stackSize == loadStackSize + 1 && nextInsn.getOpcode() == AALOAD) { + final AbstractInsnNode aaLoadInsn = nextInsn; + + while (true) { + nextInsn = nextInsn.getNext(); + if (nextInsn == null) break; + + frame = frameMap.get(nextInsn); + if (frame == null) continue; + stackSize = frame.getStackSize(); + + if (stackSize == loadStackSize + 1 && nextInsn.getOpcode() == PUTFIELD) { + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn; + + // stack: value, view, ref + instructions.insert( + nextInsn, + new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + setterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I" + fieldInsn.desc + ")V")); + // stack: - + instructions.remove(nextInsn); + + break; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == GETFIELD) { + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn; + + // stack: view, ref + instructions.insert( + nextInsn, + new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + getterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I)" + fieldInsn.desc)); + // stack: value + instructions.remove(nextInsn); + + break; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == DUP + && nextInsn.getNext() + .getOpcode() == GETFIELD) { + // May happen with operator+assignment (e.g. cursor[i].value += 10) + final FieldInsnNode fieldInsn = (FieldInsnNode) nextInsn.getNext(); + + final MethodInsnNode getter = new MethodInsnNode( + INVOKESTATIC, + mappedSubtype.className, + getterName(fieldInsn.name), + "(L" + mappedSubtype.className + ";I)" + fieldInsn.desc); + + // stack: view, ref + instructions.insert(nextInsn, new InsnNode(DUP2)); + // stack: view, ref, view, ref + instructions.insert(nextInsn.getNext(), getter); + // stack: value, view, ref + + instructions.remove(nextInsn); + instructions.remove(fieldInsn); + + nextInsn = getter; + continue; + } else + if (stackSize < loadStackSize) throw new ClassFormatError( + "Invalid " + mappedSubtype.className + + " view array usage detected: " + + getOpcodeName(nextInsn)); + } + + instructions.remove(aaLoadInsn); + + return i; + } else if (stackSize == loadStackSize && nextInsn.getOpcode() == ARRAYLENGTH) { + if (LWJGLUtil.DEBUG && loadInsn.getNext() != nextInsn) throw new InternalError(); + + instructions.remove(nextInsn); + loadInsn.var = var; + instructions.insert( + loadInsn, + new MethodInsnNode(INVOKEVIRTUAL, mappedSubtype.className, CAPACITY_METHOD_NAME, "()I")); + + return i + 1; + } else if (stackSize < loadStackSize) // Consumed by something other than AALOAD or ARRAYLENGTH + throw new ClassFormatError( + "Invalid " + mappedSubtype.className + " view array usage detected: " + getOpcodeName(nextInsn)); + } + } + + private static class FieldInfo { + + final long offset; + final long length; + final long lengthPadded; + final Type type; + final boolean isVolatile; + final boolean isPointer; + + FieldInfo(final long offset, final long length, final long lengthPadded, final Type type, + final boolean isVolatile, final boolean isPointer) { + this.offset = offset; + this.length = length; + this.lengthPadded = lengthPadded; + this.type = type; + this.isVolatile = isVolatile; + this.isPointer = isPointer; + } + + String getAccessType() { + return isPointer ? "a" + : type.getDescriptor() + .toLowerCase() + (isVolatile ? "v" : ""); + } + + } + + private static class MappedSubtypeInfo { + + final String className; + + final int sizeof; + final int sizeof_shift; + final int align; + final int padding; + final boolean cacheLinePadded; + + final Map fields; + + MappedSubtypeInfo(String className, Map fields, int sizeof, int align, int padding, + final boolean cacheLinePadded) { + this.className = className; + + this.sizeof = sizeof; + if (((sizeof - 1) & sizeof) == 0) this.sizeof_shift = getPoT(sizeof); + else this.sizeof_shift = 0; + this.align = align; + this.padding = padding; + this.cacheLinePadded = cacheLinePadded; + + this.fields = fields; + } + + private static int getPoT(int value) { + int pot = -1; + while (value > 0) { + pot++; + value >>= 1; + } + return pot; + } + + } + + // ------------------------------------------------------- + // -------------------[ MACROS & UTILS ]------------------ + // ------------------------------------------------------- + + private static void getClassEnums(final Class clazz, final Map map, + final String... prefixFilters) { + try { + OUTER: for (Field field : clazz.getFields()) { + if (!Modifier.isStatic(field.getModifiers()) || field.getType() != int.class) continue; + + for (String filter : prefixFilters) { + if (field.getName() + .startsWith(filter)) continue OUTER; + } + + if (map.put((Integer) field.get(null), field.getName()) != null) throw new IllegalStateException(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + static String getOpcodeName(final AbstractInsnNode insn) { + final String op = OPCODE_TO_NAME.get(insn.getOpcode()); + return INSNTYPE_TO_NAME.get(insn.getType()) + ": " + + insn.getOpcode() + + (op == null ? "" : " [" + OPCODE_TO_NAME.get(insn.getOpcode()) + "]"); + } + + static String jvmClassName(Class type) { + return type.getName() + .replace('.', '/'); + } + + static String getterName(final String fieldName) { + return "get$" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1) + "$LWJGL"; + } + + static String setterName(final String fieldName) { + return "set$" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1) + "$LWJGL"; + } + + private static void checkInsnAfterIsArray(final AbstractInsnNode instruction, final int opcode) { + if (instruction == null) throw new ClassFormatError("Unexpected end of instructions after .asArray() method."); + + if (instruction.getOpcode() != opcode) throw new ClassFormatError( + "The result of .asArray() must be stored to a local variable. Found: " + getOpcodeName(instruction)); + } + + static AbstractInsnNode getIntNode(final int value) { + if (value <= 5 && -1 <= value) return new InsnNode(ICONST_M1 + value + 1); + + if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) return new IntInsnNode(BIPUSH, value); + + if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) return new IntInsnNode(SIPUSH, value); + + return new LdcInsnNode(value); + } + + static void visitIntNode(final MethodVisitor mv, final int value) { + if (value <= 5 && -1 <= value) mv.visitInsn(ICONST_M1 + value + 1); + else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) mv.visitIntInsn(BIPUSH, value); + else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) mv.visitIntInsn(SIPUSH, value); + else mv.visitLdcInsn(value); + } + + /** Replace an instruction with a list of instructions. */ + static int replace(final InsnList instructions, final int i, final AbstractInsnNode location, final InsnList list) { + final int size = list.size(); + + instructions.insert(location, list); + instructions.remove(location); + + return i + (size - 1); + } + + private static void throwAccessErrorOnReadOnlyField(String className, String fieldName) { + throw new IllegalAccessError("The " + className + "." + fieldName + " field is final."); + } + + private static void printBytecode(byte[] bytecode) { + StringWriter sw = new StringWriter(); + ClassVisitor tracer = new TraceClassVisitor(new ClassWriter(0), new PrintWriter(sw)); + new ClassReader(bytecode).accept(tracer, 0); + String dump = sw.toString(); + + LWJGLUtil.log(dump); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java b/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java new file mode 100644 index 0000000..4bb7fbf --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedObjectUnsafe.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import sun.misc.Unsafe; + +/** + * [INTERNAL USE ONLY] + * + * @author Riven + */ +final class MappedObjectUnsafe { + + static final Unsafe INSTANCE = getUnsafeInstance(); + + private static final long BUFFER_ADDRESS_OFFSET = getObjectFieldOffset(ByteBuffer.class, "address"); + private static final long BUFFER_CAPACITY_OFFSET = getObjectFieldOffset(ByteBuffer.class, "capacity"); + + private static final ByteBuffer global = ByteBuffer.allocateDirect(4 * 1024); + + static ByteBuffer newBuffer(long address, int capacity) { + if (address <= 0L || capacity < 0) throw new IllegalStateException("you almost crashed the jvm"); + + ByteBuffer buffer = global.duplicate() + .order(ByteOrder.nativeOrder()); + INSTANCE.putLong(buffer, BUFFER_ADDRESS_OFFSET, address); + INSTANCE.putInt(buffer, BUFFER_CAPACITY_OFFSET, capacity); + buffer.position(0); + buffer.limit(capacity); + return buffer; + } + + private static long getObjectFieldOffset(Class type, String fieldName) { + while (type != null) { + try { + return INSTANCE.objectFieldOffset(type.getDeclaredField(fieldName)); + } catch (Throwable t) { + type = type.getSuperclass(); + } + } + + throw new UnsupportedOperationException(); + } + + private static Unsafe getUnsafeInstance() { + final Field[] fields = Unsafe.class.getDeclaredFields(); + + /* + * Different runtimes use different names for the Unsafe singleton, + * so we cannot use .getDeclaredField and we scan instead. For example: + * Oracle: theUnsafe + * PERC : m_unsafe_instance + * Android: THE_ONE + */ + for (Field field : fields) { + if (!field.getType() + .equals(Unsafe.class)) continue; + + final int modifiers = field.getModifiers(); + if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) continue; + + field.setAccessible(true); + try { + return (Unsafe) field.get(null); + } catch (IllegalAccessException e) { + // ignore + } + break; + } + + throw new UnsupportedOperationException(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet.java b/src/main/java/org/lwjglx/util/mapped/MappedSet.java new file mode 100644 index 0000000..6324bd7 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +/** + * Factory for mapped sets. A mapped set can be used as a Structure of Arrays by + * linking together the view of two or more mapped objects. Changing the view + * of the mapped set, changes the corresponding view of all the mapped objects in + * the set. + */ +public class MappedSet { + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet2 create(MappedObject a, MappedObject b) { + return new MappedSet2(a, b); + } + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet3 create(MappedObject a, MappedObject b, MappedObject c) { + return new MappedSet3(a, b, c); + } + + /** + * Creates a MappedSet by linking the specified MappedObjects. + * + * @return the mapped set. + */ + public static MappedSet4 create(MappedObject a, MappedObject b, MappedObject c, MappedObject d) { + return new MappedSet4(a, b, c, d); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet2.java b/src/main/java/org/lwjglx/util/mapped/MappedSet2.java new file mode 100644 index 0000000..117d04f --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet2.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +/** MappedSet implementation for two MappedObjects. */ +public class MappedSet2 { + + private final MappedObject a, b; + + MappedSet2(MappedObject a, MappedObject b) { + this.a = a; + this.b = b; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet3.java b/src/main/java/org/lwjglx/util/mapped/MappedSet3.java new file mode 100644 index 0000000..c004af0 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet3.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +/** MappedSet implementation for three MappedObjects. */ +public class MappedSet3 { + + private final MappedObject a, b, c; + + MappedSet3(MappedObject a, MappedObject b, MappedObject c) { + this.a = a; + this.b = b; + this.c = c; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + c.setViewAddress(c.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + this.c.next(); + } + +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedSet4.java b/src/main/java/org/lwjglx/util/mapped/MappedSet4.java new file mode 100644 index 0000000..e2d219b --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedSet4.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +/** MappedSet implementation for four MappedObjects. */ +public class MappedSet4 { + + private final MappedObject a, b, c, d; + + MappedSet4(MappedObject a, MappedObject b, MappedObject c, MappedObject d) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + } + + public int view; + + void view(int view) { + a.setViewAddress(a.getViewAddress(view)); + b.setViewAddress(b.getViewAddress(view)); + c.setViewAddress(c.getViewAddress(view)); + d.setViewAddress(d.getViewAddress(view)); + } + + public void next() { + this.a.next(); + this.b.next(); + this.c.next(); + this.d.next(); + } +} diff --git a/src/main/java/org/lwjglx/util/mapped/MappedType.java b/src/main/java/org/lwjglx/util/mapped/MappedType.java new file mode 100644 index 0000000..f84682b --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/MappedType.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation marks a class as a mapped object, which will go under bytecode + * transformation at runtime. Mapped objects cannot be instantiated directly; a data + * buffer must be mapped first and the mapped object instance will then be used as a + * view on top of the buffer. Instead of a separate instance per "element" in the buffer, + * only a single instance is used to manage everything. See {@link MappedObject} + * for API details and org.lwjgl.test.mapped.TestMappedObject for examples. + *

+ * The instance fields of the annotated class should only be limited to primitive types or + * {@link java.nio.ByteBuffer}. Static fields are supported and they can have any type. + *

+ * The purpose of mapped objects is to reduce the memory requirements required for the type + * of data that are often used in OpenGL/OpenCL programming, while at the same time enabling + * clean Java code. There are also performance benefits related to not having to copy data + * between buffers and Java objects and the removal of bounds checking when accessing + * buffer data. + * + * @author Riven + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface MappedType { + + /** + * The number of bytes to add to the total byte size. + * SIZEOF will be calculated as SIZEOF = max(field_offset + field_length) + padding. + *

+ * Cannot be used with {@link #cacheLinePadding()}. + * + * @return the padding amount + */ + int padding() default 0; + + /** + * When true, SIZEOF will be increased (if necessary) so that it's a multiple of the CPU cache line size. + * Additionally, {@link MappedObject#malloc(int)} on the mapped object type will automatically use + * {@link CacheUtil#createByteBuffer(int)} instead of the unaligned + * {@link org.lwjgl.BufferUtils#createByteBuffer(int)}. + *

+ * Cannot be used with {@link #padding()}. + * + * @return if cache-line padding should be applied + * + * @see CacheUtil + */ + boolean cacheLinePadding() default false; + + /** + * The mapped data memory alignment, in bytes. + * + * @return the memory alignment + */ + int align() default 4; + + /** + * When autoGenerateOffsets is true, byte offsets of the mapped fields will + * be generated automatically. This is convenient for packed data. For manually + * aligned data, autoGenerateOffsets must be set to false and the user needs + * to manually specify byte offsets using the {@link MappedField} annotation. + * + * @return true if automatic byte offset generation is required. + */ + boolean autoGenerateOffsets() default true; + +} diff --git a/src/main/java/org/lwjglx/util/mapped/Pointer.java b/src/main/java/org/lwjglx/util/mapped/Pointer.java new file mode 100644 index 0000000..f7c8982 --- /dev/null +++ b/src/main/java/org/lwjglx/util/mapped/Pointer.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2002-2011 LWJGL Project + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjglx.util.mapped; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation can be used on long fields of {@link MappedObject} subclasses, + * to specify that the long value should be interpreted as a pointer. This + * will determine the actual byte size of the field at runtime (4 or 8 bytes). + * + * @author Spasi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Pointer { + +} diff --git a/src/main/resources/META-INF/rfb-plugin/lwjgl3ify.properties b/src/main/resources/META-INF/rfb-plugin/lwjgl3ify.properties new file mode 100644 index 0000000..4a98429 --- /dev/null +++ b/src/main/resources/META-INF/rfb-plugin/lwjgl3ify.properties @@ -0,0 +1,9 @@ +name=LWJGL3ify +version=${version} +additionalVersions= +className=me.eigenraven.lwjgl3ify.rfb.Lwjgl3ifyRfbPlugin +transformerExclusions=me.eigenraven.lwjgl3ify +versionConstraints= +loadBefore= +loadAfter= +loadRequires= diff --git a/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/GraphicalConsole.java b/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/GraphicalConsole.java new file mode 100644 index 0000000..a149bd8 --- /dev/null +++ b/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/GraphicalConsole.java @@ -0,0 +1,201 @@ +package me.eigenraven.lwjgl3ify.relauncherstub; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; +import javax.swing.text.BadLocationException; + +import com.github.weisj.darklaf.LafManager; +import com.github.weisj.darklaf.theme.spec.ColorToneRule; +import com.github.weisj.darklaf.theme.spec.ContrastRule; +import com.github.weisj.darklaf.theme.spec.PreferredThemeStyle; + +public class GraphicalConsole { + + // Give up after 32MB of logs + static final long MAX_LOG_SIZE = 32 * 1024 * 1024; + final ConcurrentLinkedQueue consoleBuffer = new ConcurrentLinkedQueue<>(); + final AtomicLong logSize = new AtomicLong(0); + final AtomicBoolean logSizeExceededMax = new AtomicBoolean(false); + final InputStream stdout, stderr; + Thread stdoutAdapter; + Thread stderrAdapter; + final Process process; + + class StreamToQueueAdapter implements Runnable { + + final BufferedReader reader; + final JTextArea guiLog; + final static String LINE_SEPARATOR = System.lineSeparator(); + + StreamToQueueAdapter(InputStream stream, JTextArea guiLog) { + reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + this.guiLog = guiLog; + } + + @Override + public void run() { + while (true) { + try { + final String line = reader.readLine(); + if (line == null) { + // EOF + break; + } + invokeOnSwingThread(false, () -> { + while (!consoleBuffer.isEmpty()) { + final String bufferedLine = consoleBuffer.remove(); + try { + guiLog.getDocument() + .insertString( + guiLog.getDocument() + .getLength(), + bufferedLine + LINE_SEPARATOR, + null); + } catch (BadLocationException e) { + // ignored + } + } + }); + final long currLogSize = logSize.addAndGet(line.length() + 1); + if (currLogSize > MAX_LOG_SIZE) { + final boolean prevExceeded = logSizeExceededMax.getAndSet(true); + if (!prevExceeded) { + consoleBuffer.add("Max console size exceeded, > " + MAX_LOG_SIZE + " bytes!"); + } + return; + } + consoleBuffer.add(line); + } catch (IOException e) { + break; + } + } + try { + reader.close(); + } catch (IOException e) { + // ignored + } + } + } + + public GraphicalConsole(final InputStream stdout, final InputStream stderr, final Process process) { + this.stdout = stdout; + this.stderr = stderr; + this.process = process; + try { + System.setProperty("awt.useSystemAAFontSettings", "on"); + LafManager.installTheme(new PreferredThemeStyle(ContrastRule.STANDARD, ColorToneRule.DARK)); + } catch (Exception e) { + consoleBuffer.add("Could not initialize DarkLaf GUI theme"); + } + + invokeOnSwingThread(true, () -> { + final JFrame consoleWindow = new JFrame("Lwjgl3ify relaunch console"); + consoleWindow.setMinimumSize(new Dimension(640, 500)); + consoleWindow.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + final JTextArea logArea = new JTextArea(); + logArea.setEditable(false); + logArea.setFont( + Font.decode(Font.MONOSPACED) + .deriveFont(14.0f)); + try { + logArea.getDocument() + .insertString( + logArea.getDocument() + .getLength(), + "Relaunching the process with new Java..." + System.lineSeparator(), + null); + } catch (BadLocationException e) { + throw new RuntimeException(e); + } + final JScrollPane logScroll = new JScrollPane(logArea); + consoleWindow.getContentPane() + .add(logScroll, BorderLayout.CENTER); + + this.stdoutAdapter = new Thread(new StreamToQueueAdapter(stdout, logArea), "stdout adapter"); + this.stdoutAdapter.setDaemon(true); + this.stdoutAdapter.start(); + this.stderrAdapter = new Thread(new StreamToQueueAdapter(stderr, logArea), "stderr adapter"); + this.stderrAdapter.setDaemon(true); + this.stderrAdapter.start(); + + final JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); + final JButton closeMeButton = new JButton("Close console"); + closeMeButton.addActionListener(al -> consoleWindow.dispose()); + final JButton killButton = new JButton("Kill process"); + killButton.addActionListener(al -> process.destroyForcibly()); + + buttonPanel.add(closeMeButton); + buttonPanel.add(killButton); + + consoleWindow.getContentPane() + .add(buttonPanel, BorderLayout.SOUTH); + + final Thread processDeathAwaiter = new Thread(() -> { + try { + final Process terminated = process.onExit() + .get(); + final int exitCode = terminated.exitValue(); + invokeOnSwingThread(false, () -> { + killButton.setEnabled(false); + try { + logArea.getDocument() + .insertString( + logArea.getDocument() + .getLength(), + "Process exited with code " + exitCode, + null); + } catch (BadLocationException e) { + // ignored + } + }); + + } catch (InterruptedException | ExecutionException e) { + // ignored + } + }, "death awaiter"); + processDeathAwaiter.start(); + + consoleWindow.setVisible(true); + }); + } + + private void invokeOnSwingThread(boolean wait, Runnable runnable) { + try { + if (wait) { + SwingUtilities.invokeAndWait(runnable); + } else { + SwingUtilities.invokeLater(runnable); + } + } catch (InterruptedException e) { + // cancelled + } catch (InvocationTargetException e) { + if (e.getCause() instanceof RuntimeException re) { + throw re; + } else { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/RelauncherStubMain.java b/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/RelauncherStubMain.java new file mode 100644 index 0000000..1384861 --- /dev/null +++ b/src/relauncherStub/java/me/eigenraven/lwjgl3ify/relauncherstub/RelauncherStubMain.java @@ -0,0 +1,72 @@ +package me.eigenraven.lwjgl3ify.relauncherstub; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Arrays; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; + +/** + * Run with arguments of [parentPid, show console [true/false], java binary, java arguments]. + * Needs modern Java to access the ProcessHandle API. + */ +public class RelauncherStubMain { + + public RelauncherStubMain() {} + + public void run(String[] args) throws Throwable { + if (args.length < 4) { + System.err.println("Missing arguments"); + return; + } + final long parentPid = Long.parseLong(args[0]); + final boolean showConsole = Boolean.parseBoolean(args[1]); + final String[] javaCmdline = Arrays.copyOfRange(args, 2, args.length); + final ProcessHandle myProcess = ProcessHandle.current(); + final ProcessHandle parentProcess = ProcessHandle.of(parentPid) + .orElse( + myProcess.parent() + .orElse(null)); + + System.out.println("quit"); // notify the parent that we're ok to wait on them + if (parentProcess != null) { + // Wait for parent to fully exit + parentProcess.onExit() + .get(); + } else { + // Wait a little bit, hopefully the parent exits in this time (not finding the parent shouldn't happen) + Thread.sleep(1000); + } + + final ProcessBuilder childBuilder = new ProcessBuilder(javaCmdline); + + if (showConsole) { + childBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE); + childBuilder.redirectError(ProcessBuilder.Redirect.PIPE); + final Process child = childBuilder.start(); + new GraphicalConsole(child.getInputStream(), child.getErrorStream(), child); + } else { + childBuilder.redirectOutput(ProcessBuilder.Redirect.DISCARD); + childBuilder.redirectError(ProcessBuilder.Redirect.DISCARD); + childBuilder.start(); + } + + } + + public static void main(String[] args) throws Throwable { + try { + new RelauncherStubMain().run(args); + } catch (Throwable e) { + final StringWriter traceWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(traceWriter)); + SwingUtilities.invokeAndWait(() -> { + JOptionPane.showMessageDialog( + null, + e.toString() + "\n" + traceWriter.toString(), + "Relauncher crash", + JOptionPane.ERROR_MESSAGE); + }); + } + } +}