diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b01da52cff..2c7692186d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,37 +1,113 @@ -# Automatically build the project and run any configured tests for every push -# and submitted pull request. This can help catch issues that only occur on -# certain platforms or Java versions, and provides a first line of defence -# against bad commits. - name: build -on: [pull_request, push] +on: [push, workflow_dispatch] + +permissions: + contents: write jobs: build: - strategy: - matrix: - # Use these Java versions - java: [ - 21, # Current Java LTS - ] - runs-on: ubuntu-22.04 + runs-on: ubuntu-latest steps: - - name: checkout repository - uses: actions/checkout@v4 - - name: validate gradle wrapper - uses: gradle/wrapper-validation-action@v2 - - name: setup jdk ${{ matrix.java }} - uses: actions/setup-java@v4 + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: microsoft + java-version: 21 + + - uses: gradle/actions/setup-gradle@v4 + + # Android (bionic) arm64 builds of the LWJGL natives that the glibc linux-arm64 + # builds cannot provide on Zalith/Pojav. Cached so only the first run is slow. + - name: Cache Android natives + id: natives-cache + uses: actions/cache@v4 + with: + path: src/main/resources/linux/arm64/org/lwjgl + key: android-natives-v1-${{ hashFiles('.github/workflows/build.yml') }} + + - name: Build Android arm64 natives (spirv-cross, shaderc) + if: steps.natives-cache.outputs.cache-hit != 'true' + run: | + set -euxo pipefail + sudo apt-get update -y + sudo apt-get install -y ninja-build cmake python3 git + + NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_ROOT:-${ANDROID_NDK_HOME:-}}}" + test -d "$NDK" + STRIP="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip" + COMMON=(-G Ninja + -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" + -DANDROID_ABI=arm64-v8a + -DANDROID_PLATFORM=android-26 + -DANDROID_STL=c++_static + -DCMAKE_BUILD_TYPE=Release) + + OUT="$GITHUB_WORKSPACE/src/main/resources/linux/arm64/org/lwjgl" + mkdir -p "$OUT/spvc" "$OUT/shaderc" + cd "$RUNNER_TEMP" + + # --- SPIRV-Cross (C API) -> libspirv-cross.so --- + git clone --depth 1 --branch vulkan-sdk-1.3.296.0 https://github.com/KhronosGroup/SPIRV-Cross.git + cmake -S SPIRV-Cross -B spvc-build "${COMMON[@]}" \ + -DSPIRV_CROSS_SHARED=ON -DSPIRV_CROSS_STATIC=OFF \ + -DSPIRV_CROSS_CLI=OFF -DSPIRV_CROSS_ENABLE_TESTS=OFF + cmake --build spvc-build --target spirv-cross-c-shared -j"$(nproc)" + cp "$(find spvc-build -name 'libspirv-cross-c-shared.so' | head -n1)" "$OUT/spvc/libspirv-cross.so" + "$STRIP" --strip-unneeded "$OUT/spvc/libspirv-cross.so" + + # --- shaderc -> libshaderc.so --- + git clone --depth 1 --branch v2024.4 https://github.com/google/shaderc.git + (cd shaderc && python3 utils/git-sync-deps) + cmake -S shaderc -B shaderc-build "${COMMON[@]}" \ + -DSHADERC_SKIP_TESTS=ON -DSHADERC_SKIP_EXAMPLES=ON \ + -DSHADERC_SKIP_COPYRIGHT_CHECK=ON -DSHADERC_ENABLE_WERROR_COMPILE=OFF \ + -DSPIRV_SKIP_TESTS=ON -DSPIRV_SKIP_EXECUTABLES=ON \ + -DENABLE_GLSLANG_BINARIES=OFF -DSPIRV_HEADERS_SKIP_EXAMPLES=ON + cmake --build shaderc-build --target shaderc_shared -j"$(nproc)" + cp "$(find shaderc-build -name 'libshaderc_shared.so' | head -n1)" "$OUT/shaderc/libshaderc.so" + "$STRIP" --strip-unneeded "$OUT/shaderc/libshaderc.so" + + - name: Check natives + run: | + set -eux + for f in spvc/libspirv-cross.so shaderc/libshaderc.so; do + p="src/main/resources/linux/arm64/org/lwjgl/$f" + test -s "$p" + file "$p" + # must not depend on glibc's libstdc++ + ! (readelf -d "$p" | grep -q 'libstdc++') + done + + - run: chmod +x ./gradlew && ./gradlew build --no-daemon + + - name: Check natives are inside the jar + run: | + JAR="$(ls build/libs/*.jar | grep -v sources | head -n1)" + unzip -l "$JAR" | grep -E 'linux/arm64/org/lwjgl/(spvc/libspirv-cross|shaderc/libshaderc)\.so' + test "$(unzip -l "$JAR" | grep -cE 'linux/arm64/org/lwjgl/(spvc/libspirv-cross|shaderc/libshaderc)\.so')" -eq 2 + + - name: Prepare jar + run: | + mkdir out + cp "$(ls build/libs/*.jar | grep -v sources | head -n1)" out/Riftoptimizer-Vulkan-mobile.jar + + - uses: actions/upload-artifact@v4 with: - java-version: ${{ matrix.java }} - distribution: 'microsoft' - - name: make gradle wrapper executable - run: chmod +x ./gradlew - - name: build - run: ./gradlew build - - name: capture build artifacts - if: ${{ matrix.java == '21' }} # Only upload artifacts built from latest java - uses: actions/upload-artifact@v4 + name: Riftoptimizer-Vulkan-mobile + path: out/Riftoptimizer-Vulkan-mobile.jar + + - uses: softprops/action-gh-release@v2 + if: github.ref == 'refs/heads/mobile-compat' with: - name: Artifacts - path: build/libs/ \ No newline at end of file + tag_name: mobile-test + name: Riftoptimizer-Vulkan Mobile Test + prerelease: true + fail_on_unmatched_files: true + files: out/Riftoptimizer-Vulkan-mobile.jar + body: | + Test build for Minecraft 1.21.11 (Fabric), for Zalith/Pojav on Android. + - LWJGL modules bundled at 3.3.6 to match the launcher (fixes NoSuchFieldError UNSAFE). + - libspirv-cross.so and libshaderc.so are now built for Android arm64 (bionic, static libc++) + by CI and shipped inside the jar (fixes libstdc++.so.6 / libspirv-cross.so UnsatisfiedLinkError). + Not fully verified on Android yet. \ No newline at end of file diff --git a/build.gradle b/build.gradle index ca529cce1e..c8fc14e290 100644 --- a/build.gradle +++ b/build.gradle @@ -40,27 +40,37 @@ dependencies { includeModule("fabric-transitive-access-wideners-v1") } -project.ext.lwjglVersion = "3.3.3" +// Mobile (Zalith/Pojav) ships LWJGL 3.3.6-snapshot as core. Bundled modules must +// match it: 3.3.3 structs reference Struct.UNSAFE, which no longer exists in 3.3.6. +project.ext.lwjglVersion = "3.3.6" project.ext.jomlVersion = "1.10.4" project.ext.winNatives = "natives-windows" project.ext.linuxNatives = "natives-linux" +project.ext.linuxArmNatives = "natives-linux-arm64" project.ext.macosNatives = "natives-macos" project.ext.macosArmNatives = "natives-macos-arm64" dependencies { include(implementation("org.lwjgl:lwjgl-vulkan:$lwjglVersion")) - ext.includeNatives = { name -> + // shaderc / spirv-cross: the official linux-arm64 natives are glibc builds that need + // libstdc++.so.6, which Android does not have (UnsatisfiedLinkError on libshaderc.so). + // For these two, the arm64 .so files are built for Android (bionic, static libc++) by CI + // and shipped as resources at linux/arm64/org/lwjgl// instead. + ext.includeNatives = { name, androidBuilt -> include(implementation("$name:$lwjglVersion")) include(runtimeOnly("$name:$lwjglVersion:$winNatives")) include(runtimeOnly("$name:$lwjglVersion:$linuxNatives")) + if (!androidBuilt) { + include(runtimeOnly("$name:$lwjglVersion:$linuxArmNatives")) + } include(runtimeOnly("$name:$lwjglVersion:$macosNatives")) include(runtimeOnly("$name:$lwjglVersion:$macosArmNatives")) } - includeNatives("org.lwjgl:lwjgl-vma") - includeNatives("org.lwjgl:lwjgl-shaderc") - includeNatives("org.lwjgl:lwjgl-spvc") + includeNatives("org.lwjgl:lwjgl-vma", false) + includeNatives("org.lwjgl:lwjgl-shaderc", true) + includeNatives("org.lwjgl:lwjgl-spvc", true) //MoltenVK include(runtimeOnly("org.lwjgl:lwjgl-vulkan:$lwjglVersion:$macosNatives")) @@ -80,9 +90,6 @@ tasks.withType(JavaCompile).configureEach { } java { - // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task - // if it is present. - // If you remove this line, sources will not be generated. withSourcesJar() sourceCompatibility = JavaVersion.VERSION_21 @@ -104,11 +111,6 @@ publishing { } } - // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. repositories { - // Add repositories to publish to here. - // Notice: This block does NOT have the same function as the block in the top level. - // The repositories here will be used for publishing your artifact, not for - // retrieving dependencies. } } diff --git a/build.yml.new b/build.yml.new new file mode 100644 index 0000000000..36c23ec3b9 --- /dev/null +++ b/build.yml.new @@ -0,0 +1,98 @@ +name: build +on: [push, workflow_dispatch] + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: microsoft + java-version: 21 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Cache Android natives + id: natcache + uses: actions/cache@v4 + with: + path: android-natives + key: android-natives-shaderc-2024.4-spvc-1.3.280-v1 + + - name: Build Android natives (shaderc + SPIRV-Cross, bionic, static libc++) + if: steps.natcache.outputs.cache-hit != 'true' + run: | + set -euxo pipefail + NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}" + TC="$NDK/build/cmake/android.toolchain.cmake" + STRIP="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip" + COMMON="-G Ninja -DCMAKE_TOOLCHAIN_FILE=$TC -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DANDROID_STL=c++_static -DCMAKE_BUILD_TYPE=Release -DCMAKE_SHARED_LINKER_FLAGS=-Wl,-z,max-page-size=16384" + mkdir -p android-natives + + git clone --depth 1 --branch v2024.4 https://github.com/google/shaderc + (cd shaderc && python3 utils/git-sync-deps) + cmake -S shaderc -B build-shaderc $COMMON \ + -DSHADERC_SKIP_TESTS=ON -DSHADERC_SKIP_EXAMPLES=ON -DSHADERC_SKIP_COPYRIGHT_CHECK=ON \ + -DSPIRV_SKIP_TESTS=ON -DSPIRV_SKIP_EXECUTABLES=ON -DSKIP_GLSLANG_INSTALL=ON \ + -DSKIP_SPIRV_TOOLS_INSTALL=ON -DSKIP_GOOGLETEST_INSTALL=ON -DENABLE_GLSLANG_BINARIES=OFF + cmake --build build-shaderc --target shaderc_shared -j"$(nproc)" + cp "$(find build-shaderc -name 'libshaderc_shared.so' | head -n1)" android-natives/libshaderc.so + + git clone --depth 1 --branch vulkan-sdk-1.3.280.0 https://github.com/KhronosGroup/SPIRV-Cross + cmake -S SPIRV-Cross -B build-spvc $COMMON \ + -DSPIRV_CROSS_SHARED=ON -DSPIRV_CROSS_STATIC=OFF -DSPIRV_CROSS_CLI=OFF -DSPIRV_CROSS_ENABLE_TESTS=OFF + cmake --build build-spvc -j"$(nproc)" + cp "$(find build-spvc -name 'libspirv-cross-c-shared.so' | head -n1)" android-natives/libspirv-cross.so + + "$STRIP" --strip-unneeded android-natives/*.so + + - name: Verify natives are Android-compatible + run: | + set -eu + for f in android-natives/libshaderc.so android-natives/libspirv-cross.so; do + test -s "$f" + readelf -h "$f" | grep -q AArch64 + readelf -d "$f" | grep NEEDED + if readelf -d "$f" | grep -E 'libstdc\+\+|libgcc_s'; then echo "::error::$f depends on glibc libstdc++"; exit 1; fi + done + + - name: Add natives to mod resources + run: | + mkdir -p src/main/resources/linux/arm64/org/lwjgl/shaderc src/main/resources/linux/arm64/org/lwjgl/spvc + cp android-natives/libshaderc.so src/main/resources/linux/arm64/org/lwjgl/shaderc/libshaderc.so + cp android-natives/libspirv-cross.so src/main/resources/linux/arm64/org/lwjgl/spvc/libspirv-cross.so + + - run: chmod +x ./gradlew && ./gradlew build --no-daemon + + - name: Prepare jar + run: | + mkdir out + cp "$(ls build/libs/*.jar | grep -v sources | head -n1)" out/Riftoptimizer-Vulkan-mobile.jar + unzip -l out/Riftoptimizer-Vulkan-mobile.jar | grep -E 'linux/arm64/org/lwjgl/(shaderc|spvc)/' + + - uses: actions/upload-artifact@v4 + with: + name: Riftoptimizer-Vulkan-mobile + path: out/Riftoptimizer-Vulkan-mobile.jar + + - uses: softprops/action-gh-release@v2 + if: github.ref == 'refs/heads/mobile-compat' + with: + tag_name: mobile-v4-android-natives + name: Riftoptimizer-Vulkan Mobile v4 (Android natives) + prerelease: true + fail_on_unmatched_files: true + files: out/Riftoptimizer-Vulkan-mobile.jar + body: | + Minecraft 1.21.11 (Fabric), Zalith/Pojav on Android (arm64). + + Fixes crash #3: `UnsatisfiedLinkError ... libshaderc.so ... library "libstdc++.so.6" not found`. + - libshaderc / libspirv-cross are now built for Android (bionic, static libc++) in CI instead of + using the glibc linux-arm64 LWJGL builds. This also pre-empts the same crash in spirv-cross. + - Shaders now target Vulkan 1.0 / SPIR-V 1.0 so Vulkan-1.0-only drivers (Turnip Adreno 610) accept them. + Use together with Riftoptimizer 1.2.6. Not yet verified on a device. diff --git a/ci/build.yml b/ci/build.yml new file mode 100644 index 0000000000..3365f5b93a --- /dev/null +++ b/ci/build.yml @@ -0,0 +1,113 @@ +name: build +on: [push, workflow_dispatch] + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: microsoft + java-version: 21 + + - uses: gradle/actions/setup-gradle@v4 + + # Android (bionic) arm64 builds of the LWJGL natives that the glibc linux-arm64 + # builds cannot provide on Zalith/Pojav. Cached so only the first run is slow. + - name: Cache Android natives + id: natives-cache + uses: actions/cache@v4 + with: + path: src/main/resources/linux/arm64/org/lwjgl + key: android-natives-v1-${{ hashFiles('.github/workflows/build.yml') }} + + - name: Build Android arm64 natives (spirv-cross, shaderc) + if: steps.natives-cache.outputs.cache-hit != 'true' + run: | + set -euxo pipefail + sudo apt-get update -y + sudo apt-get install -y ninja-build cmake python3 git + + NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_ROOT:-${ANDROID_NDK_HOME:-}}}" + test -d "$NDK" + STRIP="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip" + COMMON=(-G Ninja + -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" + -DANDROID_ABI=arm64-v8a + -DANDROID_PLATFORM=android-26 + -DANDROID_STL=c++_static + -DCMAKE_BUILD_TYPE=Release) + + OUT="$GITHUB_WORKSPACE/src/main/resources/linux/arm64/org/lwjgl" + mkdir -p "$OUT/spvc" "$OUT/shaderc" + cd "$RUNNER_TEMP" + + # --- SPIRV-Cross (C API) -> libspirv-cross.so --- + git clone --depth 1 --branch vulkan-sdk-1.3.296.0 https://github.com/KhronosGroup/SPIRV-Cross.git + cmake -S SPIRV-Cross -B spvc-build "${COMMON[@]}" \ + -DSPIRV_CROSS_SHARED=ON -DSPIRV_CROSS_STATIC=OFF \ + -DSPIRV_CROSS_CLI=OFF -DSPIRV_CROSS_ENABLE_TESTS=OFF + cmake --build spvc-build --target spirv-cross-c-shared -j"$(nproc)" + cp "$(find spvc-build -name 'libspirv-cross-c-shared.so' | head -n1)" "$OUT/spvc/libspirv-cross.so" + "$STRIP" --strip-unneeded "$OUT/spvc/libspirv-cross.so" + + # --- shaderc -> libshaderc.so --- + git clone --depth 1 --branch v2024.4 https://github.com/google/shaderc.git + (cd shaderc && python3 utils/git-sync-deps) + cmake -S shaderc -B shaderc-build "${COMMON[@]}" \ + -DSHADERC_SKIP_TESTS=ON -DSHADERC_SKIP_EXAMPLES=ON \ + -DSHADERC_SKIP_COPYRIGHT_CHECK=ON -DSHADERC_ENABLE_WERROR_COMPILE=OFF \ + -DSPIRV_SKIP_TESTS=ON -DSPIRV_SKIP_EXECUTABLES=ON \ + -DENABLE_GLSLANG_BINARIES=OFF -DSPIRV_HEADERS_SKIP_EXAMPLES=ON + cmake --build shaderc-build --target shaderc_shared -j"$(nproc)" + cp "$(find shaderc-build -name 'libshaderc_shared.so' | head -n1)" "$OUT/shaderc/libshaderc.so" + "$STRIP" --strip-unneeded "$OUT/shaderc/libshaderc.so" + + - name: Check natives + run: | + set -eux + for f in spvc/libspirv-cross.so shaderc/libshaderc.so; do + p="src/main/resources/linux/arm64/org/lwjgl/$f" + test -s "$p" + file "$p" + # must not depend on glibc's libstdc++ + ! (readelf -d "$p" | grep -q 'libstdc++') + done + + - run: chmod +x ./gradlew && ./gradlew build --no-daemon + + - name: Check natives are inside the jar + run: | + JAR="$(ls build/libs/*.jar | grep -v sources | head -n1)" + unzip -l "$JAR" | grep -E 'linux/arm64/org/lwjgl/(spvc/libspirv-cross|shaderc/libshaderc)\.so' + test "$(unzip -l "$JAR" | grep -cE 'linux/arm64/org/lwjgl/(spvc/libspirv-cross|shaderc/libshaderc)\.so')" -eq 2 + + - name: Prepare jar + run: | + mkdir out + cp "$(ls build/libs/*.jar | grep -v sources | head -n1)" out/Riftoptimizer-Vulkan-mobile.jar + + - uses: actions/upload-artifact@v4 + with: + name: Riftoptimizer-Vulkan-mobile + path: out/Riftoptimizer-Vulkan-mobile.jar + + - uses: softprops/action-gh-release@v2 + if: github.ref == 'refs/heads/mobile-compat' + with: + tag_name: mobile-test + name: Riftoptimizer-Vulkan Mobile Test + prerelease: true + fail_on_unmatched_files: true + files: out/Riftoptimizer-Vulkan-mobile.jar + body: | + Test build for Minecraft 1.21.11 (Fabric), for Zalith/Pojav on Android. + - LWJGL modules bundled at 3.3.6 to match the launcher (fixes NoSuchFieldError UNSAFE). + - libspirv-cross.so and libshaderc.so are now built for Android arm64 (bionic, static libc++) + by CI and shipped inside the jar (fixes libstdc++.so.6 / libspirv-cross.so UnsatisfiedLinkError). + Not fully verified on Android yet. diff --git a/src/main/java/net/vulkanmod/config/RiftBridge.java b/src/main/java/net/vulkanmod/config/RiftBridge.java new file mode 100644 index 0000000000..ffabe1f10a --- /dev/null +++ b/src/main/java/net/vulkanmod/config/RiftBridge.java @@ -0,0 +1,285 @@ +package net.vulkanmod.config; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import net.vulkanmod.Initializer; +import net.vulkanmod.config.gui.OptionBlock; +import net.vulkanmod.config.option.CyclingOption; +import net.vulkanmod.config.option.Option; +import net.vulkanmod.config.option.OptionPage; +import net.vulkanmod.config.option.RangeOption; +import net.vulkanmod.config.option.SwitchOption; +import net.vulkanmod.render.chunk.build.light.LightMode; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** + * Puts the Riftoptimizer settings (mod id "rift") into the VulkanMod settings screen. + * Everything goes through reflection on dev.fpsuim.Config, so this jar needs no Riftoptimizer + * classes at build time and a missing field only hides that one option. + */ +public final class RiftBridge { + private static Class cfgClass; + + private RiftBridge() {} + + public static boolean isPresent() { + if (!FabricLoader.getInstance().isModLoaded("rift")) return false; + try { + cfgClass = Class.forName("dev.fpsuim.Config"); + return true; + } catch (Throwable t) { + Initializer.LOGGER.warn("Riftoptimizer found but its Config class could not be loaded", t); + return false; + } + } + + // ---- reflection helpers ---- + + private static Object cfg() throws ReflectiveOperationException { + return cfgClass.getMethod("get").invoke(null); + } + + private static Field field(String key) { + try { + return cfgClass.getField(key); + } catch (ReflectiveOperationException e) { + return null; + } + } + + private static int getInt(String key) { + try { + return ((Number) field(key).get(cfg())).intValue(); + } catch (Throwable t) { + return 0; + } + } + + private static void setInt(String key, int v) { + try { + Field f = field(key); + Object c = cfg(); + if (f.getType() == double.class) f.setDouble(c, v); + else f.setInt(c, v); + } catch (Throwable ignored) { + } + } + + private static boolean getBool(String key) { + try { + return field(key).getBoolean(cfg()); + } catch (Throwable t) { + return false; + } + } + + private static void setBool(String key, boolean v) { + try { + field(key).setBoolean(cfg(), v); + } catch (Throwable ignored) { + } + } + + private static String getString(String key) { + try { + Object o = field(key).get(cfg()); + return o == null ? "" : o.toString(); + } catch (Throwable t) { + return ""; + } + } + + /** Writes config/rift.json. Runs after every Apply in the settings screen. */ + public static void save() { + try { + Object c = cfg(); + c.getClass().getMethod("save").invoke(c); + } catch (Throwable t) { + Initializer.LOGGER.warn("Could not save Riftoptimizer config", t); + } + } + + // ---- option builders (return null when the Rift field does not exist) ---- + + private static Option sw(String name, String key, String tip) { + if (field(key) == null) return null; + return new SwitchOption(Component.literal(name), v -> setBool(key, v), () -> getBool(key)) + .setTooltip(v -> Component.literal(tip)); + } + + private static Option rng(String name, String key, int min, int max, int step, String tip) { + if (field(key) == null) return null; + return new RangeOption(Component.literal(name), min, max, step, + v -> Component.literal(v == 0 && min == 0 ? "Off" : String.valueOf(v)), + v -> setInt(key, v), () -> getInt(key)) + .setTooltip(v -> Component.literal(tip)); + } + + private static OptionBlock block(Option... options) { + List> list = new ArrayList<>(); + for (Option o : options) if (o != null) list.add(o); + return new OptionBlock("", list.toArray(new Option[0])); + } + + private static OptionPage page(String name, OptionBlock... blocks) { + return new OptionPage(name, blocks); + } + + // ---- pages ---- + + public static List getPages() { + List pages = new ArrayList<>(); + pages.add(presetsPage()); + pages.add(cullingPage()); + pages.add(particlesPage()); + pages.add(soundPage()); + pages.add(systemPage()); + return pages; + } + + private static OptionPage presetsPage() { + String[] names = {"auto", "extreme", "potato", "mobile", "balanced", "quality"}; + Option preset = new CyclingOption<>(Component.literal("Rift Preset"), names, + RiftBridge::applyPreset, () -> getString("profile").toLowerCase()) + .setTranslator(v -> Component.literal(v.toUpperCase())) + .setTooltip(v -> Component.literal( + "Sets Riftoptimizer AND VulkanMod options together. Change only this, press Apply, then reopen the menu.")); + return page("Presets", block(preset)); + } + + private static OptionPage cullingPage() { + Option master = field("entityCulling") == null ? null + : new SwitchOption(Component.literal("Entity Culling"), + v -> { + setBool("entityCulling", v); + Initializer.CONFIG.entityCulling = v; + }, + () -> getBool("entityCulling")) + .setTooltip(v -> Component.literal("Rift and VulkanMod entity culling together (same switch).")); + return page("Culling", + block(master, + sw("Occlusion Culling", "occlusionCulling", "Skip entities hidden behind walls."), + rng("Occlusion Interval", "occlusionInterval", 1, 6, 1, "Ticks between visibility checks. Higher = faster."), + rng("Entity Cull Range", "entityCullDistance", 24, 128, 2, "All entities, blocks."), + rng("Item Cull Range", "itemCullDistance", 8, 48, 1, "Dropped items and XP, blocks."), + rng("Tiny Entity Range", "tinyEntityDistance", 0, 64, 2, "Tiny and baby mobs, blocks. 0 = off."), + rng("Max Entities Per Frame", "maxEntitiesPerFrame", 0, 500, 10, "Far entities past this count are skipped. 0 = off."), + rng("Name Tag Range", "nameTagDistance", 8, 64, 2, "Hide far name tags, blocks.")), + block(rng("TNT Range", "tntDistance", 0, 64, 2, "TNT and falling blocks, blocks. 0 = off."), + rng("Vehicle Range", "vehicleDistance", 0, 64, 2, "Boats and minecarts, blocks. 0 = off."), + rng("Far Tick Range", "farTickDistance", 0, 96, 2, "Entities beyond this tick every 2nd tick. 0 = off."), + rng("Very Far Tick Range", "veryFarTickDistance", 0, 160, 5, "Entities beyond this tick every 4th tick. 0 = off."), + rng("Beacon Range", "beaconDistance", 0, 128, 4, "Beacon beam range (vanilla 256). 0 = vanilla."), + rng("End Portal Range", "endPortalDistance", 0, 128, 4, "End portal range (vanilla 256). 0 = vanilla."))); + } + + private static OptionPage particlesPage() { + return page("Particles", + block(rng("Particle Amount %", "particlePercent", 0, 100, 5, "Share of particles that spawn."), + rng("Particle Range", "particleDistance", 0, 64, 2, "Hide particles farther than this, blocks. 0 = off."), + rng("Particles Per Tick", "particlesPerTick", 0, 500, 10, "Hard cap against explosion lag. 0 = off."), + rng("Particle View Angle", "particleViewAngle", 0, 180, 5, "Drop particles outside this angle of your view. 0 = off."), + sw("Sprint Thinning", "fastMoveParticleThinning", "30% fewer particles while sprinting."), + sw("Low FPS Thinning", "lowFpsThinning", "Halve particles while FPS is under 30."), + sw("Skip Behind You", "skipBehindParticles", "No particles behind the camera."), + sw("Hide Own Potion Fx", "hideOwnPotionParticles", "No potion swirl in first person.")), + block(rng("Rain %", "rainParticlePercent", 0, 100, 5, "Rain splash particles."), + rng("Explosion %", "explosionParticlePercent", 0, 100, 5, "Explosion and poof smoke."), + rng("Block Break %", "blockBreakParticlePercent", 0, 100, 5, "Block breaking debris."), + rng("Combat Hit %", "combatParticlePercent", 0, 100, 5, "Crit, sweep, damage particles."), + rng("Firework %", "fireworkParticlePercent", 0, 100, 5, "Firework sparks."), + rng("Portal Enchant %", "portalParticlePercent", 0, 100, 5, "Nether portal and enchanting table."), + rng("Biome Ambient %", "biomeAmbientParticlePercent", 0, 100, 5, "Ash and spores."), + rng("Dust Snow %", "dustParticlePercent", 0, 100, 5, "Redstone dust and snowflakes."), + rng("Emote %", "emoteParticlePercent", 0, 100, 5, "Hearts, notes, villager sparks.")), + block(rng("Fire Smoke Range", "ambientParticleDistance", 0, 48, 2, "Fire, smoke, campfire, blocks. 0 = off."), + rng("Underwater Range", "underwaterParticleDistance", 0, 32, 2, "Bubbles and splash, blocks. 0 = off."), + rng("Drip Range", "dripParticleDistance", 0, 32, 2, "Water and lava drips, blocks. 0 = off."), + rng("Far Potion Range", "farPotionParticleDistance", 0, 48, 2, "Potion swirls on others, blocks. 0 = off."))); + } + + private static OptionPage soundPage() { + return page("Sound", + block(rng("Sounds Per Tick", "soundsPerTick", 0, 48, 1, "Max new sounds per tick (farms). 0 = off."), + rng("Sound Range", "soundDistance", 0, 64, 2, "Drop quiet sounds beyond this, blocks. 0 = off."), + rng("Sound Dedupe ms", "soundDedupMs", 0, 200, 5, "Drop the same sound repeated within this time. 0 = off."), + sw("Drop Faint Sounds", "dropFaintSounds", "Skip nearly silent sounds."))); + } + + private static OptionPage systemPage() { + Option anim = field("textureAnimations") == null ? null + : new SwitchOption(Component.literal("Texture Animations"), + v -> { + setBool("textureAnimations", v); + Initializer.CONFIG.textureAnimations = v; + }, + () -> getBool("textureAnimations")) + .setTooltip(v -> Component.literal("Water, lava, fire animation. OFF saves GPU. Rift and VulkanMod together.")); + + Option hudPos = field("hudPosition") == null ? null + : new CyclingOption<>(Component.literal("FPS HUD Position"), new Integer[]{0, 1, 2, 3}, + v -> setInt("hudPosition", v), () -> getInt("hudPosition")) + .setTranslator(v -> Component.literal(new String[]{"Top left", "Top right", "Bottom left", "Bottom right"}[Math.floorMod(v, 4)])); + + return page("System", + block(sw("FPS HUD", "hudEnabled", "Own FPS counter on screen (works even when the launcher counter shows 0)."), + hudPos, + anim), + block(sw("Dynamic FPS", "dynamicFps", "Lower FPS in background."), + rng("Background FPS", "backgroundFps", 1, 30, 1, "Limit while unfocused."), + rng("Menu FPS", "menuFps", 0, 90, 5, "Limit while a menu is open. 0 = off."), + rng("AFK FPS", "afkFps", 0, 45, 5, "Limit when idle. 0 = off."), + rng("AFK Seconds", "afkSeconds", 15, 300, 5, "Idle time before AFK FPS."), + rng("Loading FPS", "loadingFps", 0, 60, 5, "Limit while loading (more CPU for loading). 0 = off."), + sw("Power Saver", "powerSaver", "Caps FPS and keeps the governor higher."), + rng("Power Saver FPS", "powerSaverFps", 10, 60, 5, "FPS cap while Power Saver is on.")), + block(sw("Adaptive Governor", "adaptiveGovernor", "Trims entity and particle load when FPS dips."), + rng("Target FPS", "targetFps", 20, 120, 5, "Governor keeps FPS above this."), + sw("Adaptive Weather", "adaptiveWeather", "Weather radius 3 under heavy load."), + sw("Adaptive Clouds", "adaptiveClouds", "Clouds off under extreme load."), + sw("Adaptive Particles", "adaptiveParticleMode", "Minimal particles under extreme load."), + sw("Adaptive Shadows", "adaptiveShadows", "Entity shadows off while FPS < 40.")), + block(sw("Fast Menu Background", "fastMenuBackground", "Flat dark menu background in a world, no blur."), + sw("Skip World In Menus", "skipWorldInMenus", "No 3D world behind Advancements."), + sw("Skip World Loading", "skipWorldDuringLoading", "No 3D world behind the loading screen."), + sw("Smart RAM Cleanup", "smartGc", "Clean RAM in menus when usage is high."), + sw("GC On Exit", "gcOnExit", "Free memory when leaving a world."), + sw("Thread Priority", "threadPriority", "Higher priority for the render thread."))); + } + + // ---- presets ---- + + /** Applies a Riftoptimizer preset, then moves the VulkanMod options that overlap with it to match. */ + private static void applyPreset(String name) { + try { + Minecraft mc = Minecraft.getInstance(); + Class pc = Class.forName("dev.fpsuim.Profile"); + Object profile = pc.getMethod("byName", String.class).invoke(null, name); + Method apply = null; + for (Method m : pc.getMethods()) { + if (m.getName().equals("apply") && m.getParameterCount() == 1) apply = m; + } + if (apply == null) return; + apply.invoke(profile, mc); + + String p = ((Enum) profile).name(); + boolean low = p.equals("EXTREME") || p.equals("POTATO") || p.equals("MOBILE"); + Config vk = Initializer.CONFIG; + vk.advCulling = low ? 1 : 2; + vk.entityCulling = getBool("entityCulling"); + vk.textureAnimations = getBool("textureAnimations"); + boolean ao = mc.options.ambientOcclusion().get(); + if (!ao) vk.ambientOcclusion = LightMode.FLAT; + else if (vk.ambientOcclusion == LightMode.FLAT) vk.ambientOcclusion = LightMode.SMOOTH; + vk.write(); + if (mc.levelRenderer != null) mc.levelRenderer.allChanged(); + } catch (Throwable t) { + Initializer.LOGGER.warn("Could not apply Riftoptimizer preset", t); + } + } +} diff --git a/src/main/java/net/vulkanmod/config/gui/ModSettingsRegistry.java b/src/main/java/net/vulkanmod/config/gui/ModSettingsRegistry.java index d76a93b044..a34caa3691 100644 --- a/src/main/java/net/vulkanmod/config/gui/ModSettingsRegistry.java +++ b/src/main/java/net/vulkanmod/config/gui/ModSettingsRegistry.java @@ -7,6 +7,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.Identifier; import net.vulkanmod.Initializer; +import net.vulkanmod.config.RiftBridge; import net.vulkanmod.config.api.VkModSettingsEntryBuilder; import net.vulkanmod.config.api.VkModSettingsFactory; import net.vulkanmod.config.option.Options; @@ -21,12 +22,20 @@ public class ModSettingsRegistry { private final Set modEntries = new ObjectArraySet<>(); ModSettingsRegistry() { - ModSettingsEntry vulkanModSettings = new ModSettingsEntry(Component.literal("VulkanMod").withStyle(ChatFormatting.DARK_RED), + ModSettingsEntry vulkanModSettings = new ModSettingsEntry(Component.literal("VulkanMod").withStyle(ChatFormatting.DARK_AQUA), () -> Identifier.fromNamespaceAndPath("vulkanmod", "vlogo_transparent.png"), Options::getOptionPages, () -> Initializer.CONFIG.write()); this.addModEntry(vulkanModSettings); + // Riftoptimizer pages live in the same screen when the mod is installed + if (RiftBridge.isPresent()) { + this.addModEntry(new ModSettingsEntry(Component.literal("Riftoptimizer").withStyle(ChatFormatting.AQUA), + () -> Identifier.fromNamespaceAndPath("vulkanmod", "vlogo_transparent.png"), + RiftBridge::getPages, + RiftBridge::save)); + } + // build and add vulkanmod settings entrypoints var entryPointContainers = FabricLoader.getInstance().getEntrypointContainers(CONFIG_ENTRY_POINT_KEY, VkModSettingsFactory.class); for (EntrypointContainer entryPointContainer : entryPointContainers) { diff --git a/src/main/java/net/vulkanmod/config/gui/util/VGuiConstants.java b/src/main/java/net/vulkanmod/config/gui/util/VGuiConstants.java index 4e3187f9e1..93fe7eccb1 100644 --- a/src/main/java/net/vulkanmod/config/gui/util/VGuiConstants.java +++ b/src/main/java/net/vulkanmod/config/gui/util/VGuiConstants.java @@ -6,7 +6,9 @@ public class VGuiConstants { public static final int COLOR_WHITE = ColorUtil.ARGB.pack(1f, 1f, 1f, 1f); public static final int COLOR_BLACK = ColorUtil.ARGB.pack(0f, 0f, 0f, 1f); public static final int COLOR_GRAY = ColorUtil.ARGB.pack(0.6f, 0.6f, 0.6f, 1f); - public static final int COLOR_RED = ColorUtil.ARGB.pack(0.4f, 0.05f, 0.05f, 0.8f); + // Name kept so every user of it follows the theme: it is the teal theme colour now (same as Riftoptimizer's accent). + public static final int COLOR_RED = ColorUtil.ARGB.pack(0.35f, 0.8f, 0.72f, 0.8f); + public static final int COLOR_ACCENT = ColorUtil.ARGB.pack(0.58f, 0.89f, 0.83f, 1f); public static final int PAGE_BUTTON_WIDTH = 100; public static final int WIDGET_HEIGHT = 20; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java index a1168fb0a2..2824cbf218 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java @@ -7,6 +7,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; import net.vulkanmod.config.gui.render.GuiRenderer; +import net.vulkanmod.config.gui.util.VGuiConstants; import net.vulkanmod.config.option.RangeOption; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.glfw.GLFW; @@ -31,9 +32,9 @@ protected void renderControls(double mouseX, double mouseY) { int y0 = (int) (this.y + this.height * 0.5f - 1.0f); int y1 = (int) (y0 + 2.0f); GuiRenderer.fill(this.controlX, y0, this.controlX + this.controlWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.1f)); - GuiRenderer.fill(this.controlX, y0, valueX - halfWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f)); + GuiRenderer.fill(this.controlX, y0, valueX - halfWidth, y1, ColorUtil.ARGB.multiplyAlpha(VGuiConstants.COLOR_ACCENT, 0.6f)); - int color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f); + int color = VGuiConstants.COLOR_ACCENT; GuiRenderer.renderBorder(valueX - halfWidth, y0 - halfHeight, valueX + halfWidth, y1 + halfHeight, 1, color); } else { @@ -42,7 +43,7 @@ protected void renderControls(double mouseX, double mouseY) { GuiRenderer.fill(this.controlX, y0, this.controlX + this.controlWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f)); float alpha = this.active ? 0.8f : 0.3f; - GuiRenderer.fill(this.controlX, y0, valueX, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, alpha)); + GuiRenderer.fill(this.controlX, y0, valueX, y1, ColorUtil.ARGB.multiplyAlpha(VGuiConstants.COLOR_ACCENT, alpha)); } int color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java index 61966ed0c7..17c8829a27 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java @@ -4,6 +4,7 @@ import net.minecraft.client.gui.Font; import net.minecraft.network.chat.Component; import net.vulkanmod.config.gui.render.GuiRenderer; +import net.vulkanmod.config.gui.util.VGuiConstants; import net.vulkanmod.config.option.SwitchOption; import net.vulkanmod.vulkan.util.ColorUtil; @@ -29,10 +30,10 @@ protected void renderControls(double mouseX, double mouseY) { if (this.option.getNewValue()) { int x1 = x0 + halfWidth + 2; - color = ColorUtil.ARGB.pack(0.4f, 0.4f, 0.4f, 1.0f); + color = ColorUtil.ARGB.multiplyAlpha(VGuiConstants.COLOR_ACCENT, 0.45f); GuiRenderer.fillBox(x0 + 2, y0 + 2, x1 - (x0 + 2) - 1, h1, color); - color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 1.0f); + color = VGuiConstants.COLOR_ACCENT; GuiRenderer.fillBox(x1, y0 + 2, w1, h1, color); } else { color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.4f); diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index dfb88f51f4..db12e5851b 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -55,6 +55,12 @@ public class Renderer { private static boolean swapChainUpdate = false; + // Riftoptimizer-Vulkan (Android/Turnip workaround): the driver crashes inside vkQueueSubmit the first time + // a previously presented swapchain image is re-acquired and the acquire semaphore is waited on by the submit. + // So the image is acquired with a fence instead, which the host waits on, and the submit does not wait on + // an acquire semaphore. Disable with -Dvulkanmod.hostAcquire=false. + private static final boolean HOST_ACQUIRE = !"false".equalsIgnoreCase(System.getProperty("vulkanmod.hostAcquire")); + public static void initRenderer() { INSTANCE = new Renderer(); INSTANCE.init(); @@ -89,6 +95,7 @@ public static int getCurrentImage() { private ArrayList imageAvailableSemaphores; private ArrayList renderFinishedSemaphores; private ArrayList inFlightFences; + private ArrayList acquireFences; private List transferCbs; private Framebuffer boundFramebuffer; @@ -101,6 +108,9 @@ public static int getCurrentImage() { private boolean recordingCmds = false; int recursion = 0; + // Riftoptimizer-Vulkan debug: counts queue submissions for the [dbg] log lines + private static long dbgSubmitCount = 0; + MainPass mainPass; private final List onResizeCallbacks = new ObjectArrayList<>(); @@ -183,6 +193,7 @@ private void createSyncObjects() { imageAvailableSemaphores = new ArrayList<>(framesNum); inFlightFences = new ArrayList<>(framesNum); + acquireFences = new ArrayList<>(framesNum); try (MemoryStack stack = stackPush()) { VkSemaphoreCreateInfo semaphoreInfo = VkSemaphoreCreateInfo.calloc(stack); @@ -192,20 +203,27 @@ private void createSyncObjects() { fenceInfo.sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); fenceInfo.flags(VK_FENCE_CREATE_SIGNALED_BIT); + // Acquire fences start unsignaled: they are signaled by vkAcquireNextImageKHR + VkFenceCreateInfo acquireFenceInfo = VkFenceCreateInfo.calloc(stack); + acquireFenceInfo.sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); + LongBuffer pImageAvailableSemaphore = stack.mallocLong(1); LongBuffer pRenderFinishedSemaphore = stack.mallocLong(1); LongBuffer pFence = stack.mallocLong(1); + LongBuffer pAcquireFence = stack.mallocLong(1); for (int i = 0; i < framesNum; i++) { if (vkCreateSemaphore(device, semaphoreInfo, null, pImageAvailableSemaphore) != VK_SUCCESS - || vkCreateFence(device, fenceInfo, null, pFence) != VK_SUCCESS) { + || vkCreateFence(device, fenceInfo, null, pFence) != VK_SUCCESS + || vkCreateFence(device, acquireFenceInfo, null, pAcquireFence) != VK_SUCCESS) { throw new RuntimeException("Failed to create synchronization objects for the frame: " + i); } imageAvailableSemaphores.add(pImageAvailableSemaphore.get(0)); inFlightFences.add(pFence.get(0)); + acquireFences.add(pAcquireFence.get(0)); } for (int i = 0; i < swapChain.getImagesNum(); ++i) { @@ -271,9 +289,23 @@ public void beginFrame() { if (swapChain.hasImages()) { IntBuffer pImageIndex = stack.mallocInt(1); long semaphore = imageAvailableSemaphores.get(currentFrame); - - int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, + long acquireFence = acquireFences.get(currentFrame); + + int vkResult; + if (HOST_ACQUIRE) { + vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, + VK_NULL_HANDLE, acquireFence, pImageIndex); + + // The fence is only signaled when the acquire succeeded + if (vkResult == VK_SUCCESS || vkResult == VK_SUBOPTIMAL_KHR) { + vkWaitForFences(device, acquireFence, true, VUtil.UINT64_MAX); + vkResetFences(device, acquireFence); + } + } + else { + vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, semaphore, VK_NULL_HANDLE, pImageIndex); + } if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) { swapChainUpdate = true; @@ -336,6 +368,45 @@ public void endFrame() { p.push("Post_rendering"); } + // Riftoptimizer-Vulkan debug: log everything handed to vkQueueSubmit right before the call, + // so that the last [dbg] line in latestlog.txt shows what was submitted when the driver crashes. + private void dbgLogSubmit(String where, VkSubmitInfo info, long fence) { + try { + StringBuilder sb = new StringBuilder(); + sb.append("[dbg] ").append(where).append(" #").append(++dbgSubmitCount) + .append(" hostAcquire=").append(HOST_ACQUIRE) + .append(" frame=").append(currentFrame) + .append(" img=").append(imageIndex) + .append(" acquired=").append(swapChain.isAcquired()) + .append(" cb=0x").append(Long.toHexString(currentCmdBuffer.address())) + .append(" fence=0x").append(Long.toHexString(fence)); + + sb.append(" waits=["); + int waitCount = info.waitSemaphoreCount(); + LongBuffer waits = info.pWaitSemaphores(); + for (int i = 0; waits != null && i < waitCount; i++) { + if (i > 0) sb.append(','); + sb.append("0x").append(Long.toHexString(waits.get(i))); + } + sb.append("]"); + + sb.append(" signals=["); + int signalCount = info.signalSemaphoreCount(); + LongBuffer signals = info.pSignalSemaphores(); + for (int i = 0; signals != null && i < signalCount; i++) { + if (i > 0) sb.append(','); + sb.append("0x").append(Long.toHexString(signals.get(i))); + } + sb.append("]"); + + sb.append(" cbCount=").append(info.commandBufferCount()); + + Initializer.LOGGER.info(sb.toString()); + } catch (Throwable t) { + Initializer.LOGGER.info("[dbg] log failed: " + t); + } + } + private void submitFrame() { try (MemoryStack stack = stackPush()) { int vkResult; @@ -348,8 +419,10 @@ private void submitFrame() { int totalWaitSemaphores = waitSemaphoreCount; // Swapchain has an acquired image, - // the corresponding acquire operation has to be waited before running this command buffer - if (swapChain.isAcquired()) { + // the corresponding acquire operation has to be waited before running this command buffer. + // With HOST_ACQUIRE the host has already waited for it (acquire fence), so no semaphore wait. + boolean waitAcquireSemaphore = swapChain.isAcquired() && !HOST_ACQUIRE; + if (waitAcquireSemaphore) { totalWaitSemaphores += 1; } @@ -362,7 +435,7 @@ private void submitFrame() { waitDstStageMask.put(i, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); } - if (swapChain.isAcquired()) { + if (waitAcquireSemaphore) { waitSemaphores.put(totalWaitSemaphores - 1, imageAvailableSemaphores.get(currentFrame)); waitDstStageMask.put(totalWaitSemaphores - 1, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); } @@ -381,6 +454,8 @@ private void submitFrame() { vkResetFences(device, inFlightFences.get(currentFrame)); + dbgLogSubmit("submitFrame", submitInfo, inFlightFences.get(currentFrame)); + if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().vkQueue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult))); @@ -457,6 +532,9 @@ public void flushCmds() { waitFences(); vkResetFences(device, inFlightFences.get(currentFrame)); + + dbgLogSubmit("flushCmds", submitInfo, inFlightFences.get(currentFrame)); + if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().vkQueue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult))); @@ -550,6 +628,11 @@ private void resetDescriptors() { } void waitForSwapChain() { + // With HOST_ACQUIRE the acquire has already been waited on the host and the + // acquire semaphore is never signaled, so there is nothing to wait for here. + if (HOST_ACQUIRE) + return; + vkResetFences(device, inFlightFences.get(currentFrame)); // constexpr VkPipelineStageFlags t=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; @@ -620,6 +703,10 @@ private void destroySyncObjects() { for (int i = 0; i < framesNum; ++i) { vkDestroyFence(device, inFlightFences.get(i), null); vkDestroySemaphore(device, imageAvailableSemaphores.get(i), null); + + if (acquireFences != null && i < acquireFences.size()) { + vkDestroyFence(device, acquireFences.get(i), null); + } } for (int i = 0; i < swapChain.getImagesNum(); ++i) { diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 985e84072d..be31e1e86d 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -48,7 +48,11 @@ public class Vulkan { public static final boolean ENABLE_VALIDATION_LAYERS = false; // public static final boolean ENABLE_VALIDATION_LAYERS = true; - public static final boolean DYNAMIC_RENDERING = true; + // Riftoptimizer-Vulkan: decided at runtime in DeviceManager.createLogicalDevice(). + // true -> VK_KHR_dynamic_rendering (desktop GPUs, modern mobile drivers) + // false -> legacy VkRenderPass/VkFramebuffer path (older mobile GPUs e.g. Adreno 6xx on Vulkan 1.1) + // Can be forced to legacy with -Dvulkanmod.legacyRenderPass=true + public static boolean DYNAMIC_RENDERING = true; public static final Set VALIDATION_LAYERS; @@ -64,8 +68,10 @@ public class Vulkan { } } + // Only the swapchain is strictly required. dynamic_rendering and synchronization2 + // are enabled opportunistically in DeviceManager when the device exposes them. public static final Set REQUIRED_DEVICE_EXTENSIONS = Set.of( - "VK_KHR_dynamic_rendering", "VK_KHR_synchronization2", "VK_KHR_swapchain" + "VK_KHR_swapchain" ); public static long window; @@ -496,4 +502,3 @@ public static void popDebugSection(VkCommandBuffer commandBuffer) { } } } - diff --git a/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java b/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java index 9e500fea69..34d2892dc4 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java +++ b/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java @@ -204,6 +204,15 @@ public static void createLogicalDevice() { createInfo.pNext(deviceVulkan11Features); createInfo.pNext(deviceVulkan12Features); + // Riftoptimizer-Vulkan: pick the render path at runtime. + // Devices without VK_KHR_dynamic_rendering (e.g. many Adreno 6xx drivers, Vulkan 1.1) + // fall back to the legacy VkRenderPass/VkFramebuffer path. + boolean legacyForced = Boolean.getBoolean("vulkanmod.legacyRenderPass"); + Vulkan.DYNAMIC_RENDERING = !legacyForced && device.hasExtension("VK_KHR_dynamic_rendering"); + Initializer.LOGGER.info("Render path: {} on {} (Vulkan {})", + Vulkan.DYNAMIC_RENDERING ? "dynamic rendering" : "legacy render pass", + device.deviceName, device.vkVersion); + if (Vulkan.DYNAMIC_RENDERING) { VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamicRenderingFeaturesKHR = VkPhysicalDeviceDynamicRenderingFeaturesKHR.calloc(stack); dynamicRenderingFeaturesKHR.sType$Default(); @@ -214,6 +223,14 @@ public static void createLogicalDevice() { HashSet enabledExtensions = new HashSet<>(Vulkan.REQUIRED_DEVICE_EXTENSIONS); + if (Vulkan.DYNAMIC_RENDERING) { + enabledExtensions.add("VK_KHR_dynamic_rendering"); + } + + if (device.hasExtension("VK_KHR_synchronization2")) { + enabledExtensions.add("VK_KHR_synchronization2"); + } + if (device.hasExtension("VK_KHR_portability_subset")) { enabledExtensions.add("VK_KHR_portability_subset"); } @@ -369,6 +386,10 @@ public static String getAvailableDevicesInfo() { } else { stringBuilder.append("Unsupported extension: %s\n".formatted(unsupportedExtensions)); } + + stringBuilder.append("\t\tdynamic_rendering: %s, synchronization2: %s\n".formatted( + device.hasExtension("VK_KHR_dynamic_rendering"), + device.hasExtension("VK_KHR_synchronization2"))); } return stringBuilder.toString(); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SpirvCompiler.java b/src/main/java/net/vulkanmod/vulkan/shader/SpirvCompiler.java index 03a6dab946..02e10fcfb1 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SpirvCompiler.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SpirvCompiler.java @@ -7,6 +7,7 @@ import org.lwjgl.util.shaderc.ShadercIncludeResolveI; import org.lwjgl.util.shaderc.ShadercIncludeResult; import org.lwjgl.util.shaderc.ShadercIncludeResultReleaseI; +import org.lwjgl.vulkan.VK10; import org.lwjgl.vulkan.VK12; import java.io.IOException; @@ -23,7 +24,7 @@ import static org.lwjgl.util.shaderc.Shaderc.*; public class SpirvCompiler { - private static final boolean DEBUG = true; + private static final boolean DEBUG = false; private static final boolean OPTIMIZATIONS = false; private static long compiler; @@ -59,7 +60,14 @@ private static void init() { if (DEBUG) shaderc_compile_options_set_generate_debug_info(options); - shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_2, VK12.VK_API_VERSION_1_2); + // Mobile drivers (Turnip/Adreno 6xx) often expose only Vulkan 1.0, which cannot consume the + // SPIR-V 1.5 that a Vulkan 1.2 target produces. Vulkan 1.0 env emits SPIR-V 1.0 which every + // driver accepts. Override with -Dvulkanmod.spirv=1.2 if a shader needs newer features. + if ("1.2".equals(System.getProperty("vulkanmod.spirv"))) { + shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_2, VK12.VK_API_VERSION_1_2); + } else { + shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_0, VK10.VK_API_VERSION_1_0); + } shaderc_compile_options_set_include_callbacks(options, SHADER_INCLUDER, SHADER_RELEASER, pUserData); Shaderc.shaderc_compile_options_set_auto_bind_uniforms(options, true); @@ -171,4 +179,4 @@ public void free() { } } -} \ No newline at end of file +}