diff --git a/.github/scripts/build-tracy-natives.sh b/.github/scripts/build-tracy-natives.sh new file mode 100755 index 000000000..e6ead7fdd --- /dev/null +++ b/.github/scripts/build-tracy-natives.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Builds the libTracyClient shared library for the tracy-client module. +set -euo pipefail + +TRACY_VERSION="${TRACY_VERSION:-v0.13.1}" +OUT_DIR="${OUT_DIR:-dist/tracy-natives}" +TRACY_REPO="https://github.com/wolfpld/tracy" + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +case "$(uname -s)" in + Darwin) PLAT_OS="macos" ;; + Linux) PLAT_OS="linux" ;; + *) PLAT_OS="windows" ;; +esac +case "$(uname -m)" in + arm64|aarch64) PLAT_ARCH="arm64" ;; + *) PLAT_ARCH="x64" ;; +esac +RES_DIR="${RES_DIR:-$REPO_ROOT/tracy-client/src/main/resources/natives/tracy/$PLAT_OS-$PLAT_ARCH}" + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +if [[ -n "${TRACY_SRC:-}" ]]; then + SRC_DIR="$WORK_DIR/tracy" + git clone --shared --no-checkout "$TRACY_SRC" "$SRC_DIR" + git -C "$SRC_DIR" checkout --detach "$TRACY_VERSION" +else + SRC_DIR="$WORK_DIR/tracy" + git clone --depth 1 --branch "$TRACY_VERSION" "$TRACY_REPO" "$SRC_DIR" +fi + +BUILD_DIR="$WORK_DIR/build" +export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-11.0}" + +cmake -S "$SRC_DIR" -B "$BUILD_DIR" \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_SHARED_LIBS=ON \ + -DTRACY_STATIC=OFF \ + -DTRACY_ENABLE=ON \ + -DTRACY_ON_DEMAND=ON \ + -DTRACY_DELAYED_INIT=ON \ + -DTRACY_MANUAL_LIFETIME=ON \ + -DTRACY_NO_SAMPLING=ON \ + -DTRACY_NO_SYSTEM_TRACING=ON \ + -DTRACY_NO_CRASH_HANDLER=ON \ + -DTRACY_LTO=OFF +cmake --build "$BUILD_DIR" --config Release --parallel + +mkdir -p "$OUT_DIR" +for NAME in libTracyClient.so libTracyClient.dylib TracyClient.dll; do + LIB="$(find "$BUILD_DIR" -name "$NAME" | head -1)" + if [[ -n "$LIB" ]]; then + cp -L "$LIB" "$OUT_DIR/$NAME" + cp "$SRC_DIR/LICENSE" "$OUT_DIR/LICENSE" + mkdir -p "$RES_DIR" + cp -L "$LIB" "$RES_DIR/$NAME" + cp "$SRC_DIR/LICENSE" "$RES_DIR/LICENSE" + echo "built: $OUT_DIR/$NAME ($TRACY_VERSION), staged: $RES_DIR/$NAME" + exit 0 + fi +done +echo "error: built library not found under $BUILD_DIR" >&2 +exit 1 diff --git a/.github/workflows/build-tracy-natives.yml b/.github/workflows/build-tracy-natives.yml new file mode 100644 index 000000000..e18992a16 --- /dev/null +++ b/.github/workflows/build-tracy-natives.yml @@ -0,0 +1,92 @@ +name: Build Tracy natives + +on: + push: + tags: + - "tracy-v*" + workflow_dispatch: + inputs: + tracy-version: + description: Tracy git tag to build + required: false + default: v0.13.1 + publish: + description: Publish angelica-tracy.jar to the GTNH maven + type: boolean + required: false + default: false + +jobs: + build: + strategy: + matrix: + include: + - os: ubuntu-22.04 + platform: linux-x64 + - os: windows-2025 + platform: windows-x64 + - os: macos-15-intel + platform: macos-x64 + - os: macos-15 + platform: macos-arm64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - name: Build libTracyClient + shell: bash + env: + RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }} + OUT_DIR: dist/tracy-natives + run: | + export TRACY_VERSION="${RAW_VERSION#tracy-}" + bash .github/scripts/build-tracy-natives.sh + - uses: actions/upload-artifact@v4 + with: + name: tracy-natives-${{ matrix.platform }} + path: dist/tracy-natives/* + if-no-files-found: error + + assemble: + needs: build + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Check tracy version matches the version catalog + shell: bash + env: + RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }} + run: | + ver="${RAW_VERSION#tracy-}" + grep -q "^tracy = \"${ver#v}\"$" gradle/libs.versions.toml \ + || { echo "libs.versions.toml tracy does not match $ver" >&2; exit 1; } + - uses: actions/download-artifact@v5 + with: + pattern: tracy-natives-* + path: staging + - name: Stage natives into tracy-client resources + shell: bash + run: | + for d in staging/tracy-natives-*; do + dest="tracy-client/src/main/resources/natives/tracy/${d#staging/tracy-natives-}" + mkdir -p "$dest" + cp "$d"/* "$dest/" + done + find tracy-client/src/main/resources/natives -type f + - name: Build angelica-tracy.jar + run: ./gradlew :tracy-client:distJar + - uses: actions/upload-artifact@v4 + with: + name: angelica-tracy + path: tracy-client/build/libs/angelica-tracy-*.jar + if-no-files-found: error + - name: Publish to GTNH maven + if: github.ref_type == 'tag' || inputs.publish + env: + MAVEN_USER: ${{ secrets.MAVEN_USER }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + run: ./gradlew :tracy-client:publish diff --git a/.gitignore b/.gitignore index 46cd1aa0e..90cf82006 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .gradle +.kotlin/ .settings /.idea/ /.vs/ @@ -38,3 +39,6 @@ addon.local.gradle.kts addon.late.local.gradle addon.late.local.gradle.kts local/ +tracy-client/src/main/resources/natives/ +dist/tracy-natives/ +*.tracy diff --git a/Justfile b/Justfile new file mode 100644 index 000000000..9dc6c429f --- /dev/null +++ b/Justfile @@ -0,0 +1,17 @@ +# Angelica dev commands + +# Build with headless display +build: + xvfb-run --server-args="-screen 0 1366x768x24" ./gradlew build + +# Run tests with headless display +test: + xvfb-run --server-args="-screen 0 1366x768x24" ./gradlew test + +# Build jar only (no tests) +jar: + ./gradlew jar + +# Clean build directory +clean: + ./gradlew clean diff --git a/build.gradle.kts b/build.gradle.kts index 21d374b2d..532fbbb92 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,33 +8,120 @@ plugins { tasks.withType().configureEach { logLevel.set("FATAL") } tasks.withType().configureEach { logLevel.set("FATAL") } +val lwjglDebug = false +val gpuHud = false +val renderdoc = false +val rgp = false -minecraft { - extraRunJvmArguments.add("-Dangelica.enableTestBlocks=true") - extraRunJvmArguments.add("-Dangelica.dumpClass=true") -// extraRunJvmArguments.add("-Dangelica.useVulkan=true") -// extraRunJvmArguments.add("-Dangelica.vulkanDebug=true") -// extraRunJvmArguments.add("-Dorg.lwjgl.util.Debug=true") +minecraft { + extraRunJvmArguments.add("-Dangelica.debug.testBlocks=true") + extraRunJvmArguments.add("-Dangelica.tracy=true") + extraRunJvmArguments.add("-Dangelica.sdlgpu.enable=true") + extraRunJvmArguments.add("-Dangelica.unmappedGL=fail") + extraRunJvmArguments.add("-Dorg.lwjgl.util.Debug=$lwjglDebug") + + extraRunJvmArguments.add("-Dsun.net.client.defaultConnectTimeout=5000") + extraRunJvmArguments.add("-Dsun.net.client.defaultReadTimeout=5000") + // TODO: Remove once GTNHGradle includes shaderc/spvc in the default lwjgl3Bindings list + lwjgl3Bindings.addAll("shaderc", "spvc") + lwjgl3Version = libs.versions.lwjgl3.get() // extraRunJvmArguments.addAll("-Dlegacy.debugClassLoadingSave=true") // extraRunJvmArguments.addAll("-Drfb.dumpLoadedClasses=true", "-Drfb.dumpLoadedClassesPerTransformer=true") - //extraRunJvmArguments.add("-Dangelica.redirectorLogspam=true") + //extraRunJvmArguments.add("-Dangelica.debug.redirectorLogspam=true") + } -tasks.test { - useJUnitPlatform() - testLogging { - events("passed", "skipped", "failed") - } - // On macOS ARM64, use an ARM64-compatible JVM for tests - val isMacOsArm64 = System.getProperty("os.name").lowercase().contains("mac") && System.getProperty("os.arch") == "aarch64" - javaLauncher = javaToolchains.launcherFor { - languageVersion = JavaLanguageVersion.of(8) - if (isMacOsArm64) { - vendor = JvmVendorSpec.AZUL +// Ensure flyby args are passed to the client +tasks.withType().matching { it.name.startsWith("runClient") }.configureEach { + for ((key, value) in System.getProperties()) { + val name = key.toString() + if (name.startsWith("angelica.flyby.")) { + jvmArgs("-D$name=$value") + } + } +} + +if (gpuHud) { + tasks.withType().matching { it.name.startsWith("runClient") }.configureEach { + if (org.gradle.internal.os.OperatingSystem.current().isMacOsX) { + environment("MTL_HUD_ENABLED", "1") + } else { + environment("MANGOHUD", "1") + environment("LD_PRELOAD", "/usr/\$LIB/mangohud/libMangoHud_shim.so") + } + } +} + + +configurations.all { + exclude(group = "com.github.GTNewHorizons", module = "Angelica") + resolutionStrategy.dependencySubstitution { + substitute(module("com.github.GTNewHorizons:lwjgl3ify")) + .using(module("com.github.GTNewHorizons:lwjgl3ify:${libs.versions.lwjgl3ify.get()}")) + } +} + +// lwjgl3ify pulls a pinned lwjgl 3.4.2 snapshot transitively from here. +repositories { + maven { + name = "Maven Central Snapshots" + url = uri("https://central.sonatype.com/repository/maven-snapshots/") + content { includeGroup("org.lwjgl") } + } +} + +val osName = System.getProperty("os.name").lowercase() +val isMacOs = org.gradle.internal.os.OperatingSystem.current().isMacOsX +val isMacOsArm64 = isMacOs && System.getProperty("os.arch") == "aarch64" + +tasks.withType().configureEach { + if (name.startsWith("runClient")) { + if (isMacOs) { + // SDL3 / Cocoa / Metal must initialize on the JVM main thread. + jvmArgs("-XstartOnFirstThread") + jvmArgs("-Dangelica.sdlgpu.encoderAssertions=" + if (lwjglDebug) "fatal" else "warn") + if (lwjglDebug) { + environment("METAL_DEVICE_WRAPPER_TYPE", "1") + environment("METAL_DEBUG_ERROR_MODE", "0") + environment("MTL_SHADER_VALIDATION", "1") + environment("MTL_SHADER_VALIDATION_REPORT_TO_STDERR", "1") + environment("MTL_DEBUG_LAYER", "1") + environment("MallocScribble", "1") + environment("MallocPreScribble", "1") + environment("MallocGuardEdges", "1") + environment("MallocStackLogging", "1") + environment("MallocStackLoggingNoCompact", "1") + } + } + } +} + +// Linux runClient: RenderDoc frame capture (F12) OR RADV RGP/SQTT capture. Mutually exclusive; RGP wins +tasks.withType().configureEach { + if (name.startsWith("runClient") && !isMacOs && !osName.contains("windows")) { + environment("WAYLAND_DISPLAY", "") + environment("XDG_SESSION_TYPE", "x11") + val rgpFrame = project.findProperty("rgpFrame") as String? + val rgpCapture = rgp || project.hasProperty("rgp") || rgpFrame != null + if (rgpCapture) { + environment("MESA_VK_TRACE", "rgp") + if (rgpFrame != null) { + environment("MESA_VK_TRACE_FRAME", rgpFrame) + doFirst { logger.lifecycle("RGP: capturing frame $rgpFrame -> /tmp/java_*.rgp") } + } else { + environment("MESA_VK_TRACE_TRIGGER", "/tmp/angelica_rgp.trigger") + doFirst { logger.lifecycle("RGP: touch /tmp/angelica_rgp.trigger (or press F1) to capture -> /tmp/java_*.rgp") } + } + } else if (renderdoc || project.hasProperty("renderdoc")) { + val renderdocLib = file(project.findProperty("renderdocLib") as String? ?: "${System.getProperty("user.home")}/Downloads/renderdoc_1.44/lib/librenderdoc.so") + if (renderdocLib.isFile) { + environment("LD_PRELOAD", renderdocLib.absolutePath) + doFirst { logger.lifecycle("RENDERDOC: LD_PRELOAD set, press F12 to capture") } + } else { + doFirst { logger.lifecycle("RENDERDOC: enabled but ${renderdocLib.absolutePath} not found; set -PrenderdocLib=") } + } } } - dependsOn(tasks.extractNatives2) - jvmArgs("-Djava.library.path=${tasks.extractNatives2.get().destinationFolder.asFile.get().path}") } tasks.processResources { @@ -57,6 +144,7 @@ val shadowImplementation: Configuration by configurations val downgradeEmbedOnlyForTest by tasks.registering(DowngradeFiles::class) { inputCollection = embedOnly + outputs.dir(temporaryDir) } val stripModuleInfoFromShadow by tasks.registering(Jar::class) { @@ -64,7 +152,7 @@ val stripModuleInfoFromShadow by tasks.registering(Jar::class) { from(shadowImplementation.map(::zipTree)) exclude("module-info.class") duplicatesStrategy = DuplicatesStrategy.EXCLUDE - archiveClassifier = "shadow-stripped" + archiveFileName = "shadow-stripped.jar" } val downgradeShadowImplForTest by tasks.registering(DowngradeFiles::class) { @@ -72,15 +160,74 @@ val downgradeShadowImplForTest by tasks.registering(DowngradeFiles::class) { outputs.dir(temporaryDir) } -tasks.test { - dependsOn(downgradeEmbedOnlyForTest, downgradeShadowImplForTest) - classpath = classpath - .minus(embedOnly) - .plus(files(downgradeEmbedOnlyForTest.map { it.outputCollection })) - .minus(shadowImplementation) - .plus(files({ fileTree(downgradeShadowImplForTest.get().temporaryDir) })) +val glsmTestFixtures: Configuration by configurations.creating { + isCanBeConsumed = false + isCanBeResolved = true + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR)) + } } +val downgradeGlsmTestFixturesForTest by tasks.registering(DowngradeFiles::class) { + inputCollection = glsmTestFixtures + outputs.dir(temporaryDir) +} + +fun downgraded(task: TaskProvider): FileCollection = files(task.map { it.outputMap.values }) + +fun Test.configureAngelicaJava8() { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(8) + if (isMacOsArm64) { + vendor = JvmVendorSpec.AZUL + } + } + dependsOn(tasks.extractNatives2) + jvmArgs("-Djava.library.path=${tasks.extractNatives2.get().destinationFolder.asFile.get().path}") + testLogging { events("passed", "skipped", "failed") } + + val swaps = mapOf( + embedOnly to downgradeEmbedOnlyForTest, + shadowImplementation to downgradeShadowImplForTest, + glsmTestFixtures to downgradeGlsmTestFixturesForTest, + ) + dependsOn(swaps.values) + for ((original, downgrade) in swaps) { + classpath = classpath.minus(original).plus(downgraded(downgrade)) + } +} + +tasks.test { + useJUnitPlatform { excludeTags = setOf("gl-core") } + configureAngelicaJava8() +} + +val downgradeRootMainClasses = tasks.named("downgradeMainClasses") +val downgradeRootTestClasses = tasks.named("downgradeTestClasses") + +val glCoreTest by tasks.registering(Test::class) { + description = "Runs the gl-core tests in their own JVM with a real GL context." + group = "verification" + useJUnitPlatform { includeTags = setOf("gl-core") } + + dependsOn(downgradeRootMainClasses, downgradeRootTestClasses) + val rawMain = sourceSets["main"].output.classesDirs + val rawTest = sourceSets["test"].output.classesDirs + val downgradedTest = downgraded(downgradeRootTestClasses) + + setTestClassesDirs(downgradedTest) + classpath = downgradedTest + .plus(downgraded(downgradeRootMainClasses)) + .plus(sourceSets["test"].runtimeClasspath.minus(rawMain).minus(rawTest)) + + configureAngelicaJava8() + mustRunAfter(tasks.test) +} + +tasks.test { finalizedBy(glCoreTest) } +tasks.check { dependsOn(glCoreTest) } + tasks.shadowJar { dependsOn(embedOnly) from(embedOnly.map(::zipTree)) @@ -89,13 +236,18 @@ tasks.shadowJar { mergeServiceFiles() minimize { + exclude(project(rootProject.path)) exclude(project(":glsm")) exclude(project(":lwjgl3-backend")) + exclude(project(":sdl-gpu")) + exclude(dependency("org.taumc:.*:.*")) + exclude(dependency("org.antlr:.*:.*")) } relocate("com.mitchej123", "com.mitchej123") relocate("org.embeddedt", "org.embeddedt") + relocate("com.gtnewhorizons.angelica.config", "com.gtnewhorizons.angelica.config") relocate("com.gtnewhorizons.angelica.glsm", "com.gtnewhorizons.angelica.glsm") relocate("com.gtnewhorizons.angelica.lwjgl3", "com.gtnewhorizons.angelica.lwjgl3") + relocate("com.gtnewhorizons.angelica.sdlgpu", "com.gtnewhorizons.angelica.sdlgpu") } - diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 000000000..81747e0fc --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + `kotlin-dsl` +} + +repositories { + gradlePluginPortal() + mavenCentral() +} + +// Re-export Gradle's generated typed catalog accessors so applied scripts (dependencies.gradle.kts) can use them. +dependencies { + implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) +} diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 000000000..0edc03776 --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,5 @@ +dependencyResolutionManagement { + versionCatalogs { + create("libs") { from(files("../gradle/libs.versions.toml")) } + } +} diff --git a/dependencies.gradle b/dependencies.gradle deleted file mode 100644 index f0996d729..000000000 --- a/dependencies.gradle +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Add your dependencies here. Supported configurations: - * - api("group:name:version:classifier"): if you use the types from this dependency in the public API of this mod - * Available at runtime and compiletime for mods depending on this mod - * - implementation("g:n:v:c"): if you need this for internal implementation details of the mod, but none of it is visible via the public API - * Available at runtime but not compiletime for mods depending on this mod - * - compileOnly("g:n:v:c"): if the mod you're building doesn't need this dependency during runtime at all, e.g. for optional mods - * Not available at all for mods depending on this mod, only visible at compiletime for this mod - * - compileOnlyApi("g:n:v:c"): like compileOnly, but also visible at compiletime for mods depending on this mod - * Available at compiletime but not runtime for mods depending on this mod - * - runtimeOnlyNonPublishable("g:n:v:c"): if you want to include a mod in this mod's runClient/runServer runs, but not publish it as a dependency - * Not available at all for mods depending on this mod, only visible at runtime for this mod - * - devOnlyNonPublishable("g:n:v:c"): a combination of runtimeOnlyNonPublishable and compileOnly for dependencies present at both compiletime and runtime, - * but not published as Maven dependencies - useful for RFG-deobfuscated dependencies or local testing - * - runtimeOnly("g:n:v:c"): if you don't need this at compile time, but want it to be present at runtime - * Available at runtime for mods depending on this mod - * - annotationProcessor("g:n:v:c"): mostly for java compiler plugins, if you know you need this, use it, otherwise don't worry - * - testCONFIG("g:n:v:c") - replace CONFIG by one of the above (except api), same as above but for the test sources instead of main - * - * - shadowImplementation("g:n:v:c"): effectively the same as API, but the dependency is included in your jar under a renamed package name - * Requires you to enable usesShadowedDependencies in gradle.properties - * - * - compile("g:n:v:c"): deprecated, replace with "api" (works like the old "compile") or "implementation" (can be more efficient) - * - * You can exclude transitive dependencies (dependencies of the chosen dependency) by appending { transitive = false } if needed, - * but use this sparingly as it can break using your mod as another mod's dependency if you're not careful. - * - * To depend on obfuscated jars you can use `devOnlyNonPublishable(rfg.deobf("dep:spec:1.2.3"))` to fetch an obfuscated jar from maven, - * or `devOnlyNonPublishable(rfg.deobf(project.files("libs/my-mod-jar.jar")))` to use a file. - * - * Gradle names for some of the configuration can be misleading, compileOnlyApi and runtimeOnly both get published as dependencies in Maven, but compileOnly does not. - * The buildscript adds runtimeOnlyNonPublishable to also have a runtime dependency that's not published. - * - * For more details, see https://docs.gradle.org/8.0.1/userguide/java_library_plugin.html#sec:java_library_configurations_graph - */ -configurations { - transformedMod // Mods that can be transformed - used for compiling angelica, but not necessary at runtime - transformedMod.canBeConsumed = false - transformedModCompileOnly - transformedModCompileOnly.canBeConsumed = false - - // Add the transformed mod dependencies to the compilation classpaths, but don't publish them in the Maven metadata - compileClasspath.extendsFrom(transformedMod, transformedModCompileOnly) - testCompileClasspath.extendsFrom(transformedMod, transformedModCompileOnly) - - // Can be enabled for testing if desired - // runtimeClasspath.extendsFrom(transformedMod) - // testRuntimeClasspath.extendsFrom(transformedMod) - - testRuntimeClasspath.exclude group: "com.github.GTNewHorizons", module: "lwjgl3ify" - - // Embed in JAR without relocation (compile only, shadowed into JAR) - embedOnly - embedOnly.canBeConsumed = false - embedOnly.canBeResolved = true - compileClasspath.extendsFrom(embedOnly) - testCompileClasspath.extendsFrom(embedOnly) - testRuntimeClasspath.extendsFrom(embedOnly) - -} - - -// Exclude self-reference from all configurations - prevents transitive Angelica deps from resolving against this project -configurations.all { - exclude group: "com.github.GTNewHorizons", module: "Angelica" -} - -dependencies { - compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.158:dev") - - compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.1.0") { transitive = false } -// runtimeOnlyNonPublishable("com.github.GTNewHorizons:lwjgl3ify:3.0.99") - - compileOnly("org.projectlombok:lombok:1.18.42") { transitive = false } - annotationProcessor("org.projectlombok:lombok:1.18.42") - - // Iris Shaders - compileOnly('org.jetbrains:annotations:26.0.2') - api("com.github.GTNewHorizons:GTNHLib:0.11.19:dev") - - shadowImplementation(project(":glsm")) { transitive = false } - shadowImplementation(project(":lwjgl3-backend")) { transitive = false } - shadowImplementation("net.minecraftforge:eventbus:7.0-beta.15") - - shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 - shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-33.g3ec381e") { - exclude module: "antlr4" // we only want to shadow the runtime module - } - shadowImplementation("org.antlr:antlr4-runtime:4.13.2") - compileOnly "org.apache.ant:ant:1.8.2" - - // Celeritas (transitive=false: deps provided by GTNHLib/runtime) - embedOnly("org.embeddedt.celeritas:celeritas-common:2.5.8-GTNH") { transitive = false } - embedOnly("org.embeddedt.celeritas:celeritas-lwjgl2-service:2.5.3-GTNH") { transitive = false } - - // Because who doesn't want NEI - devOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.8.35-GTNH:dev') - devOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev') - - // BQ Testing -// devOnlyNonPublishable("com.github.GTNewHorizons:BetterQuesting:3.8.74-GTNH:dev") - - - // Display List Testing - /* - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-749-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:ae2stuff:0.10.14-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:BuildCraft:7.1.54:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:IguanaTweaksTConstruct:2.7.0:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenBlocks:1.12.4-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenComputers:1.12.12-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:TinkersConstruct:1.14.12-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:ServerUtilities:2.2.13:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:ironchest:6.1.6:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:waila:1.9.7:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Botania:1.13.15-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Mobs-Info:0.5.10-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:Draconic-Evolution:1.5.18-GTNH:dev") - runtimeOnlyNonPublishable("com.github.GTNewHorizons:HoloInventory:2.5.8-GTNH:dev") - */ - - //devOnlyNonPublishable('com.github.GTNewHorizons:worldedit-gtnh:v0.0.9') - - // Notfine Deps - compileOnly("thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev") - devOnlyNonPublishable("com.github.GTNewHorizons:Baubles-Expanded:2.2.2-GTNH:dev") - compileOnly("com.github.GTNewHorizons:twilightforest:2.7.13:dev") { transitive = false } - compileOnly(rfg.deobf('curse.maven:witchery-69673:2234410')) - compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.14.6-GTNH:dev") { transitive = false } - compileOnly("com.github.GTNewHorizons:Natura:2.8.9:dev") - - compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.8.4:dev") - - compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.3:dev") { transitive = false } - - compileOnly("com.falsepattern:chunkapi-mc1.7.10:0.5.1:api") { transitive = false } - compileOnly("com.falsepattern:endlessids-mc1.7.10:1.5-beta0003:dev") { transitive = false } - - compileOnly(rfg.deobf("curse.maven:extrautils-225561:2264383")) - compileOnly(rfg.deobf("curse.maven:dynamiclights-227874:2337326")) - - compileOnly("curse.maven:minefactory-reloaded-66672:2277486") - - compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") - - compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5663_H261")) - - compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675")) - compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684")) - compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228")) - compileOnly("ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.49-GTNH:dev") - compileOnly(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612")) - - devOnlyNonPublishable("com.github.GTNewHorizons:CosmeticArmorReworked:1.0.3-GTNH:dev") - - // For testing alternative splash screens — https://github.com/MalTeeez/ModernSplash/releases - // devOnlyNonPublishable("com.github.MalTeeez:modernsplash:1.7.10-1.2.4:dev") - - // Hodgepodge - transformedMod("net.industrial-craft:industrialcraft-2:2.2.828-experimental:dev") - - // Better Crashes - compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.1-GTNH:dev") - - // Distant Horizons - compileOnly("maven.modrinth:DistantHorizonsApi:5.1.0") - - afterEvaluate { - dependencies { - testImplementation(platform('org.junit:junit-bom:5.14.1')) - testImplementation('org.junit.jupiter:junit-jupiter') - testImplementation("org.mockito:mockito-core:3.+") - testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209") - - testImplementation('org.junit.platform:junit-platform-engine') - testImplementation('org.junit.platform:junit-platform-reporting') - testImplementation('org.junit.platform:junit-platform-launcher') - - testImplementation('com.tngtech.archunit:archunit-junit5:1.4.1') - - testRuntimeOnly("it.unimi.dsi:fastutil:8.5.18") - testRuntimeOnly("org.joml:joml:1.10.8") - } - } - - compileOnly("mega:fluidlogged-mc1.7.10:0.1.2") - - compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.5-alpha:dev") { transitive = false } -} diff --git a/dependencies.gradle.kts b/dependencies.gradle.kts new file mode 100644 index 000000000..37566a181 --- /dev/null +++ b/dependencies.gradle.kts @@ -0,0 +1,209 @@ +/* + * Angelica's dependency declarations. Supported configurations: + * - api("group:name:version:classifier"): if you use the types from this dependency in the public API of this mod + * Available at runtime and compiletime for mods depending on this mod + * - implementation("g:n:v:c"): if you need this for internal implementation details of the mod, but none of it is visible via the public API + * Available at runtime but not compiletime for mods depending on this mod + * - compileOnly("g:n:v:c"): if the mod you're building doesn't need this dependency during runtime at all, e.g. for optional mods + * Not available at all for mods depending on this mod, only visible at compiletime for this mod + * - runtimeOnlyNonPublishable("g:n:v:c"): if you want to include a mod in this mod's runClient/runServer runs, but not publish it as a dependency + * - devOnlyNonPublishable("g:n:v:c"): a combination of runtimeOnlyNonPublishable and compileOnly, not published as a Maven dependency + * - shadowImplementation("g:n:v:c"): like api, but included in your jar under a renamed package name + * - embedOnly("g:n:v:c"): embedded in the jar without relocation + * + * Versions come from gradle/libs.versions.toml. Mod coordinates stay literal: nearly all carry a + * :dev classifier, which a version catalog cannot express, and curse/modrinth "versions" are file ids. + * + * To depend on obfuscated jars use `rfg.deobf("dep:spec:1.2.3")`. + */ +import com.gtnewhorizons.retrofuturagradle.modutils.ModUtils +import org.gradle.accessors.dm.LibrariesForLibs +import org.gradle.kotlin.dsl.DependencyHandlerScope + +val libs = the() +val rfg = (dependencies as ExtensionAware).extensions.getByType() + +val api = configurations["api"] +val compileOnly = configurations["compileOnly"] +val annotationProcessor = configurations["annotationProcessor"] +val shadowImplementation = configurations["shadowImplementation"] +val runtimeOnlyNonPublishable = configurations["runtimeOnlyNonPublishable"] +val devOnlyNonPublishable = configurations["devOnlyNonPublishable"] + +// Mods that can be transformed - used for compiling angelica, but not necessary at runtime +val transformedMod by configurations.creating { isCanBeConsumed = false } +val transformedModCompileOnly by configurations.creating { isCanBeConsumed = false } + +// Embed in JAR without relocation (compile only, shadowed into JAR) +val embedOnly by configurations.creating { + isCanBeConsumed = false + isCanBeResolved = true +} + +// Add the transformed mod dependencies to the compilation classpaths, but don't publish them in the Maven metadata +configurations["compileClasspath"].extendsFrom(transformedMod, transformedModCompileOnly, embedOnly) +configurations["testCompileClasspath"].extendsFrom(transformedMod, transformedModCompileOnly, embedOnly) +configurations["testRuntimeClasspath"].extendsFrom(embedOnly) +configurations["testRuntimeClasspath"].exclude(group = "com.github.GTNewHorizons", module = "lwjgl3ify") + +// Prevents transitive Angelica deps from resolving against this project +configurations.configureEach { + exclude(group = "com.github.GTNewHorizons", module = "Angelica") +} + +DependencyHandlerScope.of(dependencies).apply { + compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev") + + runtimeOnlyNonPublishable(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612")) + + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-994-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ae2stuff:0.10.19-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:BetterLoadingScreen:1.7.9-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:BetterQuesting:3.8.72-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:BuildCraft:7.1.63:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Botania:1.13.32-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:LogisticsPipes:1.5.32-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenComputers:1.12.55-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Mobs-Info:0.5.18-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:IguanaTweaksTConstruct:2.7.10:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenBlocks:1.12.18-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Schematica:1.12.6-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:TinkersConstruct:1.14.93-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ServerUtilities:2.4.1:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ironchest:6.1.13:dev") + runtimeOnlyNonPublishable("ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.49-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:waila:1.19.30:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Draconic-Evolution:1.5.30-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:HoloInventory:2.5.15-GTNH:dev") + + runtimeOnlyNonPublishable("thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev") + + compileOnly(libs.retrofuturabootstrap) { isTransitive = false } + // runtimeOnlyNonPublishable(libs.lwjgl3ify) + + compileOnly(libs.lombok) { isTransitive = false } + annotationProcessor(libs.lombok) + + // Iris Shaders + compileOnly(libs.annotations) + api(libs.gtnhlib) { artifact { classifier = "dev" } } + + shadowImplementation(project(":glsm")) { isTransitive = false } + shadowImplementation(project(":lwjgl3-backend")) { isTransitive = false } + shadowImplementation(project(":sdl-gpu")) { isTransitive = false } + runtimeOnlyNonPublishable(project(":tracy-client")) { isTransitive = false } + shadowImplementation(libs.eventbus) + + shadowImplementation(libs.jcpp) // Apache 2.0 + shadowImplementation(libs.glsl.transformation.lib) { + exclude(module = "antlr4") // we only want to shadow the runtime module + } + shadowImplementation(libs.antlr4.runtime) + compileOnly(libs.ant) + + // Celeritas (isTransitive=false: deps provided by GTNHLib/runtime) + embedOnly(libs.celeritas.common) { isTransitive = false } + embedOnly(libs.celeritas.lwjgl2.service) { isTransitive = false } + + // Because who doesn't want NEI + devOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.109-GTNH:dev") + devOnlyNonPublishable("com.github.GTNewHorizons:CodeChickenCore:1.4.16:dev") + + // BQ Testing + // devOnlyNonPublishable("com.github.GTNewHorizons:BetterQuesting:3.8.74-GTNH:dev") + + // Display List Testing + /* + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-994-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ae2stuff:0.10.19-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:BuildCraft:7.1.61:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:IguanaTweaksTConstruct:2.7.10:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenBlocks:1.12.18-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:OpenComputers:1.12.47-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:TinkersConstruct:1.14.93-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ServerUtilities:2.4.1:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:ironchest:6.1.13:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:waila:1.19.30:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Botania:1.13.25-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Mobs-Info:0.5.18-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:Draconic-Evolution:1.5.27-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:HoloInventory:2.5.15-GTNH:dev") + */ + + //devOnlyNonPublishable("com.github.GTNewHorizons:worldedit-gtnh:v0.0.9") + + // Notfine Deps + compileOnly("thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev") + devOnlyNonPublishable("com.github.GTNewHorizons:Baubles-Expanded:2.2.21-GTNH:dev") + compileOnly("com.github.GTNewHorizons:twilightforest:2.7.36:dev") { isTransitive = false } + compileOnly(rfg.deobf("curse.maven:witchery-69673:2234410")) + compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.14.93-GTNH:dev") { isTransitive = false } + compileOnly("com.github.GTNewHorizons:Natura:2.8.19:dev") + + compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.8.20:dev") + + compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.3:dev") { isTransitive = false } + + compileOnly("com.falsepattern:chunkapi-mc1.7.10:0.5.1:api") { isTransitive = false } + compileOnly("com.falsepattern:endlessids-mc1.7.10:1.5-beta0003:dev") { isTransitive = false } + + compileOnly(rfg.deobf("curse.maven:extrautils-225561:2264383")) + compileOnly(rfg.deobf("curse.maven:dynamiclights-227874:2337326")) + + compileOnly("curse.maven:minefactory-reloaded-66672:2277486") + + compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.11:dev") + + compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5663_H261")) + + compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675")) + compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684")) + compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228")) + compileOnly("ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.49-GTNH:dev") + compileOnly(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612")) + + devOnlyNonPublishable("com.github.GTNewHorizons:CosmeticArmorReworked:1.0.6-GTNH:dev") + + // For testing alternative splash screens - https://github.com/MalTeeez/ModernSplash/releases + // devOnlyNonPublishable("com.github.MalTeeez:modernsplash:1.7.10-1.2.4:dev") + + // Hodgepodge + transformedMod("net.industrial-craft:industrialcraft-2:2.2.828-experimental:dev") + + // Better Crashes + compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.5-GTNH:dev") + + // Distant Horizons + compileOnly("maven.modrinth:DistantHorizonsApi:5.1.0") + + compileOnly("mega:fluidlogged-mc1.7.10:0.1.2") + + compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.5-alpha:dev") { isTransitive = false } +} + +afterEvaluate { + val glsmTestFixtures = configurations["glsmTestFixtures"] + val testImplementation = configurations["testImplementation"] + val testCompileOnly = configurations["testCompileOnly"] + val testRuntimeOnly = configurations["testRuntimeOnly"] + + DependencyHandlerScope.of(dependencies).apply { + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(libs.mockito.core) + testImplementation(libs.lwjgl2) + + testImplementation(libs.junit.platform.engine) + testImplementation(libs.junit.platform.reporting) + testImplementation(libs.junit.platform.launcher) + + testImplementation(libs.archunit.junit5) + + glsmTestFixtures(testFixtures(project(":glsm")) as ModuleDependency) { isTransitive = false } + testCompileOnly(testFixtures(project(":glsm"))) + + testRuntimeOnly(libs.fastutil) + testRuntimeOnly(libs.joml) + } +} diff --git a/glsm/build.gradle.kts b/glsm/build.gradle.kts index 742cdb87b..3049afd0f 100644 --- a/glsm/build.gradle.kts +++ b/glsm/build.gradle.kts @@ -2,6 +2,7 @@ import xyz.wagyourtail.jvmdg.gradle.task.files.DowngradeFiles plugins { `java-library` + `java-test-fixtures` `maven-publish` } @@ -9,6 +10,8 @@ apply(plugin = "xyz.wagyourtail.jvmdowngrader") version = rootProject.version +val lwjglNatives: String by extra + java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) withSourcesJar() @@ -20,7 +23,7 @@ val rfgObfAttr = Attribute.of("com.gtnewhorizons.retrofuturagradle.obfuscation", val rfgTransformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean::class.javaObjectType) configurations { - listOf("apiElements", "runtimeElements").forEach { name -> + listOf("apiElements", "runtimeElements", "testFixturesApiElements", "testFixturesRuntimeElements").forEach { name -> named(name) { attributes { attribute(rfgObfAttr, "mcp") @@ -31,7 +34,7 @@ configurations { } // Compile stubs: MC class signatures needed to resolve GTNHLib's type hierarchy. -// Not included in the published jar — real MC classes are on the classpath at runtime. +// Not included in the published jar - real MC classes are on the classpath at runtime. sourceSets { create("stubs") { java.srcDir("src/stubs/java") @@ -65,6 +68,16 @@ repositories { url = uri("https://maven.wagyourtail.xyz/releases") content { includeGroup("xyz.wagyourtail.jvmdowngrader") } } + maven { + name = "Sonatype Snapshots" + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } + maven { + name = "Maven Central Snapshots" + url = uri("https://central.sonatype.com/repository/maven-snapshots/") + } + + mavenLocal() mavenCentral() mavenLocal() } @@ -74,42 +87,62 @@ dependencies { compileOnly(sourceSets["stubs"].output) // LWJGL - compileOnly("org.lwjgl.lwjgl:lwjgl:${property("lwjglVersion")}") - compileOnly("org.lwjgl.lwjgl:lwjgl_util:${property("lwjglVersion")}") + compileOnly(libs.lwjgl2) + compileOnly(libs.lwjgl2.util) - compileOnly("org.ow2.asm:asm-tree:5.0.3") + compileOnly(libs.asm.tree.compile) // Our Deps - api("com.github.GTNewHorizons:GTNHLib:${property("gtnhlibVersion")}:dev") - api("net.minecraftforge:eventbus:${property("eventbusVersion")}") + api(libs.gtnhlib) { artifact { classifier = "dev" } } + api(libs.eventbus) - compileOnly("org.embeddedt.celeritas:celeritas-common:${property("celeritasVersion")}") { isTransitive = false } - implementation("org.taumc:glsl-transformation-lib:${property("glslTransformLibVersion")}") { exclude(module = "antlr4") } - implementation("org.antlr:antlr4-runtime:${property("antlr4RuntimeVersion")}") - implementation("org.anarres:jcpp:${property("jcppVersion")}") + compileOnly(libs.celeritas.common) { isTransitive = false } + api(libs.glsl.transformation.lib) { exclude(module = "antlr4") } + api(libs.antlr4.runtime) + implementation(libs.jcpp) - compileOnly("org.projectlombok:lombok:${property("lombokVersion")}") { isTransitive = false } - annotationProcessor("org.projectlombok:lombok:${property("lombokVersion")}") - compileOnly("org.jetbrains:annotations:${property("jetbrainsAnnotationsVersion")}") - compileOnly("org.apache.logging.log4j:log4j-api:${property("log4jVersion")}") + // shaderc + SPIRV-Cross for the SpirvShaderTranslator (GLSL -> SPIR-V -> GLSL ES). + // TODO: Remove + compileOnly(libs.lwjgl3.shaderc) + compileOnly(libs.lwjgl3.spvc) + testImplementation(libs.lwjgl3.shaderc) + testImplementation(libs.lwjgl3.spvc) + // Host natives so the JNI wrapper can find libshaderc / libspirv-cross / liblwjgl. + testRuntimeOnly(libs.lwjgl3.shaderc) { artifact { classifier = lwjglNatives } } + testRuntimeOnly(libs.lwjgl3.spvc) { artifact { classifier = lwjglNatives } } + testRuntimeOnly(libs.lwjgl3) + testRuntimeOnly(libs.lwjgl3) { artifact { classifier = lwjglNatives } } + // @Lwjgl3Aware annotation + compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false } + + compileOnly(libs.lombok) { isTransitive = false } + annotationProcessor(libs.lombok) + compileOnly(libs.annotations) + compileOnly(libs.log4j.api) // Deps (normally from MC) - compile only, but needed at test runtime - compileOnly("com.google.guava:guava:${property("guavaVersion")}") - testRuntimeOnly("com.google.guava:guava:${property("guavaVersion")}") - testRuntimeOnly("it.unimi.dsi:fastutil:${property("fastutilVersion")}") - testRuntimeOnly("org.joml:joml:${property("jomlVersion")}") { isTransitive = false } + compileOnly(libs.guava) + testRuntimeOnly(libs.guava) + testRuntimeOnly(libs.fastutil) + testRuntimeOnly(libs.joml) { isTransitive = false } + + testFixturesCompileOnly(sourceSets["stubs"].output) + testFixturesApi(platform(libs.junit.bom)) + testFixturesApi(libs.junit.jupiter.api) + testFixturesApi(libs.lwjgl2) // Test testImplementation(sourceSets["stubs"].output) - testImplementation(platform("org.junit:junit-bom:${property("junitBomVersion")}")) - testImplementation("org.junit.jupiter:junit-jupiter") - testImplementation("org.ow2.asm:asm-tree:9.7") - testImplementation("org.lwjgl.lwjgl:lwjgl:${property("lwjglVersion")}") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") - testRuntimeOnly("org.apache.logging.log4j:log4j-core:${property("log4jVersion")}") - testRuntimeOnly("org.embeddedt.celeritas:celeritas-lwjgl2-service:${property("celeritasVersion")}") { isTransitive = false } - testRuntimeOnly("xyz.wagyourtail.jvmdowngrader:jvmdowngrader-java-api:${property("jvmDowngraderVersion")}:downgraded-8") - testRuntimeOnly("org.apache.commons:commons-lang3:${property("commonsLang3Version")}") + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(libs.asm.tree.test) + testImplementation(libs.lwjgl2) + testRuntimeOnly(libs.junit.platform.launcher) + testRuntimeOnly(libs.log4j.core) + testImplementation(libs.celeritas.common) { isTransitive = false } + testRuntimeOnly(libs.celeritas.lwjgl2.service) { isTransitive = false } + testRuntimeOnly(libs.jvmdowngrader.java.api) { artifact { classifier = "downgraded-8" } } + testRuntimeOnly(libs.commons.lang3) } val depsToDowngrade by configurations.creating { @@ -118,8 +151,8 @@ val depsToDowngrade by configurations.creating { } dependencies { - depsToDowngrade("net.minecraftforge:eventbus:${property("eventbusVersion")}") - depsToDowngrade("org.embeddedt.celeritas:celeritas-common:${property("celeritasVersion")}") { isTransitive = false } + depsToDowngrade(libs.eventbus) + depsToDowngrade(libs.celeritas.common) { isTransitive = false } } tasks.withType().configureEach { @@ -136,9 +169,18 @@ val downgradeDepsForTest by tasks.registering(DowngradeFiles::class) { val downgradeMainClasses by tasks.registering(DowngradeFiles::class) { inputCollection = sourceSets["main"].output.classesDirs.plus(sourceSets["stubs"].output.classesDirs) classpath = sourceSets["main"].compileClasspath + (sourceSets["main"].output.classesDirs.files + sourceSets["stubs"].output.classesDirs.files) + .forEach { outputs.dir(temporaryDir.resolve(it.name)) } dependsOn(tasks.named("classes"), tasks.named("stubsClasses")) } +val downgradeTestFixturesClasses by tasks.registering(DowngradeFiles::class) { + inputCollection = sourceSets["testFixtures"].output.classesDirs + classpath = sourceSets["testFixtures"].compileClasspath + sourceSets["testFixtures"].output.classesDirs.files.forEach { outputs.dir(temporaryDir.resolve(it.name)) } + dependsOn(tasks.named("testFixturesClasses")) +} + val downgradeTestClasses by tasks.registering(DowngradeFiles::class) { inputCollection = sourceSets["test"].output.classesDirs classpath = sourceSets["test"].compileClasspath @@ -161,7 +203,7 @@ fun Test.configureGlsmJava8() { } } - dependsOn(downgradeMainClasses, downgradeTestClasses, downgradeDepsForTest) + dependsOn(downgradeMainClasses, downgradeTestClasses, downgradeTestFixturesClasses, downgradeDepsForTest) val mainClassesDirs = sourceSets["main"].output.classesDirs .plus(sourceSets["stubs"].output.classesDirs) @@ -175,7 +217,9 @@ fun Test.configureGlsmJava8() { classpath = downgradedTest .plus(downgradedMain) .plus(downgradedDeps) - .plus(sourceSets["test"].runtimeClasspath.minus(mainClassesDirs).minus(testClassesDirs).minus(depsToDowngrade)) + .plus(files(downgradeTestFixturesClasses.map { it.outputCollection })) + .plus(sourceSets["test"].runtimeClasspath.minus(mainClassesDirs).minus(testClassesDirs) + .minus(sourceSets["testFixtures"].output.classesDirs).minus(depsToDowngrade)) val extractNatives = rootProject.tasks.named("extractNatives2") dependsOn(extractNatives) @@ -184,7 +228,10 @@ fun Test.configureGlsmJava8() { tasks.test { useJUnitPlatform { - excludeTags = GL_TASK_TAGS.values.toSet() + excludeTags = GL_TASK_TAGS.values.toSet() + "lwjgl3" + } + filter { + excludeTestsMatching("com.gtnewhorizons.angelica.glsm.shader.SpirvShaderTranslator*Test") } configureGlsmJava8() } @@ -225,6 +272,41 @@ val verifyTestsRan by tasks.registering { } tasks.check { dependsOn(verifyTestsRan) } +val spirvTest by tasks.registering(Test::class) { + description = "Runs SpirvShaderTranslator* tests against native shaderc + spvc on Java 21." + group = "verification" + useJUnitPlatform() + + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(21) + } + + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath.filter { file -> + // Strip the LWJGL2 jars - they collide with LWJGL3's sealed org.lwjgl package. + !file.name.startsWith("lwjgl-2.") && !file.name.startsWith("lwjgl_util-") && !file.name.startsWith("lwjgl-platform-") + } + + filter { + includeTestsMatching("com.gtnewhorizons.angelica.glsm.shader.SpirvShaderTranslator*Test") + includeTestsMatching("com.gtnewhorizons.angelica.glsm.ffp.FFPUniformBlockSpirvLayoutTest") + } + + // libshaderc.so / libspirv-cross.so are extracted by extractNatives3. + val extractNatives3 = rootProject.tasks.named("extractNatives3") + dependsOn(extractNatives3) + jvmArgs( + "-Djava.library.path=${extractNatives3.get().property("destinationFolder").let { (it as DirectoryProperty).asFile.get().path }}", + "--enable-native-access=ALL-UNNAMED" + ) + + testLogging { + showStandardStreams = true + } +} + +tasks.named("check") { dependsOn(spirvTest) } + publishing { publications { create("mavenJava") { diff --git a/glsm/gradle.properties b/glsm/gradle.properties deleted file mode 100644 index 3d5efea7a..000000000 --- a/glsm/gradle.properties +++ /dev/null @@ -1,16 +0,0 @@ -lwjglVersion = 2.9.4-nightly-20150209 -eventbusVersion = 7.0-beta.15 -celeritasVersion = 2.5.8-GTNH -lombokVersion = 1.18.42 -log4jVersion = 2.0-beta9 -guavaVersion = 18.0 -gtnhlibVersion = 0.11.19 -fastutilVersion = 8.5.18 -jomlVersion = 1.10.8 -glslTransformLibVersion = 0.2.0-26.g5ee7d96-GTNH -antlr4RuntimeVersion = 4.13.2 -jcppVersion = 1.4.14 -jetbrainsAnnotationsVersion = 26.0.2 -junitBomVersion = 5.14.1 -jvmDowngraderVersion = 1.3.5 -commonsLang3Version = 3.17.0 diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java new file mode 100644 index 000000000..661480153 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java @@ -0,0 +1,122 @@ +package com.gtnewhorizons.angelica.config; + +import net.minecraft.launchwrapper.Launch; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Locale; + +public final class SystemProperties { + + private static final Logger LOGGER = LogManager.getLogger("SystemProperties"); + + // Backend selection + public static final boolean USE_SDL_GPU = Boolean.getBoolean("angelica.sdlgpu.enable"); + public static final String GL_PROFILE = System.getProperty("angelica.glProfile", ""); + public static final boolean DISABLE_NVIDIA_WORKAROUND = Boolean.getBoolean("angelica.disableNvidiaWorkaround"); + + // Redirector + public static final UnmappedGLMode UNMAPPED_GL = parseEnum("angelica.unmappedGL", UnmappedGLMode.WARN, UnmappedGLMode.WARN, UnmappedGLMode.class); + public static final boolean FFP_WARN_ON_UNSUPPORTED = Boolean.getBoolean("angelica.ffp.warnOnUnsupported"); + + // SDL-GPU + public static final String KEY_SDL_GPU_DRIVER = "angelica.sdlgpu.driver"; + public static final String SDL_GPU_DRIVER = System.getProperty(KEY_SDL_GPU_DRIVER, ""); + public static final boolean SDL_GPU_DEBUG = Boolean.getBoolean("angelica.sdlgpu.debug"); + private static final SdlAssertionMode ENCODER_ASSERTIONS = parseEnum("angelica.sdlgpu.encoderAssertions", SdlAssertionMode.OFF, SdlAssertionMode.WARN, SdlAssertionMode.class); + public static final boolean SDL_ENCODER_ASSERTIONS = ENCODER_ASSERTIONS != SdlAssertionMode.OFF; + public static final boolean SDL_ENCODER_ASSERTIONS_FATAL = ENCODER_ASSERTIONS == SdlAssertionMode.FATAL; + public static final boolean SDL_VERIFY_STATE_SYNC = Boolean.getBoolean("angelica.sdlgpu.verifyStateSync"); + public static final boolean SDL_VERIFY_PER_FRAME_UNIFORM_BLOCK = Boolean.getBoolean("angelica.sdlgpu.verifyPerFrameUniformBlock"); + + // Tracy + public static final boolean TRACY = Boolean.getBoolean("angelica.tracy"); + public static final boolean TRACY_FINE_ZONES = Boolean.getBoolean("angelica.tracy.fineZones"); + public static final String TRACY_DIR = System.getProperty("angelica.tracy.dir", "angelica" + File.separator + "natives" + File.separator + "tracy"); + public static final int TRACY_MAX_SRC_LOCS = Math.max(16, Integer.getInteger("angelica.tracy.maxSrcLocs", 4096)); + + // Flyby + public static final String FLYBY_ROUTE = System.getProperty("angelica.flyby.route", ""); + public static final boolean FLYBY_WAIT_FOR_TRACY = Boolean.getBoolean("angelica.flyby.waitForTracy"); + public static final int FLYBY_WARMUP_TICKS = Integer.getInteger("angelica.flyby.warmupTicks", 400); + public static final int FLYBY_LENGTH = Integer.getInteger("angelica.flyby.length", 0); // Blocks for moving routes, ticks for stationary + public static final double FLYBY_SPEED = parseDouble("angelica.flyby.speed"); // Travel speed in blocks per tick + public static final boolean FLYBY_EXIT_WHEN_DONE = Boolean.getBoolean("angelica.flyby.exitWhenDone"); + + // Debug + public static final boolean LWJGL_DEBUG = Boolean.getBoolean("org.lwjgl.util.Debug"); + public static final boolean DEBUG_MARKERS = Boolean.getBoolean("angelica.debug.markers"); + public static final boolean DEBUG_F3_DETAIL = Boolean.getBoolean("angelica.debug.f3Detail"); + public static final boolean ENABLE_TEST_BLOCKS = Boolean.getBoolean("angelica.debug.testBlocks"); + public static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.debug.dumpClass"); + public static final boolean DUMP_SHADERS = Boolean.getBoolean("angelica.debug.dumpShaders") || isDeobf(); + public static final boolean REDIRECTOR_LOGSPAM = Boolean.getBoolean("angelica.debug.redirectorLogspam"); + public static final boolean DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debug.displayLists"); + public static final boolean LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.debug.displayLists.compilation"); + public static final boolean FORCE_ORPHAN_STREAMING = Boolean.getBoolean("angelica.debug.forceOrphanStreaming"); + public static final String SHADER_DUMP_ROOT = "angelica_dumps"; + + // Set by us, read by celeritas + public static final String KEY_CELERITAS_ENABLE_GL_DEBUG = "celeritas.enableGLDebug"; + + public static Path shaderDumpDir(String phase) { + return DUMP_SHADERS ? Paths.get(SHADER_DUMP_ROOT, phase) : null; + } + + public enum UnmappedGLMode { + OFF, + WARN, + FAIL, + STRICT; + + public boolean detects() { + return this != OFF; + } + + public boolean failsUnmapped() { + return this == FAIL || this == STRICT; + } + + public boolean failsAwareUnroutable() { + return this == STRICT; + } + } + + private enum SdlAssertionMode { + OFF, + WARN, + FATAL + } + + private static > E parseEnum(String key, E whenAbsent, E whenInvalid, Class type) { + final String raw = System.getProperty(key); + if (raw == null || raw.isEmpty()) return whenAbsent; + try { + return Enum.valueOf(type, raw.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + LOGGER.warn("Unrecognized value '{}' for -D{}; using {}. Valid values: {}", raw, key, whenInvalid, Arrays.toString(type.getEnumConstants())); + return whenInvalid; + } + } + + private static double parseDouble(String key) { + final String raw = System.getProperty(key); + if (raw == null || raw.isEmpty()) return 0.0D; + try { + return Double.parseDouble(raw); + } catch (NumberFormatException e) { + return 0.0D; + } + } + + private static boolean isDeobf() { + return Launch.blackboard != null && Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment")); + } + + private SystemProperties() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CaptureGate.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CaptureGate.java new file mode 100644 index 000000000..4626804f9 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CaptureGate.java @@ -0,0 +1,76 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +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.List; +import java.util.Locale; +import java.util.function.UnaryOperator; + +/** Decides whether instrumentation is worth emitting this frame. */ +public final class CaptureGate { + + private static final Logger LOGGER = LogManager.getLogger("Angelica"); + private static final boolean IS_LINUX = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("linux"); + private static final Path PROC_SELF_MAPS = Paths.get("/proc/self/maps"); + private static final String[] CAPTURE_ENV = { "RENDERDOC_CAPTURE_KEYPRESS", "ENABLE_VULKAN_RENDERDOC_CAPTURE", "RENDERDOC_HOOK_EGL" }; + private static final String[] CAPTURE_LIBS = { "renderdoc", "glxtrace", "egltrace", "apitrace" }; + public static final boolean FORCED = SystemProperties.DEBUG_MARKERS || SystemProperties.LWJGL_DEBUG; + public static final boolean TOOL_ATTACHED = detectCaptureTool(); + public static boolean markersThisFrame = true; + + private CaptureGate() {} + + public static void refresh() { + markersThisFrame = gateValue(FORCED, TOOL_ATTACHED, Tracy.isConnected()); + } + + static boolean gateValue(boolean forced, boolean toolAttached, boolean tracyConnected) { + return forced || toolAttached || tracyConnected; + } + + public static boolean enabledAtStartup() { + return FORCED || TOOL_ATTACHED; + } + + private static boolean detectCaptureTool() { + if (detectFromEnv(System::getenv)) { + LOGGER.info("Capture tool detected via environment; instrumentation enabled"); + return true; + } + if (!IS_LINUX) return false; + try { + if (detectFromMaps(Files.readAllLines(PROC_SELF_MAPS, StandardCharsets.ISO_8859_1))) { + LOGGER.info("Capture tool library detected in process map; instrumentation enabled"); + return true; + } + } catch (IOException e) { + LOGGER.warn("Could not read {} for capture tool detection: {}", PROC_SELF_MAPS, e.toString()); + } + return false; + } + + static boolean detectFromEnv(UnaryOperator env) { + for (String key : CAPTURE_ENV) { + if (env.apply(key) != null) return true; + } + return false; + } + + static boolean detectFromMaps(List mapLines) { + for (int i = 0; i < mapLines.size(); i++) { + final String line = mapLines.get(i).toLowerCase(Locale.ROOT); + for (String lib : CAPTURE_LIBS) { + if (line.contains(lib)) return true; + } + } + return false; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java index 2c1e376d2..e2bf1d0a1 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java @@ -1,8 +1,12 @@ package com.gtnewhorizons.angelica.glsm; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Usage; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import com.gtnewhorizons.angelica.glsm.shader.SpirvShaderTranslator; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; +import org.lwjgl.opengl.GL20; import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLParser; import org.taumc.glsl.ShaderParser; @@ -15,6 +19,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -33,12 +38,12 @@ import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACK *
    *
  • Matrix builtin replacement (gl_ModelViewMatrix, gl_ProjectionMatrix, etc.)
  • *
  • Vertex attribute replacement (gl_Vertex, gl_Color, gl_MultiTexCoord0/1, gl_Normal)
  • - *
  • gl_TexCoord[N] varying array → per-index in/out declarations
  • - *
  • Texture function renames (texture2D → texture, etc.)
  • - *
  • Fragment output handling (gl_FragColor → layout-qualified out declarations)
  • + *
  • gl_TexCoord[N] varying array -> per-index in/out declarations
  • + *
  • Texture function renames (texture2D -> texture, etc.)
  • + *
  • Fragment output handling (gl_FragColor -> layout-qualified out declarations)
  • *
  • Fog builtins (gl_Fog, gl_FogFragCoord)
  • - *
  • gl_FrontColor → local variable in vertex shaders
  • - *
  • shadow2D/shadow2DLod → texture/textureLod with vec4 wrapping
  • + *
  • gl_FrontColor -> local variable in vertex shaders
  • + *
  • shadow2D/shadow2DLod -> texture/textureLod with vec4 wrapping
  • *
  • Version upgrade to 330 core minimum
  • *
  • Reserved word pre-parse renaming (texture-as-variable, sample, etc.)
  • *
@@ -71,30 +76,59 @@ public class CompatShaderTransformer { "gl_NormalMatrix", "angelica_NormalMatrix" ); - private static final Path DUMP_DIR; private static final AtomicInteger dumpCounter = new AtomicInteger(0); - static { - DUMP_DIR = Boolean.parseBoolean(System.getProperty("angelica.dumpShaders", "false")) ? Paths.get("compat_shaders") : null; - } - - private static final int CACHE_SIZE = 32; + private static final int CACHE_SIZE = 256; private record CacheKey(String source, boolean isFragment) {} + private static final Map cache = Collections.synchronizedMap( - new LinkedHashMap<>(32, 0.75f, true) { + new LinkedHashMap<>(CACHE_SIZE, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > CACHE_SIZE; - } + return size() > CACHE_SIZE; + } + }); + + private record EsCacheKey(String source, int glShaderType, boolean isFragment) {} + private static final Map esCache = Collections.synchronizedMap( + new LinkedHashMap<>(CACHE_SIZE, 0.75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > CACHE_SIZE; + } }); public static void clearCache() { cache.clear(); + esCache.clear(); } - /** - * Transform a mod shader source for core profile compatibility. - */ + public static void prewarm(String source, int glShaderType, boolean isFragment) { + if (!RenderSystem.isGLES()) return; + final EsCacheKey key = new EsCacheKey(source, glShaderType, isFragment); + if (esCache.containsKey(key)) return; + transform(source, glShaderType, isFragment); + } + + /** Transform a mod shader for core profile; under GLES, also rewrites to ES 320. */ public static String transform(String source, boolean isFragment) { + return transform(source, isFragment ? GL20.GL_FRAGMENT_SHADER : GL20.GL_VERTEX_SHADER, isFragment); + } + + /** Variant carrying the exact GL shader type so the GLES re-emit dispatches to the right shaderc kind (geometry/tess/compute). */ + public static String transform(String source, int glShaderType, boolean isFragment) { + if (!source.isEmpty() && source.charAt(source.length() - 1) == '\0') { + source = source.substring(0, source.length() - 1); + } + final boolean gles = RenderSystem.isGLES(); + + if (gles) { + final EsCacheKey esKey = new EsCacheKey(source, glShaderType, isFragment); + final String esCached = esCache.get(esKey); + if (esCached != null) { + dumpShader(source, esCached, isFragment, needsTransformation(source)); + return esCached; + } + } + final boolean needsTransform = needsTransformation(source); String result; if (!needsTransform) { @@ -103,17 +137,27 @@ public class CompatShaderTransformer { final CacheKey key = new CacheKey(source, isFragment); final String cached = cache.get(key); if (cached != null) { - dumpShader(source, cached, isFragment, needsTransform); - return cached; + result = cached; + } else { + try { + result = transformInternal(source, isFragment); + cache.put(key, result); + } catch (Exception e) { + GLStateManager.LOGGER.warn("CompatShaderTransformer: AST transformation failed, falling back to version fixup only", e); + result = fixupVersion(source); + } } + } + if (gles) { + final String preGles = result; try { - result = transformInternal(source, isFragment); - cache.put(key, result); - } catch (Exception e) { - GLStateManager.LOGGER.warn("CompatShaderTransformer: AST transformation failed, falling back to version fixup only", e); - result = fixupVersion(source); + result = toGLES(result, glShaderType, isFragment); + } catch (RuntimeException e) { + dumpShader(source, preGles, isFragment, needsTransform); + throw e; } + esCache.put(new EsCacheKey(source, glShaderType, isFragment), result); } dumpShader(source, result, isFragment, needsTransform); @@ -144,24 +188,24 @@ public class CompatShaderTransformer { final int targetVersion = Math.max(declaredVersion, RENDER_BACKEND != null ? RENDER_BACKEND.getMinGLSLVersion() : 330); - // Pre-parse reserved word renaming — prevents ANTLR parse failures + // Pre-parse reserved word renaming - prevents ANTLR parse failures source = GlslTransformUtils.replaceTexture(source); source = GlslTransformUtils.renameReservedWords(source, targetVersion); - final ShaderParser.ParsedShader parsedShader = ShaderParser.parseShader(source); - final Transformer transformer = new Transformer(parsedShader.full()); + final GlslTransformUtils.QuietParse parsed = GlslTransformUtils.parseBothQuiet(source); + final Transformer transformer = new Transformer(parsed.full()); injectMatrixUniforms(transformer); transformFog(transformer, isFragment, source); - // gl_FrontLightModelProduct.sceneColor → angelica_SceneColor uniform + // gl_FrontLightModelProduct.sceneColor -> angelica_SceneColor uniform if (source.contains("gl_FrontLightModelProduct")) { transformer.injectVariable("uniform vec4 angelica_SceneColor;"); transformer.replaceExpression("gl_FrontLightModelProduct.sceneColor", "angelica_SceneColor"); } - // gl_LightSource[i] → struct + uniform array (both via injectFunction to keep struct before uniform) + // gl_LightSource[i] -> struct + uniform array (both via injectFunction to keep struct before uniform) if (source.contains("gl_LightSource")) { transformer.injectFunction("struct angelica_LightSourceParameters {" + "vec4 ambient;vec4 diffuse;vec4 specular;vec4 position;vec4 halfVector;" @@ -172,7 +216,7 @@ public class CompatShaderTransformer { transformer.rename("gl_LightSource", "angelica_LightSource"); } - // gl_FrontMaterial → struct + uniform (both via injectFunction to keep struct before uniform) + // gl_FrontMaterial -> struct + uniform (both via injectFunction to keep struct before uniform) if (source.contains("gl_FrontMaterial")) { transformer.injectFunction("struct angelica_MaterialParameters {" + "vec4 emission;vec4 ambient;vec4 diffuse;vec4 specular;float shininess;" @@ -181,7 +225,7 @@ public class CompatShaderTransformer { transformer.rename("gl_FrontMaterial", "angelica_FrontMaterial"); } - // gl_FrontColor (vertex) → gl_Color (fragment) varying chain + // gl_FrontColor (vertex) -> gl_Color (fragment) varying chain // Vertex side is unconditional: fragment may read gl_Color without vertex writing gl_FrontColor. // Uses angelica_ prefix to avoid colliding with user-declared varyings (e.g. "v_Color"). if (!isFragment) { @@ -199,7 +243,7 @@ public class CompatShaderTransformer { } } - // gl_TexCoord[N] varying array → per-index in/out declarations + // gl_TexCoord[N] varying array -> per-index in/out declarations final Set texCoordIndices = new HashSet<>(); transformer.renameArray("gl_TexCoord", "angelica_TexCoord", texCoordIndices); for (Integer i : texCoordIndices) { @@ -226,7 +270,7 @@ public class CompatShaderTransformer { transformer.renameAndWrapShadow("shadow2DLod", "textureLod"); final String versionDirective = "#version " + targetVersion + " core\n"; - final String extensions = VERSION_PATTERN.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); + final String extensions = VERSION_PATTERN.matcher(GlslTransformUtils.getFormattedShader(parsed.pre(), "")).replaceFirst("").trim(); // Preserve #define directives final StringBuilder defines = new StringBuilder(); @@ -242,7 +286,7 @@ public class CompatShaderTransformer { // Restore pre-parse renames String output = GlslTransformUtils.restoreReservedWords(result.toString()); - // Core profile: attribute → in, varying → out (vertex) / in (fragment) + // Core profile: attribute -> in, varying -> out (vertex) / in (fragment) output = fixupQualifiers(output, isFragment); return output; @@ -310,7 +354,8 @@ public class CompatShaderTransformer { transformer.injectVariable("uniform float angelica_FogEnd;"); transformer.injectVariable("uniform vec4 angelica_FogColor;"); transformer.injectFunction("struct angelica_FogParameters {vec4 color;float density;float start;float end;float scale;};"); - transformer.injectFunction("angelica_FogParameters angelica_Fog = angelica_FogParameters(" + transformer.injectFunction("angelica_FogParameters angelica_Fog;"); + transformer.prependMain("angelica_Fog = angelica_FogParameters(" + "angelica_FogColor, angelica_FogDensity, angelica_FogStart, angelica_FogEnd, " + "1.0 / (angelica_FogEnd - angelica_FogStart));"); } @@ -485,18 +530,19 @@ public class CompatShaderTransformer { } private static void dumpShader(String original, String transformed, boolean isFragment, boolean wasTransformed) { - if (DUMP_DIR == null) return; + final Path dir = SystemProperties.shaderDumpDir("compat"); + if (dir == null) return; final int id = dumpCounter.getAndIncrement(); final String suffix = isFragment ? ".frag.glsl" : ".vert.glsl"; try { - Files.createDirectories(DUMP_DIR); + Files.createDirectories(dir); // Capture caller info for identification final String caller = identifyCaller(); final String header = "// Compat shader dump #" + id + " (" + (isFragment ? "fragment" : "vertex") + ")" + "\n// Transformed: " + wasTransformed + "\n// Caller: " + caller + "\n\n"; - Files.writeString(DUMP_DIR.resolve(id + "_original" + suffix), header + original, StandardCharsets.UTF_8); - Files.writeString(DUMP_DIR.resolve(id + "_transformed" + suffix), header + transformed, StandardCharsets.UTF_8); + Files.writeString(dir.resolve(id + "_original" + suffix), header + original, StandardCharsets.UTF_8); + Files.writeString(dir.resolve(id + "_transformed" + suffix), header + transformed, StandardCharsets.UTF_8); } catch (IOException e) { GLStateManager.LOGGER.warn("Failed to dump compat shader: {}", e.getMessage()); } @@ -524,10 +570,10 @@ public class CompatShaderTransformer { return source; } - // Patterns for parsing fragment shader in declarations to generate passthrough vertex shaders - private static final Pattern FRAG_IN_COLOR = Pattern.compile("\\bin\\s+vec4\\s+angelica_FrontColor\\b"); - private static final Pattern FRAG_IN_TEXCOORD = Pattern.compile("\\bin\\s+vec4\\s+angelica_TexCoord(\\d+)\\b"); - private static final Pattern FRAG_IN_FOGCOORD = Pattern.compile("\\bin\\s+float\\s+angelica_FogFragCoord\\b"); + private static final String PRECISION_QUALIFIER = "(?:highp\\s+|mediump\\s+|lowp\\s+)?"; + private static final Pattern FRAG_IN_COLOR = Pattern.compile("\\bin\\s+" + PRECISION_QUALIFIER + "(vec[234])\\s+angelica_FrontColor\\b"); + private static final Pattern FRAG_IN_TEXCOORD = Pattern.compile("\\bin\\s+" + PRECISION_QUALIFIER + "(vec[234])\\s+angelica_TexCoord(\\d+)\\b"); + private static final Pattern FRAG_IN_FOGCOORD = Pattern.compile("\\bin\\s+" + PRECISION_QUALIFIER + "float\\s+angelica_FogFragCoord\\b"); /** * Generate a passthrough vertex shader for a fragment-only program. @@ -548,22 +594,26 @@ public class CompatShaderTransformer { final StringBuilder varyings = new StringBuilder(); final StringBuilder assignments = new StringBuilder(); - if (FRAG_IN_COLOR.matcher(fragmentSource).find()) { - sb.append("layout(location = 1) in vec4 a_Color;\n"); - varyings.append("out vec4 angelica_FrontColor;\n"); + final Matcher colorMatcher = FRAG_IN_COLOR.matcher(fragmentSource); + if (colorMatcher.find()) { + final String colorType = colorMatcher.group(1); + sb.append("layout(location = 1) in ").append(colorType).append(" a_Color;\n"); + varyings.append("out ").append(colorType).append(" angelica_FrontColor;\n"); assignments.append(" angelica_FrontColor = a_Color;\n"); } final Matcher texCoordMatcher = FRAG_IN_TEXCOORD.matcher(fragmentSource); - final Set texCoordIndices = new HashSet<>(); + final Map texCoordTypes = new HashMap<>(); while (texCoordMatcher.find()) { - texCoordIndices.add(Integer.parseInt(texCoordMatcher.group(1))); + texCoordTypes.putIfAbsent(Integer.parseInt(texCoordMatcher.group(2)), texCoordMatcher.group(1)); } - for (int i : texCoordIndices) { + for (Map.Entry e : texCoordTypes.entrySet()) { + final int i = e.getKey(); + final String type = e.getValue(); // PRIMARY_UV=2, SECONDARY_UV=3. Only indices 0 and 1 are supported; higher indices collide at location 3. final int location = i == 0 ? 2 : 3; - sb.append("layout(location = ").append(location).append(") in vec4 a_TexCoord").append(i).append(";\n"); - varyings.append("out vec4 angelica_TexCoord").append(i).append(";\n"); + sb.append("layout(location = ").append(location).append(") in ").append(type).append(" a_TexCoord").append(i).append(";\n"); + varyings.append("out ").append(type).append(" angelica_TexCoord").append(i).append(";\n"); assignments.append(" angelica_TexCoord").append(i).append(" = a_TexCoord").append(i).append(";\n"); } @@ -581,6 +631,23 @@ public class CompatShaderTransformer { return sb.toString(); } + /** 330-core -> GLSL ES 320 via shaderc + SPIRV-Cross. Throws on shaderc failure. */ + public static String toGLES(String source, int glShaderType, boolean isFragment) { + final Matcher m = VERSION_PATTERN.matcher(source); + if (m.find() && "es".equalsIgnoreCase(m.group(2))) return source; + if (glShaderType == 0) throw new IllegalArgumentException("toGLES requires a valid GL shader type"); + final String translated = SpirvShaderTranslator.glslToGlslEs(source, glShaderType, "compat"); + if (translated == null) { + throw new IllegalStateException("SpirvShaderTranslator failed for shader kind 0x" + + Integer.toHexString(glShaderType) + "; see preceding shaderc error + run/client/angelica_dumps/compat/"); + } + return translated; + } + + public static String toGLES(String source, boolean isFragment) { + return toGLES(source, isFragment ? GL20.GL_FRAGMENT_SHADER : GL20.GL_VERTEX_SHADER, isFragment); + } + /** Ensure #version is at least 330 core, strip 'compatibility' profile. */ private static String fixupVersion(String source) { final Matcher m = VERSION_PATTERN.matcher(source); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java index 99fad7693..82f6ab6ca 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java @@ -7,6 +7,10 @@ import com.gtnewhorizons.angelica.glsm.states.LightModelState; import com.gtnewhorizons.angelica.glsm.states.LightState; import com.gtnewhorizons.angelica.glsm.states.MaterialState; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; @@ -173,10 +177,10 @@ public class CompatUniformManager { final int[] locs = pu.locs; // Matrix uniforms — skip if this program's storage already holds the current generation - final int mvGen = GLStateManager.mvGeneration; - final int mvLinearGen = GLStateManager.mvLinearGeneration; - final int projGen = GLStateManager.projGeneration; - final int texMatGen = GLStateManager.texMatrixGeneration; + final int mvGen = GLStateManager.getMvGeneration(); + final int mvLinearGen = GLStateManager.getMvLinearGeneration(); + final int projGen = GLStateManager.getProjGeneration(); + final int texMatGen = GLStateManager.getTexMatrixGeneration(); final boolean mvChanged = mvGen != pu.lastMvGen; final boolean mvLinearChanged = mvLinearGen != pu.lastMvLinearGen; final boolean projChanged = projGen != pu.lastProjGen; @@ -190,14 +194,14 @@ public class CompatUniformManager { } // Fragment-category uniforms (fog, alpha) — skip if generation unchanged - final int fragGen = GLStateManager.fragmentGeneration; + final int fragGen = GLStateManager.getFragmentGeneration(); if (fragGen != pu.lastFragmentGen) { pu.lastFragmentGen = fragGen; uploadFragmentUniforms(locs); } // Lighting-derived uniforms (scene color, light sources, material) - final int litGen = GLStateManager.lightingGeneration; + final int litGen = GLStateManager.getLightingGeneration(); if (litGen != pu.lastLightingGen) { pu.lastLightingGen = litGen; if (locs[LOC_SCENE_COLOR] != -1) uploadSceneColor(locs); @@ -207,7 +211,7 @@ public class CompatUniformManager { // Clip plane equations + enabled bool — uploaded when enable state or equations change if (locs[LOC_CLIP_PLANES] != -1 || locs[LOC_CLIP_PLANES_ENABLED] != -1) { - final int cpGen = GLStateManager.clipPlaneGeneration; + final int cpGen = GLStateManager.getClipPlaneGeneration(); if (cpGen != pu.lastClipPlaneGen) { pu.lastClipPlaneGen = cpGen; uploadClipPlanes(locs); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java index 256610d19..be7f6ae3f 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica.glsm; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizon.gtnhlib.client.model.NormalHelper; import com.gtnewhorizon.gtnhlib.client.renderer.CallbackTessellator; @@ -10,6 +12,8 @@ import com.gtnewhorizon.gtnhlib.client.renderer.tessellator.VertexTransformCallb import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VBOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; @@ -52,18 +56,15 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; */ @UtilityClass public class DisplayListManager { - // -Dangelica.debugDisplayLists: disable transform collapsing and draw merging - private static final boolean DEBUG_DISPLAY_LISTS; + private static final Tracy.ZoneId Z_GL_LIST_COMPILE = Tracy.zoneId("glListCompile", Tracy.COLOR_FFP); + private static final Tracy.ZoneId Z_GL_LIST_PLAYBACK = Tracy.zoneId("glListPlayback", Tracy.COLOR_FFP); - // -Dangelica.logDisplayListCompilation: log compiled display list commands - private static final boolean LOG_DISPLAY_LIST_COMPILATION; + // Tracy profiling counter + public static long listPlaybacks; static { - DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debugDisplayLists"); - - LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.logDisplayListCompilation"); - if (LOG_DISPLAY_LIST_COMPILATION) { - GLStateManager.LOGGER.warn("Display list compilation logging ENABLED (-Dangelica.logDisplayListCompilation=true)"); + if (SystemProperties.LOG_DISPLAY_LIST_COMPILATION) { + GLStateManager.LOGGER.warn("Display list compilation logging ENABLED (-Dangelica.debug.displayLists.compilation=true)"); } } @@ -460,7 +461,7 @@ public class DisplayListManager { currentRecorder.writeHint(target, mode); } - public static void recordFog(int pname, java.nio.FloatBuffer params) { + public static void recordFog(int pname, FloatBuffer params) { drawBarrier(); currentRecorder.writeFog(pname, params); } @@ -475,7 +476,7 @@ public class DisplayListManager { currentRecorder.writeLighti(light, pname, param); } - public static void recordLight(int light, int pname, java.nio.FloatBuffer params) { + public static void recordLight(int light, int pname, FloatBuffer params) { drawBarrier(); currentRecorder.writeLight(light, pname, params); } @@ -490,7 +491,7 @@ public class DisplayListManager { currentRecorder.writeLightModeli(pname, param); } - public static void recordLightModel(int pname, java.nio.FloatBuffer params) { + public static void recordLightModel(int pname, FloatBuffer params) { drawBarrier(); currentRecorder.writeLightModel(pname, params); } @@ -500,7 +501,7 @@ public class DisplayListManager { currentRecorder.writeMaterialf(face, pname, val); } - public static void recordMaterial(int face, int pname, java.nio.FloatBuffer params) { + public static void recordMaterial(int face, int pname, FloatBuffer params) { drawBarrier(); currentRecorder.writeMaterial(face, pname, params); } @@ -556,7 +557,7 @@ public class DisplayListManager { currentRecorder.writeDrawBuffers(count, buf); } - public static void recordDrawBuffers(int count, java.nio.IntBuffer bufs) { + public static void recordDrawBuffers(int count, IntBuffer bufs) { drawBarrier(); currentRecorder.writeDrawBuffers(count, bufs); } @@ -623,7 +624,7 @@ public class DisplayListManager { pendingTransformOps.add(String.format("glTranslatef(%.4f, %.4f, %.4f)", x, y, z)); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -636,7 +637,7 @@ public class DisplayListManager { pendingTransformOps.add(String.format("glScalef(%.4f, %.4f, %.4f)", x, y, z)); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -654,7 +655,7 @@ public class DisplayListManager { pendingTransformOps.add(String.format("glRotatef(%.4f, %.4f, %.4f, %.4f)", Math.toDegrees(rad), x, y, z)); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -676,7 +677,7 @@ public class DisplayListManager { pendingTransformOps.add("glMultMatrixf(...)"); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -694,7 +695,7 @@ public class DisplayListManager { pendingTransformOps.add(String.format("glOrtho(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -709,7 +710,7 @@ public class DisplayListManager { pendingTransformOps.add(String.format("glFrustum(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar)); } - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { flushMatrix(); } } @@ -780,10 +781,10 @@ public class DisplayListManager { currentRecorder = new CommandRecorder(); // Create command recorder accumulatedDraws = new ArrayList<>(8); // Fewer draws than commands typically transformCallback = new DisplayListCallback(); - compilationStackTrace = LOG_DISPLAY_LIST_COMPILATION ? Thread.currentThread().getStackTrace() : null; + compilationStackTrace = SystemProperties.LOG_DISPLAY_LIST_COMPILATION ? Thread.currentThread().getStackTrace() : null; // Initialize debug logging fields (only when logging enabled) - if (LOG_DISPLAY_LIST_COMPILATION) { + if (SystemProperties.LOG_DISPLAY_LIST_COMPILATION) { pendingTransformOps = new ArrayList<>(); multMatrixSources = new ArrayList<>(); drawRangeSources = new ArrayList<>(); @@ -804,9 +805,11 @@ public class DisplayListManager { GLStateManager.warnOnce("endlist-outside", "glEndList called outside of a display list!"); return; } + if (Tracy.ENABLED) Tracy.beginZone(Z_GL_LIST_COMPILE); try { finishCurrentList(); } finally { + if (Tracy.ENABLED) Tracy.endZone(); // Non-null here means finishCurrentList threw before transferring or releasing // ownership of the recorder. if (currentRecorder != null) { @@ -888,7 +891,7 @@ public class DisplayListManager { } // Log compilation details if enabled (before context restoration changes glListId) - if (LOG_DISPLAY_LIST_COMPILATION) { + if (SystemProperties.LOG_DISPLAY_LIST_COMPILATION) { logCompiledDisplayList(glListId, compiled, compilationStackTrace); } } @@ -989,7 +992,7 @@ public class DisplayListManager { tessellator, copyLast ); accumulatedDraws.add(pendingDraw); - if (DEBUG_DISPLAY_LISTS) { + if (SystemProperties.DEBUG_DISPLAY_LISTS) { drawBarrier(); } } @@ -1017,29 +1020,38 @@ public class DisplayListManager { } private static void executeDisplayList(int list) { + if (Tracy.ENABLED) { + listPlaybacks++; + Tracy.beginZone(Z_GL_LIST_PLAYBACK); + } final boolean locked = GLStateManager.acquireDrawLock(); try { - final CompiledDisplayList compiled = displayListCache.get(list); - if (compiled != null) { - compiled.render(list); - return; - } - - // Fall back to VBOManager or legacy display list - if (list < 0) { - // Negative IDs are VBOManager space (entity models, etc.) - final VertexBuffer vbo = VBOManager.get(list); - if (vbo != null) { - vbo.render(); - } - // Per OpenGL spec: if list is undefined, glCallList has no effect - } - // An uncached positive-ID list = no-op (per OpenGL spec) + executeDisplayListInner(list); } finally { if (locked) GLStateManager.releaseDrawLock(); + if (Tracy.ENABLED) Tracy.endZone(); } } + private static void executeDisplayListInner(int list) { + final CompiledDisplayList compiled = displayListCache.get(list); + if (compiled != null) { + compiled.render(list); + return; + } + + // Fall back to VBOManager or legacy display list + if (list < 0) { + // Negative IDs are VBOManager space (entity models, etc.) + final VertexBuffer vbo = VBOManager.get(list); + if (vbo != null) { + vbo.render(); + } + // Per OpenGL spec: if list is undefined, glCallList has no effect + } + // An uncached positive-ID list = no-op (per OpenGL spec) + } + /** * Delete display lists and free their VBO resources. */ diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java index 6c730719f..6f900a42e 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java @@ -76,29 +76,29 @@ public class Feature { */ private static void addTextureGenStates(Set> collection) { for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { - collection.add(GLStateManager.textures.getTexGenSStates(i)); - collection.add(GLStateManager.textures.getTexGenTStates(i)); - collection.add(GLStateManager.textures.getTexGenRStates(i)); - collection.add(GLStateManager.textures.getTexGenQStates(i)); + collection.add(GLStateManager.getTextures().getTexGenSStates(i)); + collection.add(GLStateManager.getTextures().getTexGenTStates(i)); + collection.add(GLStateManager.getTextures().getTexGenRStates(i)); + collection.add(GLStateManager.getTextures().getTexGenQStates(i)); } } static { attribToFeatures.put(GL11.GL_COLOR_BUFFER_BIT, ImmutableSet.of( - GLStateManager.alphaTest // GL_ALPHA_TEST enable bit - , GLStateManager.alphaState // Alpha test function and reference value - , GLStateManager.blendMode // GL_BLEND enable bit - , GLStateManager.blendState // Blending source/destination functions, equation, blend color - , GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP enable bit - , GLStateManager.ditherState // GL_DITHER enable bit - , GLStateManager.drawBuffer // GL_DRAW_BUFFER setting - , GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP enable bit - , GLStateManager.logicOpMode // Logic op function - , GLStateManager.colorMask // Color-mode and index-mode writemasks - , GLStateManager.clearColor // Color-mode and index-mode clear values + GLStateManager.getAlphaTest() + , GLStateManager.getAlphaState() + , GLStateManager.getBlendMode() + , GLStateManager.getBlendState() + , GLStateManager.getColorLogicOpState() + , GLStateManager.getDitherState() + , GLStateManager.getDrawBuffer() + , GLStateManager.getIndexLogicOpState() + , GLStateManager.getLogicOpMode() + , GLStateManager.getColorMask() + , GLStateManager.getClearColor() )); attribToFeatures.put(GL11.GL_CURRENT_BIT, ImmutableSet.of( - GLStateManager.color // Current RGBA color + GLStateManager.getColor() , ShaderManager.getNormalStack() // Current normal vector , ShaderManager.getTexCoordStack() // Current texture coordinates // Current color index @@ -110,78 +110,78 @@ public class Feature { // GL_EDGE_FLAG flag )); attribToFeatures.put(GL11.GL_DEPTH_BUFFER_BIT, ImmutableSet.of( - GLStateManager.depthTest // GL_DEPTH_TEST enable bit - , GLStateManager.depthState // Depth buffer test function + GLStateManager.getDepthTest() + , GLStateManager.getDepthState() // Depth buffer clear value // GL_DEPTH_WRITEMASK enable bit )); final HashSet> enableBits = new HashSet<>(ImmutableSet.of( - GLStateManager.alphaTest // GL_ALPHA_TEST flag - , GLStateManager.autoNormalState // GL_AUTO_NORMAL flag - , GLStateManager.blendMode // GL_BLEND flag - , GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP flag - , GLStateManager.colorMaterial // GL_COLOR_MATERIAL - , GLStateManager.cullState // GL_CULL_FACE flag - , GLStateManager.depthTest // GL_DEPTH_TEST flag - , GLStateManager.ditherState // GL_DITHER flag - , GLStateManager.fogMode // GL_FOG flag - , GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP flag - , GLStateManager.lightStates[0] // GL_LIGHT0 - , GLStateManager.lightStates[1] // GL_LIGHT1 - , GLStateManager.lightStates[2] // GL_LIGHT2 - , GLStateManager.lightStates[3] // GL_LIGHT3 - , GLStateManager.lightStates[4] // GL_LIGHT4 - , GLStateManager.lightStates[5] // GL_LIGHT5 - , GLStateManager.lightStates[6] // GL_LIGHT6 - , GLStateManager.lightStates[7] // GL_LIGHT7 - , GLStateManager.lightingState // GL_LIGHTING flag - , GLStateManager.lineSmoothState // GL_LINE_SMOOTH flag - , GLStateManager.lineStippleState // GL_LINE_STIPPLE flag - , GLStateManager.map1Color4State // GL_MAP1_COLOR_4 - , GLStateManager.map1IndexState // GL_MAP1_INDEX - , GLStateManager.map1NormalState // GL_MAP1_NORMAL - , GLStateManager.map1TextureCoord1State // GL_MAP1_TEXTURE_COORD_1 - , GLStateManager.map1TextureCoord2State // GL_MAP1_TEXTURE_COORD_2 - , GLStateManager.map1TextureCoord3State // GL_MAP1_TEXTURE_COORD_3 - , GLStateManager.map1TextureCoord4State // GL_MAP1_TEXTURE_COORD_4 - , GLStateManager.map1Vertex3State // GL_MAP1_VERTEX_3 - , GLStateManager.map1Vertex4State // GL_MAP1_VERTEX_4 - , GLStateManager.map2Color4State // GL_MAP2_COLOR_4 - , GLStateManager.map2IndexState // GL_MAP2_INDEX - , GLStateManager.map2NormalState // GL_MAP2_NORMAL - , GLStateManager.map2TextureCoord1State // GL_MAP2_TEXTURE_COORD_1 - , GLStateManager.map2TextureCoord2State // GL_MAP2_TEXTURE_COORD_2 - , GLStateManager.map2TextureCoord3State // GL_MAP2_TEXTURE_COORD_3 - , GLStateManager.map2TextureCoord4State // GL_MAP2_TEXTURE_COORD_4 - , GLStateManager.map2Vertex3State // GL_MAP2_VERTEX_3 - , GLStateManager.map2Vertex4State // GL_MAP2_VERTEX_4 - , GLStateManager.multisampleState // GL_MULTISAMPLE flag - , GLStateManager.normalizeState // GL_NORMALIZE flag - , GLStateManager.pointSmoothState // GL_POINT_SMOOTH flag - , GLStateManager.polygonOffsetPointState // GL_POLYGON_OFFSET_POINT flag - , GLStateManager.polygonOffsetLineState // GL_POLYGON_OFFSET_LINE flag - , GLStateManager.polygonOffsetFillState // GL_POLYGON_OFFSET_FILL flag - , GLStateManager.polygonSmoothState // GL_POLYGON_SMOOTH flag - , GLStateManager.polygonStippleState // GL_POLYGON_STIPPLE flag - , GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag - , GLStateManager.sampleAlphaToCoverageState // GL_SAMPLE_ALPHA_TO_COVERAGE flag - , GLStateManager.sampleAlphaToOneState // GL_SAMPLE_ALPHA_TO_ONE flag - , GLStateManager.sampleCoverageState // GL_SAMPLE_COVERAGE flag - , GLStateManager.scissorTest // GL_SCISSOR_TEST flag - , GLStateManager.stencilTest // GL_STENCIL_TEST flag + GLStateManager.getAlphaTest() + , GLStateManager.getAutoNormalState() + , GLStateManager.getBlendMode() + , GLStateManager.getColorLogicOpState() + , GLStateManager.getColorMaterial() + , GLStateManager.getCullState() + , GLStateManager.getDepthTest() + , GLStateManager.getDitherState() + , GLStateManager.getFogMode() + , GLStateManager.getIndexLogicOpState() + , GLStateManager.getLightStates()[0] // GL_LIGHT0 + , GLStateManager.getLightStates()[1] // GL_LIGHT1 + , GLStateManager.getLightStates()[2] // GL_LIGHT2 + , GLStateManager.getLightStates()[3] // GL_LIGHT3 + , GLStateManager.getLightStates()[4] // GL_LIGHT4 + , GLStateManager.getLightStates()[5] // GL_LIGHT5 + , GLStateManager.getLightStates()[6] // GL_LIGHT6 + , GLStateManager.getLightStates()[7] // GL_LIGHT7 + , GLStateManager.getLightingState() + , GLStateManager.getLineSmoothState() + , GLStateManager.getLineStippleState() + , GLStateManager.getMap1Color4State() + , GLStateManager.getMap1IndexState() + , GLStateManager.getMap1NormalState() + , GLStateManager.getMap1TextureCoord1State() + , GLStateManager.getMap1TextureCoord2State() + , GLStateManager.getMap1TextureCoord3State() + , GLStateManager.getMap1TextureCoord4State() + , GLStateManager.getMap1Vertex3State() + , GLStateManager.getMap1Vertex4State() + , GLStateManager.getMap2Color4State() + , GLStateManager.getMap2IndexState() + , GLStateManager.getMap2NormalState() + , GLStateManager.getMap2TextureCoord1State() + , GLStateManager.getMap2TextureCoord2State() + , GLStateManager.getMap2TextureCoord3State() + , GLStateManager.getMap2TextureCoord4State() + , GLStateManager.getMap2Vertex3State() + , GLStateManager.getMap2Vertex4State() + , GLStateManager.getMultisampleState() + , GLStateManager.getNormalizeState() + , GLStateManager.getPointSmoothState() + , GLStateManager.getPolygonOffsetPointState() + , GLStateManager.getPolygonOffsetLineState() + , GLStateManager.getPolygonOffsetFillState() + , GLStateManager.getPolygonSmoothState() + , GLStateManager.getPolygonStippleState() + , GLStateManager.getRescaleNormalState() + , GLStateManager.getSampleAlphaToCoverageState() + , GLStateManager.getSampleAlphaToOneState() + , GLStateManager.getSampleCoverageState() + , GLStateManager.getScissorTest() + , GLStateManager.getStencilTest() )); // Enable bits for the user-definable clipping planes - for(int i = 0; i < GLStateManager.clipPlaneStates.length; i++) { - enableBits.add(GLStateManager.clipPlaneStates[i]); + for(int i = 0; i < GLStateManager.getClipPlaneStates().length; i++) { + enableBits.add(GLStateManager.getClipPlaneStates()[i]); } // GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D flags for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { - enableBits.add(GLStateManager.textures.getTexture1DStates(i)); - enableBits.add(GLStateManager.textures.getTextureUnitStates(i)); - enableBits.add(GLStateManager.textures.getTexture3DStates(i)); + enableBits.add(GLStateManager.getTextures().getTexture1DStates(i)); + enableBits.add(GLStateManager.getTextures().getTextureUnitStates(i)); + enableBits.add(GLStateManager.getTextures().getTexture3DStates(i)); } // Flags GL_TEXTURE_GEN_x where x is S, T, R, or Q @@ -196,8 +196,8 @@ public class Feature { // GL_AUTO_NORMAL enable bit )); attribToFeatures.put(GL11.GL_FOG_BIT, ImmutableSet.of( - GLStateManager.fogMode // GL_FOG enable bit - , GLStateManager.fogState // Fog color + GLStateManager.getFogMode() + , GLStateManager.getFogState() // ^^ Fog density // ^^ Linear fog start // ^^ Linear fog end @@ -214,42 +214,42 @@ public class Feature { // GL_TEXTURE_COMPRESSION_HINT setting )); attribToFeatures.put(GL11.GL_LIGHTING_BIT, ImmutableSet.of( - GLStateManager.colorMaterial // GL_COLOR_MATERIAL enable bit - , GLStateManager.colorMaterialFace // GL_COLOR_MATERIAL_FACE value - , GLStateManager.colorMaterialParameter // Color material parameters that are tracking the current color - , GLStateManager.lightModel // Ambient scene color, GL_LIGHT_MODEL_LOCAL_VIEWER, GL_LIGHT_MODEL_TWO_SIDE - , GLStateManager.lightingState // GL_LIGHTING enable bit + GLStateManager.getColorMaterial() + , GLStateManager.getColorMaterialFace() + , GLStateManager.getColorMaterialParameter() + , GLStateManager.getLightModel() + , GLStateManager.getLightingState() // Enable bit for each light - , GLStateManager.lightStates[0] // GL_LIGHT0 - , GLStateManager.lightStates[1] // GL_LIGHT1 - , GLStateManager.lightStates[2] // GL_LIGHT2 - , GLStateManager.lightStates[3] // GL_LIGHT3 - , GLStateManager.lightStates[4] // GL_LIGHT4 - , GLStateManager.lightStates[5] // GL_LIGHT5 - , GLStateManager.lightStates[6] // GL_LIGHT6 - , GLStateManager.lightStates[7] // GL_LIGHT7 + , GLStateManager.getLightStates()[0] // GL_LIGHT0 + , GLStateManager.getLightStates()[1] // GL_LIGHT1 + , GLStateManager.getLightStates()[2] // GL_LIGHT2 + , GLStateManager.getLightStates()[3] // GL_LIGHT3 + , GLStateManager.getLightStates()[4] // GL_LIGHT4 + , GLStateManager.getLightStates()[5] // GL_LIGHT5 + , GLStateManager.getLightStates()[6] // GL_LIGHT6 + , GLStateManager.getLightStates()[7] // GL_LIGHT7 // Ambient, diffuse, and specular intensity for each light // Direction, position, exponent, and cutoff angle for each light // Constant, linear, and quadratic attenuation factors for each light - , GLStateManager.lightDataStates[0] - , GLStateManager.lightDataStates[1] - , GLStateManager.lightDataStates[2] - , GLStateManager.lightDataStates[3] - , GLStateManager.lightDataStates[4] - , GLStateManager.lightDataStates[5] - , GLStateManager.lightDataStates[6] - , GLStateManager.lightDataStates[7] + , GLStateManager.getLightDataStates()[0] + , GLStateManager.getLightDataStates()[1] + , GLStateManager.getLightDataStates()[2] + , GLStateManager.getLightDataStates()[3] + , GLStateManager.getLightDataStates()[4] + , GLStateManager.getLightDataStates()[5] + , GLStateManager.getLightDataStates()[6] + , GLStateManager.getLightDataStates()[7] // Ambient, diffuse, specular, and emissive color for each material // Ambient, diffuse, and specular color indices for each material // Specular exponent for each material - , GLStateManager.frontMaterial - , GLStateManager.backMaterial - , GLStateManager.shadeModelState // GL_SHADE_MODEL setting + , GLStateManager.getFrontMaterial() + , GLStateManager.getBackMaterial() + , GLStateManager.getShadeModelState() )); attribToFeatures.put(GL11.GL_LINE_BIT, ImmutableSet.of( - GLStateManager.lineSmoothState // GL_LINE_SMOOTH flag - , GLStateManager.lineStippleState // GL_LINE_STIPPLE enable bit - , GLStateManager.lineState // Line stipple pattern, repeat counter, and width + GLStateManager.getLineSmoothState() + , GLStateManager.getLineStippleState() + , GLStateManager.getLineState() )); attribToFeatures.put(GL11.GL_LIST_BIT, ImmutableSet.of( // GL_LIST_BASE setting @@ -274,31 +274,31 @@ public class Feature { // GL_READ_BUFFER setting )); attribToFeatures.put(GL11.GL_POINT_BIT, ImmutableSet.of( - GLStateManager.pointSmoothState // GL_POINT_SMOOTH flag - , GLStateManager.pointState // Point size + GLStateManager.getPointSmoothState() + , GLStateManager.getPointState() )); attribToFeatures.put(GL11.GL_POLYGON_BIT, ImmutableSet.of( - GLStateManager.cullState // GL_CULL_FACE enable bit - , GLStateManager.polygonSmoothState // GL_POLYGON_SMOOTH flag - , GLStateManager.polygonStippleState // GL_POLYGON_STIPPLE enable bit - , GLStateManager.polygonOffsetFillState // GL_POLYGON_OFFSET_FILL flag - , GLStateManager.polygonOffsetLineState // GL_POLYGON_OFFSET_LINE flag - , GLStateManager.polygonOffsetPointState // GL_POLYGON_OFFSET_POINT flag - , GLStateManager.polygonState // GL_CULL_FACE_MODE, GL_FRONT_FACE, GL_POLYGON_MODE, GL_POLYGON_OFFSET_FACTOR/UNITS + GLStateManager.getCullState() + , GLStateManager.getPolygonSmoothState() + , GLStateManager.getPolygonStippleState() + , GLStateManager.getPolygonOffsetFillState() + , GLStateManager.getPolygonOffsetLineState() + , GLStateManager.getPolygonOffsetPointState() + , GLStateManager.getPolygonState() )); attribToFeatures.put(GL11.GL_POLYGON_STIPPLE_BIT, ImmutableSet.of( // Polygon stipple pattern )); attribToFeatures.put(GL11.GL_SCISSOR_BIT, ImmutableSet.of( - GLStateManager.scissorTest // GL_SCISSOR_TEST enable bit + GLStateManager.getScissorTest() // Scissor box )); attribToFeatures.put(GL11.GL_STENCIL_BUFFER_BIT, ImmutableSet.of( - GLStateManager.stencilTest // GL_STENCIL_TEST enable bit - , GLStateManager.stencilState // Stencil function, ref, mask, ops, writemask, clear value + GLStateManager.getStencilTest() + , GLStateManager.getStencilState() )); final Set> textureAttribs = new HashSet<>(ImmutableSet.of( - GLStateManager.activeTextureUnit // Active texture unit + GLStateManager.getActiveTextureUnitStack() // GL_TEXTURE_ENV_MODE + GL_TEXTURE_ENV_COLOR — now per-unit in TexEnvState (added below) // Enable bits for the four texture coordinates @@ -315,8 +315,8 @@ public class Feature { // Current Texture Bindings - GL_TEXTURE_BINDING_2D + per-unit TexEnvState for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { - textureAttribs.add(GLStateManager.textures.getTextureUnitBindings(i)); - textureAttribs.add(GLStateManager.textures.getTexEnvState(i)); + textureAttribs.add(GLStateManager.getTextures().getTextureUnitBindings(i)); + textureAttribs.add(GLStateManager.getTextures().getTexEnvState(i)); } // Enable bits GL_TEXTURE_GEN_x where x is S, T, R, or Q @@ -326,14 +326,14 @@ public class Feature { attribToFeatures.put(GL11.GL_TRANSFORM_BIT, ImmutableSet.of( // Coefficients of the six clipping planes - // Enable bits for the user-definable clipping planes - GLStateManager.matrixMode - , GLStateManager.normalizeState // GL_NORMALIZE flag - , GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag + + GLStateManager.getMatrixMode() + , GLStateManager.getNormalizeState() + , GLStateManager.getRescaleNormalState() )); attribToFeatures.put(GL11.GL_VIEWPORT_BIT, ImmutableSet.of( - // Depth range (near and far) - GLStateManager.viewportState + + GLStateManager.getViewportState() )); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java index c93d38296..993008900 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java @@ -151,7 +151,7 @@ public class FeedbackManager { computeMVP(); final int stride = positionStride(); - final int elementSize = VAOManager.Attrib.glTypeSizeBytes(type); + final int elementSize = GLTypes.sizeBytes(type); final int indexByteCount = indexCount * elementSize; ensureIndexReadbackCapacity(indexByteCount); indexReadbackBuf.clear().limit(indexByteCount); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java new file mode 100644 index 000000000..af0797575 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java @@ -0,0 +1,198 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.AlphaStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.Color4Stack; +import com.gtnewhorizons.angelica.glsm.stacks.ColorMaskStack; +import com.gtnewhorizons.angelica.glsm.stacks.DepthStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.FogStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.IntegerStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.LightModelStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.LightStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.LineStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.MaterialStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.MatrixModeStack; +import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack; +import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack; +import com.gtnewhorizons.angelica.glsm.states.ClipPlaneState; +import com.gtnewhorizons.angelica.glsm.states.Color4; +import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState; +import com.gtnewhorizons.angelica.glsm.states.ImageUnitArray; +import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntStack; +import org.joml.Matrix4fStack; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; + +import java.util.ArrayList; +import java.util.List; + +class GLContextState { + final List allBooleanStates = new ArrayList<>(); + + private BooleanStateStack track(BooleanStateStack s) { + allBooleanStates.add(s); + return s; + } + + public int programGeneration; + public int drawFramebufferGeneration; + public boolean poppingAttributes; + // modelview matrix changes (any: translation, rotation, scale) + public int mvGeneration; + public int mvLinearGeneration; + // projection matrix changes + public int projGeneration; + // texture matrix changes + public int texMatrixGeneration; + public int lightingGeneration; + // fog + alpha ref + overlay color + public int fragmentGeneration; + // current vertex color + public int colorGeneration; + // clip plane equation changes + public int clipPlaneGeneration; + public float overlayR = 0.0f; + public float overlayG = 0.0f; + public float overlayB = 0.0f; + public float overlayA = 0.0f; + public float shaderColorR = 1.0f; + public float shaderColorG = 1.0f; + public float shaderColorB = 1.0f; + public float shaderColorA = 1.0f; + // Deferred vertex attribute upload flags - set when state changes, flushed before draw + public boolean dirtyColorAttrib = true; + public boolean dirtyNormalAttrib; + public boolean dirtyTexCoordAttrib; + public boolean dirtyLightmapAttrib = true; + public boolean unit23TexCoordSetDuringDraw = false; + public int maxBoundTextureUnit = 0; + public int maxBoundImageUnit = 0; + public final IntStack attribs = new IntArrayList(GLStateManager.MAX_ATTRIB_STACK_DEPTH); + public int attribDepth = 0; + @SuppressWarnings("unchecked") + public final List>[] modifiedAtDepth = new List[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedMvGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedMvLinearGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedProjGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedTexMatGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedLightingGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedFragmentGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedColorGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedNormalGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final int[] savedTexCoordGen = new int[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; + public final IntegerStateStack activeTextureUnit = new IntegerStateStack(0); + public int clientActiveTextureUnit = 0; + public final IntegerStateStack shadeModelState = new IntegerStateStack(GL11.GL_SMOOTH); + public final TextureUnitArray textures = new TextureUnitArray(); + public final ImageUnitArray imageUnits = new ImageUnitArray(); + public final BlendStateStack blendState = new BlendStateStack(); + public final BooleanStateStack blendMode = track(new BooleanStateStack(GL11.GL_BLEND)); + public final BooleanStateStack scissorTest = track(new BooleanStateStack(GL11.GL_SCISSOR_TEST)); + public final DepthStateStack depthState = new DepthStateStack(); + public final BooleanStateStack depthTest = track(new BooleanStateStack(GL11.GL_DEPTH_TEST)); + public final FogStateStack fogState = new FogStateStack(); + public final BooleanStateStack fogMode = track(new BooleanStateStack(GL11.GL_FOG, false, true)); + public final Color4Stack color = new Color4Stack(); + public final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F)); + public final ColorMaskStack colorMask = new ColorMaskStack(); + public final IntegerStateStack drawBuffer = new IntegerStateStack(GLStateManager.DEFAULT_DRAW_BUFFER); + public final IntegerStateStack logicOpMode = new IntegerStateStack(GL11.GL_COPY); + public final BooleanStateStack cullState = track(new BooleanStateStack(GL11.GL_CULL_FACE)); + public final AlphaStateStack alphaState = new AlphaStateStack(); + public final BooleanStateStack alphaTest = track(new BooleanStateStack(GL11.GL_ALPHA_TEST, false, true)); + public final BooleanStateStack lightingState = track(new BooleanStateStack(GL11.GL_LIGHTING, false, true)); + public final BooleanStateStack rescaleNormalState = track(new BooleanStateStack(GL12.GL_RESCALE_NORMAL, false, true)); + public final BooleanStateStack normalizeState = track(new BooleanStateStack(GL11.GL_NORMALIZE, false, true)); + public final BooleanStateStack ditherState = track(new BooleanStateStack(GL11.GL_DITHER, true)); + public final BooleanStateStack stencilTest = track(new BooleanStateStack(GL11.GL_STENCIL_TEST)); + public final BooleanStateStack lineSmoothState = track(new BooleanStateStack(GL11.GL_LINE_SMOOTH)); + public final BooleanStateStack lineStippleState = track(new BooleanStateStack(GL11.GL_LINE_STIPPLE, false, true)); + public final BooleanStateStack pointSmoothState = track(new BooleanStateStack(GL11.GL_POINT_SMOOTH, false, true)); + public final BooleanStateStack polygonSmoothState = track(new BooleanStateStack(GL11.GL_POLYGON_SMOOTH)); + public final BooleanStateStack polygonStippleState = track(new BooleanStateStack(GL11.GL_POLYGON_STIPPLE, false, true)); + public final BooleanStateStack multisampleState = track(new BooleanStateStack(GL13.GL_MULTISAMPLE, true)); + public final BooleanStateStack sampleAlphaToCoverageState = track(new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE)); + public final BooleanStateStack sampleAlphaToOneState = track(new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_ONE)); + public final BooleanStateStack sampleCoverageState = track(new BooleanStateStack(GL13.GL_SAMPLE_COVERAGE)); + public final BooleanStateStack colorLogicOpState = track(new BooleanStateStack(GL11.GL_COLOR_LOGIC_OP)); + public final BooleanStateStack indexLogicOpState = track(new BooleanStateStack(GL11.GL_INDEX_LOGIC_OP, false, true)); + public final BooleanStateStack polygonOffsetPointState = track(new BooleanStateStack(GL11.GL_POLYGON_OFFSET_POINT)); + public final BooleanStateStack polygonOffsetLineState = track(new BooleanStateStack(GL11.GL_POLYGON_OFFSET_LINE)); + public final BooleanStateStack polygonOffsetFillState = track(new BooleanStateStack(GL11.GL_POLYGON_OFFSET_FILL)); + public final LineStateStack lineState = new LineStateStack(); + public final PointStateStack pointState = new PointStateStack(); + public final PolygonStateStack polygonState = new PolygonStateStack(); + public final StencilStateStack stencilState = new StencilStateStack(); + public int stencilBitMask = 0xFFFFFFFF; + public final BooleanStateStack autoNormalState = track(new BooleanStateStack(GL11.GL_AUTO_NORMAL, false, true)); + public final BooleanStateStack map1Color4State = track(new BooleanStateStack(GL11.GL_MAP1_COLOR_4, false, true)); + public final BooleanStateStack map1IndexState = track(new BooleanStateStack(GL11.GL_MAP1_INDEX, false, true)); + public final BooleanStateStack map1NormalState = track(new BooleanStateStack(GL11.GL_MAP1_NORMAL, false, true)); + public final BooleanStateStack map1TextureCoord1State = track(new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_1, false, true)); + public final BooleanStateStack map1TextureCoord2State = track(new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_2, false, true)); + public final BooleanStateStack map1TextureCoord3State = track(new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_3, false, true)); + public final BooleanStateStack map1TextureCoord4State = track(new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_4, false, true)); + public final BooleanStateStack map1Vertex3State = track(new BooleanStateStack(GL11.GL_MAP1_VERTEX_3, false, true)); + public final BooleanStateStack map1Vertex4State = track(new BooleanStateStack(GL11.GL_MAP1_VERTEX_4, false, true)); + public final BooleanStateStack map2Color4State = track(new BooleanStateStack(GL11.GL_MAP2_COLOR_4, false, true)); + public final BooleanStateStack map2IndexState = track(new BooleanStateStack(GL11.GL_MAP2_INDEX, false, true)); + public final BooleanStateStack map2NormalState = track(new BooleanStateStack(GL11.GL_MAP2_NORMAL, false, true)); + public final BooleanStateStack map2TextureCoord1State = track(new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_1, false, true)); + public final BooleanStateStack map2TextureCoord2State = track(new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_2, false, true)); + public final BooleanStateStack map2TextureCoord3State = track(new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_3, false, true)); + public final BooleanStateStack map2TextureCoord4State = track(new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_4, false, true)); + public final BooleanStateStack map2Vertex3State = track(new BooleanStateStack(GL11.GL_MAP2_VERTEX_3, false, true)); + public final BooleanStateStack map2Vertex4State = track(new BooleanStateStack(GL11.GL_MAP2_VERTEX_4, false, true)); + public final BooleanStateStack[] clipPlaneStates = new BooleanStateStack[GLStateManager.MAX_CLIP_PLANES]; + public final ClipPlaneState clipPlaneState = new ClipPlaneState(); + public final MatrixModeStack matrixMode = new MatrixModeStack(); + public final Matrix4fStack modelViewMatrix = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH); + public final Matrix4fStack projectionMatrix = new Matrix4fStack(GLStateManager.MAX_PROJECTION_STACK_DEPTH); + public final BooleanStateStack[] lightStates = new BooleanStateStack[8]; + public final LightStateStack[] lightDataStates = new LightStateStack[8]; + public final BooleanStateStack colorMaterial = track(new BooleanStateStack(GL11.GL_COLOR_MATERIAL, false, true)); + public final IntegerStateStack colorMaterialFace = new IntegerStateStack(GL11.GL_FRONT_AND_BACK); + public final IntegerStateStack colorMaterialParameter = new IntegerStateStack(GL11.GL_AMBIENT_AND_DIFFUSE); + public final LightModelStateStack lightModel = new LightModelStateStack(); + public final MaterialStateStack frontMaterial = new MaterialStateStack(GL11.GL_FRONT); + public final MaterialStateStack backMaterial = new MaterialStateStack(GL11.GL_BACK); + public final ViewPortStateStack viewportState = new ViewPortStateStack(); + public int activeProgram = 0; + public int listBase = 0; + public int boundVBO; + public int boundVAO; + public int boundPixelUnpackBuffer; + public int boundPixelPackBuffer; + public PixelUnpackState pixelUnpackState = PixelUnpackState.DEFAULT; + public final int[] clientAttribSavedTextureUnit = new int[GLStateManager.CLIENT_ATTRIB_STACK_DEPTH]; + public final int[] clientAttribSavedVertexFlags = new int[GLStateManager.CLIENT_ATTRIB_STACK_DEPTH]; + public int clientAttribStackPointer = 0; + public final boolean[] restoreUnitChanged = new boolean[GLStateManager.MAX_TEXTURE_UNITS]; + public boolean restoreDepthChanged, restoreBlendChanged, restoreColorMaskChanged, restoreClearColorChanged, restoreDrawBufferChanged, restoreLogicOpChanged, restoreStencilChanged, restoreViewportChanged, restoreLineChanged, restorePointChanged, restorePolygonChanged, restoreActiveUnitChanged; + public int drawFramebuffer = 0; + public int readFramebuffer = 0; + public int texGenGeneration; + + GLContextState() { + for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) modifiedAtDepth[i] = new ArrayList<>(); + for (int i = 0; i < lightStates.length; i++) { + lightStates[i] = track(new BooleanStateStack(GL11.GL_LIGHT0 + i, false, true)); + } + for (int i = 0; i < GLStateManager.MAX_CLIP_PLANES; i++) { + clipPlaneStates[i] = track(new BooleanStateStack(GL11.GL_CLIP_PLANE0 + i)); + } + } + + void init() { + for (int i = 0; i < lightDataStates.length; i++) { + lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i); + } + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLDebug.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLDebug.java index d27535967..b5a214889 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLDebug.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLDebug.java @@ -6,6 +6,8 @@ package com.gtnewhorizons.angelica.glsm; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMInitConfig; import org.lwjgl.opengl.EXTBlendColor; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -14,6 +16,10 @@ import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL43; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + public final class GLDebug { /** @@ -252,25 +258,6 @@ public final class GLDebug { }; } - public static String getDataTypeName(int type) { - return switch (type) { - case GL11.GL_UNSIGNED_BYTE -> "UNSIGNED_BYTE"; - case GL11.GL_BYTE -> "BYTE"; - case GL11.GL_UNSIGNED_SHORT -> "UNSIGNED_SHORT"; - case GL11.GL_SHORT -> "SHORT"; - case GL11.GL_UNSIGNED_INT -> "UNSIGNED_INT"; - case GL11.GL_INT -> "INT"; - case GL11.GL_FLOAT -> "FLOAT"; - case GL11.GL_DOUBLE -> "DOUBLE"; - case GL12.GL_UNSIGNED_BYTE_3_3_2 -> "UNSIGNED_BYTE_3_3_2"; - case GL12.GL_UNSIGNED_SHORT_4_4_4_4 -> "UNSIGNED_SHORT_4_4_4_4"; - case GL12.GL_UNSIGNED_SHORT_5_5_5_1 -> "UNSIGNED_SHORT_5_5_5_1"; - case GL12.GL_UNSIGNED_INT_8_8_8_8 -> "UNSIGNED_INT_8_8_8_8"; - case GL12.GL_UNSIGNED_INT_10_10_10_2 -> "UNSIGNED_INT_10_10_10_2"; - default -> String.format("0x%X", type); - }; - } - public static String getLightName(int light) { return switch (light) { case GL11.GL_LIGHT0 -> "LIGHT0"; @@ -559,7 +546,9 @@ public final class GLDebug { } public static void initDebugState() { - if (BackendManager.RENDER_BACKEND.supportsDebugOutput()) { + final GLSMInitConfig cfg = GLStateManager.getInitConfig(); + final boolean userRequested = cfg != null && (cfg.isLwjglDebug() || CaptureGate.enabledAtStartup()); + if (userRequested && BackendManager.RENDER_BACKEND.supportsDebugOutput()) { debugState = new KHRDebugState(); } else { debugState = new UnsupportedDebugState(); @@ -581,6 +570,10 @@ public final class GLDebug { } } + public static boolean isActive() { + return debugState instanceof KHRDebugState && CaptureGate.markersThisFrame && Thread.currentThread() == GLStateManager.getMainThread(); + } + public static void pushGroup(String group) { if (debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) { debugState.pushGroup(group); @@ -606,4 +599,49 @@ public final class GLDebug { return ""; } + private static final Scope NOOP_SCOPE = () -> {}; + private static final Scope ACTIVE_SCOPE = GLDebug::popGroup; + + public static Scope scope(String name) { + if (isActive()) { + debugState.pushGroup(name); + return ACTIVE_SCOPE; + } + return NOOP_SCOPE; + } + + @FunctionalInterface + public interface Scope extends AutoCloseable { + @Override void close(); + } + + private static MethodHandle khrCallbackInvoke; + private static boolean khrCallbackInvokeResolved; + + /// Use reflection because of lwjgl3ify + static GLDebugMessageListener adaptDebugCallback(Object callback) { + if (callback == null) return null; + final MethodHandle invoke = resolveKhrCallbackInvoke(callback.getClass()); + if (invoke == null) return null; + return (source, type, id, severity, length, message, userParam) -> { + try { + invoke.invoke(callback, source, type, id, severity, length, message, userParam); + } catch (Throwable t) { + GLStateManager.LOGGER.warn("Debug message callback threw", t); + } + }; + } + + private static synchronized MethodHandle resolveKhrCallbackInvoke(Class callbackClass) { + if (!khrCallbackInvokeResolved) { + khrCallbackInvokeResolved = true; + try { + khrCallbackInvoke = MethodHandles.publicLookup().findVirtual(callbackClass, "invoke", MethodType.methodType(void.class, int.class, int.class, int.class, int.class, int.class, long.class, long.class)); + } catch (ReflectiveOperationException e) { + GLStateManager.LOGGER.warn("{} has no public invoke(int,int,int,int,int,long,long); debug messages registered through it will not be delivered.", callbackClass.getName()); + } + } + return khrCallbackInvoke; + } + } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESCaps.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESCaps.java new file mode 100644 index 000000000..7f6edaaea --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESCaps.java @@ -0,0 +1,34 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL32; + +public final class GLESCaps { + + private GLESCaps() {} + + public static boolean isCapAllowed(int cap, boolean isGLES, boolean hasClipCullDistance) { + if (!isGLES) return true; + if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + GLStateManager.MAX_CLIP_PLANES) { + return hasClipCullDistance; + } + return switch (cap) { + case GL11.GL_LINE_SMOOTH, + GL11.GL_POLYGON_SMOOTH, + GL11.GL_COLOR_LOGIC_OP, + GL11.GL_POLYGON_OFFSET_POINT, + GL11.GL_POLYGON_OFFSET_LINE, + GL13.GL_MULTISAMPLE, + GL13.GL_SAMPLE_ALPHA_TO_ONE, + GL20.GL_VERTEX_PROGRAM_POINT_SIZE, + GL30.GL_FRAMEBUFFER_SRGB, + GL31.GL_PRIMITIVE_RESTART, + GL32.GL_DEPTH_CLAMP -> false; + default -> true; + }; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemap.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemap.java new file mode 100644 index 000000000..3b3185018 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemap.java @@ -0,0 +1,86 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; + +public final class GLESFormatRemap { + + private GLESFormatRemap() {} + + public record Result(int internalFormat, int format, int type) {} + + public static Result apply(int internalformat, int format, int type, boolean isGLES) { + internalformat = promoteAlphaFormat(internalformat); + if (isGLES) { + internalformat = remapInternalFormat(internalformat); + if (type == GL12.GL_UNSIGNED_INT_8_8_8_8_REV && (format == GL12.GL_BGRA || format == GL11.GL_RGBA)) { + type = GL11.GL_UNSIGNED_BYTE; + } + if (isGenericPixelType(type)) { + type = typeForInternalFormatES32(internalformat, type); + } + } + return new Result(internalformat, format, type); + } + + public static int promoteAlphaFormat(int internalformat) { + return switch (internalformat) { + case GL11.GL_ALPHA4 -> GL11.GL_RGBA4; + case GL11.GL_ALPHA8 -> GL11.GL_RGBA8; + case GL11.GL_ALPHA12 -> GL11.GL_RGBA12; + case GL11.GL_ALPHA16 -> GL11.GL_RGBA16; + default -> internalformat; + }; + } + + public static int remapInternalFormat(int internalformat) { + return switch (internalformat) { + case GL11.GL_RGB16, GL11.GL_RGB12 -> GL30.GL_RGB16F; + case GL11.GL_RGBA16, GL11.GL_RGBA12 -> GL30.GL_RGBA16F; + case GL30.GL_R16 -> GL30.GL_R16F; + case GL30.GL_RG16 -> GL30.GL_RG16F; + case GL11.GL_RGB10, GL11.GL_R3_G3_B2 -> GL11.GL_RGB8; + default -> internalformat; + }; + } + + public static int remapPixelType(int format, int type) { + if (type == GL12.GL_UNSIGNED_INT_8_8_8_8_REV && (format == GL12.GL_BGRA || format == GL11.GL_RGBA)) { + return GL11.GL_UNSIGNED_BYTE; + } + return type; + } + + public static int typeForInternalFormatES32(int internalformat, int type) { + return switch (internalformat) { + case GL30.GL_R16F, GL30.GL_RG16F, GL30.GL_RGB16F, GL30.GL_RGBA16F -> GL30.GL_HALF_FLOAT; + case GL30.GL_R32F, GL30.GL_RG32F, GL30.GL_RGB32F, GL30.GL_RGBA32F -> GL11.GL_FLOAT; + case GL31.GL_R8_SNORM, GL31.GL_RG8_SNORM, GL31.GL_RGB8_SNORM, GL31.GL_RGBA8_SNORM -> GL11.GL_BYTE; + case GL30.GL_R11F_G11F_B10F, GL30.GL_RGB9_E5 -> GL30.GL_HALF_FLOAT; + case GL11.GL_RGB10_A2 -> GL12.GL_UNSIGNED_INT_2_10_10_10_REV; + case GL30.GL_R8I, GL30.GL_RG8I, GL30.GL_RGB8I, GL30.GL_RGBA8I, + GL30.GL_R16I, GL30.GL_RG16I, GL30.GL_RGB16I, GL30.GL_RGBA16I, + GL30.GL_R32I, GL30.GL_RG32I, GL30.GL_RGB32I, GL30.GL_RGBA32I -> GL11.GL_INT; + case GL30.GL_R8UI, GL30.GL_RG8UI, GL30.GL_RGB8UI, GL30.GL_RGBA8UI, + GL30.GL_R16UI, GL30.GL_RG16UI, GL30.GL_RGB16UI, GL30.GL_RGBA16UI, + GL30.GL_R32UI, GL30.GL_RG32UI, GL30.GL_RGB32UI, GL30.GL_RGBA32UI -> GL11.GL_UNSIGNED_INT; + case GL14.GL_DEPTH_COMPONENT24 -> GL11.GL_UNSIGNED_INT; + case GL30.GL_DEPTH_COMPONENT32F -> GL11.GL_FLOAT; + case GL30.GL_DEPTH24_STENCIL8 -> GL30.GL_UNSIGNED_INT_24_8; + case GL30.GL_DEPTH32F_STENCIL8 -> GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV; + default -> type; + }; + } + + public static boolean isGenericPixelType(int type) { + return type == GL11.GL_UNSIGNED_BYTE + || type == GL11.GL_UNSIGNED_SHORT + || type == GL11.GL_UNSIGNED_INT + || type == GL11.GL_BYTE + || type == GL11.GL_SHORT + || type == GL11.GL_INT; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index 2d9351af6..d8befe651 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -6,8 +6,11 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Usage; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler; @@ -43,6 +46,8 @@ import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack; import com.gtnewhorizons.angelica.glsm.states.ClipPlaneState; import com.gtnewhorizons.angelica.glsm.states.Color4; import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState; +import com.gtnewhorizons.angelica.glsm.states.PolygonState; +import com.gtnewhorizons.angelica.glsm.states.ImageUnitBinding; import com.gtnewhorizons.angelica.glsm.states.TextureBinding; import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; @@ -70,6 +75,7 @@ import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Drawable; import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL42; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; @@ -81,11 +87,15 @@ import org.lwjgl.opengl.GL31; import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GLContext; import org.lwjgl.opengl.KHRDebug; +import org.lwjgl.opengl.KHRDebugCallback; +import org.lwjgl.util.glu.GLU; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; +import java.nio.Buffer; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; @@ -98,6 +108,7 @@ import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.IntSupplier; import static com.gtnewhorizons.angelica.glsm.Vendor.AMD; @@ -129,6 +140,63 @@ public class GLStateManager { if (WARN_ONCE.add(key)) LOGGER.warn(fmt, args); } + private static final CopyOnWriteArrayList registeredContexts = new CopyOnWriteArrayList<>(); + private static volatile GLContextState primaryContext; + private static final ThreadLocal tlWorkerContext = new ThreadLocal<>(); + private static volatile boolean workerContextsActive; + private static int workerContextCount; + + static GLContextState ctx() { + if (!workerContextsActive) return primaryContext(); + final GLContextState st = tlWorkerContext.get(); + return st != null ? st : primaryContext(); + } + + private static GLContextState primaryContext() { + GLContextState p = primaryContext; + if (p != null) return p; + synchronized (GLStateManager.class) { + p = primaryContext; + if (p == null) { + p = new GLContextState(); + primaryContext = p; + registeredContexts.add(p); + p.init(); + } + } + return p; + } + + static GLContextState enterWorkerContext() { + final GLContextState st = new GLContextState(); + tlWorkerContext.set(st); + synchronized (GLStateManager.class) { + workerContextCount++; + workerContextsActive = true; + } + registeredContexts.add(st); + st.init(); + return st; + } + + static void exitWorkerContext() { + final GLContextState st = tlWorkerContext.get(); + if (st != null) { + registeredContexts.remove(st); + tlWorkerContext.remove(); + synchronized (GLStateManager.class) { + if (--workerContextCount == 0) workerContextsActive = false; + } + } + } + + // Tracy profiling counters + public static long drawCalls; + public static long texBindMisses; + public static long programSwitches; + public static int programGeneration; + public static int drawFramebufferGeneration; + // Thread Checking - must be early in static init order so isMainThread() works for state initialization @Getter private static final Thread MainThread = Thread.currentThread(); @@ -140,8 +208,6 @@ public class GLStateManager { public static ContextCapabilities capabilities; - @Getter protected static boolean poppingAttributes; - public static boolean BYPASS_CACHE = Boolean.parseBoolean(System.getProperty("angelica.disableGlCache", "false")); // Software stack depths for FFP emulation public static final int MAX_ATTRIB_STACK_DEPTH = 16 + 2; public static final int MAX_MODELVIEW_STACK_DEPTH = 32 + 2; @@ -153,35 +219,18 @@ public class GLStateManager { public static final GLFeatureSet HAS_MULTIPLE_SET = new GLFeatureSet(); // Generation counters for FFP uniform dirty tracking. Bumped when the corresponding GLSM state changes. - // Per-matrix-mode generation counters — avoids re-uploading all matrices when only one mode changed - public static int mvGeneration; // modelview matrix changes (any: translation, rotation, scale) - public static int mvLinearGeneration; - public static int projGeneration; // projection matrix changes - public static int texMatrixGeneration; // texture matrix changes - public static int lightingGeneration; - public static int fragmentGeneration; // fog + alpha ref + overlay color - public static int colorGeneration; // current vertex color - public static int clipPlaneGeneration; // clip plane equation changes - - @Getter private static float overlayR = 0.0f; - @Getter private static float overlayG = 0.0f; - @Getter private static float overlayB = 0.0f; - @Getter private static float overlayA = 0.0f; - + // Per-matrix-mode generation counters - avoids re-uploading all matrices when only one mode changed public static void setOverlayColor(float r, float g, float b, float a) { - if (r == overlayR && g == overlayG && b == overlayB && a == overlayA) return; - overlayR = r; overlayG = g; overlayB = b; overlayA = a; - fragmentGeneration++; + final GLContextState glCtx = ctx(); + if (r == glCtx.overlayR && g == glCtx.overlayG && b == glCtx.overlayB && a == glCtx.overlayA) return; + glCtx.overlayR = r; glCtx.overlayG = g; glCtx.overlayB = b; glCtx.overlayA = a; + glCtx.fragmentGeneration++; } - @Getter private static float shaderColorR = 1.0f; - @Getter private static float shaderColorG = 1.0f; - @Getter private static float shaderColorB = 1.0f; - @Getter private static float shaderColorA = 1.0f; - public static void setShaderColor(float r, float g, float b, float a) { - if (r == shaderColorR && g == shaderColorG && b == shaderColorB && a == shaderColorA) return; - shaderColorR = r; shaderColorG = g; shaderColorB = b; shaderColorA = a; + final GLContextState glCtx = ctx(); + if (r == glCtx.shaderColorR && g == glCtx.shaderColorG && b == glCtx.shaderColorB && a == glCtx.shaderColorA) return; + glCtx.shaderColorR = r; glCtx.shaderColorG = g; glCtx.shaderColorB = b; glCtx.shaderColorA = a; if (GLSMHooks.SHADER_COLOR_CHANGE.hasListeners()) { GLSMHooks.shaderColorChangeEvent.red = r; GLSMHooks.shaderColorChangeEvent.green = g; @@ -191,59 +240,68 @@ public class GLStateManager { } } - // Deferred vertex attribute upload flags — set when state changes, flushed before draw - private static boolean dirtyColorAttrib = true; - private static boolean dirtyNormalAttrib; - private static boolean dirtyTexCoordAttrib; - private static boolean dirtyLightmapAttrib = true; - - private static boolean unit23TexCoordSetDuringDraw = false; public static boolean consumeUnit23TexCoordSetDuringDraw() { - boolean v = unit23TexCoordSetDuringDraw; - unit23TexCoordSetDuringDraw = false; + final GLContextState glCtx = ctx(); + boolean v = glCtx.unit23TexCoordSetDuringDraw; + glCtx.unit23TexCoordSetDuringDraw = false; return v; } - // vertexFlags bits mark attribs the VBO already supplies; FFP supplies the rest via u_Current* uniforms. - // Skip the backend vertexAttrib call in either case. + public static void forceAttribDefaultsDirty() { + final GLContextState glCtx = ctx(); + glCtx.dirtyNormalAttrib = true; + glCtx.dirtyTexCoordAttrib = true; + } + + // has* bits mark attribs the VBO already supplies; FFP supplies the rest via u_Current* uniforms. + // Skip the backend vertexAttrib call in either case public static void flushDeferredVertexAttribs(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { - if (!hasColor && dirtyColorAttrib) { - RENDER_BACKEND.vertexAttrib4f(Usage.COLOR.getAttributeLocation(), color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); - dirtyColorAttrib = false; + final GLContextState glCtx = ctx(); + final ShaderManager sm = ShaderManager.getInstance(); + final boolean ffpWillHandle = sm.isActive() || (sm.isEnabled() && getActiveProgram() == 0); + if (!hasColor && glCtx.dirtyColorAttrib && !ffpWillHandle) { + RENDER_BACKEND.vertexAttrib4f(Usage.COLOR.getAttributeLocation(), glCtx.color.getRed(), glCtx.color.getGreen(), glCtx.color.getBlue(), glCtx.color.getAlpha()); + glCtx.dirtyColorAttrib = false; } - if (!hasNormal && dirtyNormalAttrib) { + if (!hasNormal && glCtx.dirtyNormalAttrib && !ffpWillHandle) { final var n = ShaderManager.getCurrentNormal(); RENDER_BACKEND.vertexAttrib3f(Usage.NORMAL.getAttributeLocation(), n.x, n.y, n.z); - dirtyNormalAttrib = false; + glCtx.dirtyNormalAttrib = false; } - if (!hasTexCoord && dirtyTexCoordAttrib) { + if (!hasTexCoord && glCtx.dirtyTexCoordAttrib && !ffpWillHandle) { final var tc = ShaderManager.getCurrentTexCoord(); RENDER_BACKEND.vertexAttrib4f(Usage.PRIMARY_UV.getAttributeLocation(), tc.x, tc.y, tc.z, tc.w); - dirtyTexCoordAttrib = false; + glCtx.dirtyTexCoordAttrib = false; } - if (!hasLightmap && dirtyLightmapAttrib) { + if (!hasLightmap && glCtx.dirtyLightmapAttrib && !ffpWillHandle) { RENDER_BACKEND.vertexAttrib4f(Usage.SECONDARY_UV.getAttributeLocation(), GLSMConfig.lastBrightnessX, GLSMConfig.lastBrightnessY, 0.0f, 1.0f); - dirtyLightmapAttrib = false; + glCtx.dirtyLightmapAttrib = false; } } - // Highest texture unit index that has ever had a non-zero binding; limits onDeleteTexture scan range - private static int maxBoundTextureUnit = 0; + + public static int getMaxBoundTextureUnit() { + return ctx().maxBoundTextureUnit; + } + + public static void trackMaxBoundTextureUnit(int unit) { + final GLContextState glCtx = ctx(); + if (unit > glCtx.maxBoundTextureUnit) glCtx.maxBoundTextureUnit = unit; + } // Lock guard for texture bind callback (prevents recursion from RenderSystem.bindTextureToUnit) private static boolean lockBindCallback; // Deferred texture deletion: names kept valid until glGenTextures recycles them. // Emulates Mesa/compat-profile behavior where delete-then-bind doesn't error. private static final IntOpenHashSet deferredDeleteTextures = new IntOpenHashSet(); - private static long loggedUncachedTextureTargets = 0; @Getter private static Vendor VENDOR; @Getter private static boolean windows; // This setting varies depending on driver, so it gets queried at runtime - public static int DEFAULT_DRAW_BUFFER = 0x0405; // GL_BACK + public static int DEFAULT_DRAW_BUFFER = GL11.GL_BACK; private static Thread CurrentThread = MainThread; @Setter @Getter private static boolean runningSplash = true; @@ -265,6 +323,14 @@ public class GLStateManager { DRAW_LOCK.unlock(); } + private static volatile boolean stateSeedPending = false; + + public static boolean takeStateSeedPending() { + if (!stateSeedPending) return false; + stateSeedPending = false; + return true; + } + public static boolean isCachingEnabled() { if (splashComplete) return true; return Thread.currentThread() == drawableGLHolder; @@ -302,6 +368,14 @@ public class GLStateManager { return RENDER_BACKEND.getInteger(GL11.GL_TEXTURE_BINDING_2D); } + private static TextureInfo getBoundTextureInfo() { + final GLContextState glCtx = ctx(); + if (isCachingEnabled()) { + return glCtx.textures.getTextureUnitBindings(glCtx.activeTextureUnit.getValue()).getOrResolveInfo(); + } + return TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState()); + } + /** * Get the texture bound to a specific texture unit for server-side state operations. * If caching is enabled, returns cached value. @@ -317,94 +391,26 @@ public class GLStateManager { private static final String TEXTURE = "texture"; private static final String TEXTURE_RENAMED = "gtexture"; - // GLStateManager State Trackers - private static final IntStack attribs = new IntArrayList(MAX_ATTRIB_STACK_DEPTH); - - // Lazy copy-on-write tracking: only iterate modified states during popState - @Getter private static int attribDepth = 0; - @SuppressWarnings("unchecked") - private static final List>[] modifiedAtDepth = new List[MAX_ATTRIB_STACK_DEPTH]; - - static { - for (int i = 0; i < MAX_ATTRIB_STACK_DEPTH; i++) { - modifiedAtDepth[i] = new ArrayList<>(); - } - } - - // Saved generation counters at push time — used to detect whether state actually changed during push/pop scope - private static final int[] savedMvGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedMvLinearGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedProjGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedTexMatGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedLightingGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedFragmentGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedColorGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedNormalGen = new int[MAX_ATTRIB_STACK_DEPTH]; - private static final int[] savedTexCoordGen = new int[MAX_ATTRIB_STACK_DEPTH]; - /** Register a state stack as modified at the current depth (called from beforeModify). */ public static void registerModifiedState(IStateStack stack) { - if (attribDepth > 0) { - modifiedAtDepth[attribDepth - 1].add(stack); + final GLContextState c = ctx(); + if (c.attribDepth > 0) { + c.modifiedAtDepth[c.attribDepth - 1].add(stack); } } - protected static final IntegerStateStack activeTextureUnit = new IntegerStateStack(0); - private static int clientActiveTextureUnit = 0; - protected static final IntegerStateStack shadeModelState = new IntegerStateStack(GL11.GL_SMOOTH); - @Getter protected static final TextureUnitArray textures = new TextureUnitArray(); - @Getter protected static final BlendStateStack blendState = new BlendStateStack(); - @Getter protected static final BooleanStateStack blendMode = new BooleanStateStack(GL11.GL_BLEND); - @Getter protected static final BooleanStateStack scissorTest = new BooleanStateStack(GL11.GL_SCISSOR_TEST); - @Getter protected static final DepthStateStack depthState = new DepthStateStack(); - @Getter protected static final BooleanStateStack depthTest = new BooleanStateStack(GL11.GL_DEPTH_TEST); - - @Getter protected static final FogStateStack fogState = new FogStateStack(); - @Getter protected static final BooleanStateStack fogMode = new BooleanStateStack(GL11.GL_FOG, false, true); - @Getter protected static final Color4Stack color = new Color4Stack(); - @Getter protected static final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F)); - @Getter protected static final ColorMaskStack colorMask = new ColorMaskStack(); - @Getter protected static final IntegerStateStack drawBuffer = new IntegerStateStack(DEFAULT_DRAW_BUFFER); - @Getter protected static final IntegerStateStack logicOpMode = new IntegerStateStack(GL11.GL_COPY); - @Getter protected static final BooleanStateStack cullState = new BooleanStateStack(GL11.GL_CULL_FACE); - @Getter protected static final AlphaStateStack alphaState = new AlphaStateStack(); - @Getter protected static final BooleanStateStack alphaTest = new BooleanStateStack(GL11.GL_ALPHA_TEST, false, true); - - - @Getter protected static final BooleanStateStack lightingState = new BooleanStateStack(GL11.GL_LIGHTING, false, true); - @Getter protected static final BooleanStateStack rescaleNormalState = new BooleanStateStack(GL12.GL_RESCALE_NORMAL, false, true); - @Getter protected static final BooleanStateStack normalizeState = new BooleanStateStack(GL11.GL_NORMALIZE, false, true); - // Additional enable bit states tracked by GL_ENABLE_BIT - @Getter protected static final BooleanStateStack ditherState = new BooleanStateStack(GL11.GL_DITHER, true); // Defaults to true per OpenGL spec - @Getter protected static final BooleanStateStack stencilTest = new BooleanStateStack(GL11.GL_STENCIL_TEST); - @Getter protected static final BooleanStateStack lineSmoothState = new BooleanStateStack(GL11.GL_LINE_SMOOTH); - @Getter protected static final BooleanStateStack lineStippleState = new BooleanStateStack(GL11.GL_LINE_STIPPLE, false, true); - @Getter protected static final BooleanStateStack pointSmoothState = new BooleanStateStack(GL11.GL_POINT_SMOOTH, false, true); - @Getter protected static final BooleanStateStack polygonSmoothState = new BooleanStateStack(GL11.GL_POLYGON_SMOOTH); - @Getter protected static final BooleanStateStack polygonStippleState = new BooleanStateStack(GL11.GL_POLYGON_STIPPLE, false, true); - @Getter protected static final BooleanStateStack multisampleState = new BooleanStateStack(GL13.GL_MULTISAMPLE, true); // Defaults to true per OpenGL spec - @Getter protected static final BooleanStateStack sampleAlphaToCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE); - @Getter protected static final BooleanStateStack sampleAlphaToOneState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_ONE); - @Getter protected static final BooleanStateStack sampleCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_COVERAGE); - @Getter protected static final BooleanStateStack colorLogicOpState = new BooleanStateStack(GL11.GL_COLOR_LOGIC_OP); - @Getter protected static final BooleanStateStack indexLogicOpState = new BooleanStateStack(GL11.GL_INDEX_LOGIC_OP, false, true); - // Polygon offset states (enable bits) - @Getter protected static final BooleanStateStack polygonOffsetPointState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_POINT); - @Getter protected static final BooleanStateStack polygonOffsetLineState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_LINE); - @Getter protected static final BooleanStateStack polygonOffsetFillState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_FILL); - - // Line state (GL_LINE_BIT) - @Getter protected static final LineStateStack lineState = new LineStateStack(); // Line width range queried at init from GL_ALIASED_LINE_WIDTH_RANGE static float lineWidthMin = 1.0f; static float lineWidthMax = 1.0f; /** True when the driver cannot render wide lines natively (Mesa forward-compat). GS emulation handles widths > 1.0. */ public static boolean wideLineEmulationEnabled = false; + public static boolean supportsGeometryShaders() { return RENDER_BACKEND.supportsGeometryShaders(); } + public static boolean framebufferCompletenessIsMeaningful() { return RENDER_BACKEND.framebufferCompletenessIsMeaningful(); } /** * Set per draw call: true when the current draw is a line primitive that needs GS expansion. Read by * {@link com.gtnewhorizons.angelica.glsm.ffp.VertexKey}. @@ -412,66 +418,15 @@ public class GLStateManager { public static boolean wideLineEmulationActive = false; public static boolean lineStippleActive = false; - // Point state (GL_POINT_BIT) - @Getter protected static final PointStateStack pointState = new PointStateStack(); + public static boolean instancedFfpDrawActive = false; - // Polygon state (GL_POLYGON_BIT) - mode, offset values, cull face mode, front face - @Getter protected static final PolygonStateStack polygonState = new PolygonStateStack(); - // Stencil state (GL_STENCIL_BUFFER_BIT) - @Getter protected static final StencilStateStack stencilState = new StencilStateStack(); - private static int stencilBitMask = 0xFFFFFFFF; - @Getter protected static final BooleanStateStack autoNormalState = new BooleanStateStack(GL11.GL_AUTO_NORMAL, false, true); - @Getter protected static final BooleanStateStack map1Color4State = new BooleanStateStack(GL11.GL_MAP1_COLOR_4, false, true); - @Getter protected static final BooleanStateStack map1IndexState = new BooleanStateStack(GL11.GL_MAP1_INDEX, false, true); - @Getter protected static final BooleanStateStack map1NormalState = new BooleanStateStack(GL11.GL_MAP1_NORMAL, false, true); - @Getter protected static final BooleanStateStack map1TextureCoord1State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_1, false, true); - @Getter protected static final BooleanStateStack map1TextureCoord2State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_2, false, true); - @Getter protected static final BooleanStateStack map1TextureCoord3State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_3, false, true); - @Getter protected static final BooleanStateStack map1TextureCoord4State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_4, false, true); - @Getter protected static final BooleanStateStack map1Vertex3State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_3, false, true); - @Getter protected static final BooleanStateStack map1Vertex4State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_4, false, true); - @Getter protected static final BooleanStateStack map2Color4State = new BooleanStateStack(GL11.GL_MAP2_COLOR_4, false, true); - @Getter protected static final BooleanStateStack map2IndexState = new BooleanStateStack(GL11.GL_MAP2_INDEX, false, true); - @Getter protected static final BooleanStateStack map2NormalState = new BooleanStateStack(GL11.GL_MAP2_NORMAL, false, true); - @Getter protected static final BooleanStateStack map2TextureCoord1State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_1, false, true); - @Getter protected static final BooleanStateStack map2TextureCoord2State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_2, false, true); - @Getter protected static final BooleanStateStack map2TextureCoord3State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_3, false, true); - @Getter protected static final BooleanStateStack map2TextureCoord4State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_4, false, true); - @Getter protected static final BooleanStateStack map2Vertex3State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_3, false, true); - @Getter protected static final BooleanStateStack map2Vertex4State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_4, false, true); - // Clip plane states - @Getter protected static final BooleanStateStack[] clipPlaneStates = new BooleanStateStack[MAX_CLIP_PLANES]; - @Getter protected static final ClipPlaneState clipPlaneState = new ClipPlaneState(); - - @Getter protected static final MatrixModeStack matrixMode = new MatrixModeStack(); - @Getter protected static final Matrix4fStack modelViewMatrix = new Matrix4fStack(MAX_MODELVIEW_STACK_DEPTH); - @Getter protected static final Matrix4fStack projectionMatrix = new Matrix4fStack(MAX_PROJECTION_STACK_DEPTH); - - @Getter protected static final BooleanStateStack[] lightStates = new BooleanStateStack[8]; - @Getter protected static final LightStateStack[] lightDataStates = new LightStateStack[8]; - @Getter protected static final BooleanStateStack colorMaterial = new BooleanStateStack(GL11.GL_COLOR_MATERIAL, false, true); - @Getter protected static final IntegerStateStack colorMaterialFace = new IntegerStateStack(GL11.GL_FRONT_AND_BACK); - @Getter protected static final IntegerStateStack colorMaterialParameter = new IntegerStateStack(GL11.GL_AMBIENT_AND_DIFFUSE); - @Getter protected static final LightModelStateStack lightModel = new LightModelStateStack(); - - @Getter protected static final MaterialStateStack frontMaterial = new MaterialStateStack(GL11.GL_FRONT); - @Getter protected static final MaterialStateStack backMaterial = new MaterialStateStack(GL11.GL_BACK); private static final MethodHandle MAT4_STACK_CURR_DEPTH; static { - for (int i = 0; i < lightStates.length; i++) { - lightStates[i] = new BooleanStateStack(GL11.GL_LIGHT0 + i, false, true); - lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i); - } - - for (int i = 0; i < MAX_CLIP_PLANES; i++) { - clipPlaneStates[i] = new BooleanStateStack(GL11.GL_CLIP_PLANE0 + i); - } - try { final Field curr = Matrix4fStack.class.getDeclaredField("curr"); curr.setAccessible(true); @@ -481,28 +436,17 @@ public class GLStateManager { } } - @Getter protected static final ViewPortStateStack viewportState = new ViewPortStateStack(); - - @Getter protected static int activeProgram = 0; - @Getter protected static int listBase = 0; - - @Getter protected static int boundVBO; - @Getter protected static int boundVAO; - public static int getBoundEBO() { return VAOManager.boundEBO; } - private static int boundPixelUnpackBuffer; - private static int boundPixelPackBuffer; - private static PixelUnpackState pixelUnpackState = PixelUnpackState.DEFAULT; - @Getter private static int defaultVAO; // Non-zero on core profile public static void reset() { + final GLContextState glCtx = ctx(); runningSplash = true; - while (!attribs.isEmpty()) { - attribs.popInt(); + while (!glCtx.attribs.isEmpty()) { + glCtx.attribs.popInt(); } final List> stacks = Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS); @@ -516,8 +460,8 @@ public class GLStateManager { } } - modelViewMatrix.clear(); - projectionMatrix.clear(); + glCtx.modelViewMatrix.clear(); + glCtx.projectionMatrix.clear(); } /** @@ -580,7 +524,7 @@ public class GLStateManager { if (displayWidth > 0 && displayHeight > 0) { // Initialize viewport state from display dimensions. // After Display.create(), viewport is (0, 0, width, height) - viewportState.setViewPort(0, 0, displayWidth, displayHeight); + ctx().viewportState.setViewPort(0, 0, displayWidth, displayHeight); } final String glVendor = RENDER_BACKEND.getString(GL11.GL_VENDOR); @@ -591,25 +535,26 @@ public class GLStateManager { } static void init(Runnable initCallback) { + final GLContextState glCtx = ctx(); RenderSystem.initRenderer(); DEFAULT_DRAW_BUFFER = RENDER_BACKEND.getInteger(GL11.GL_DRAW_BUFFER); // The initial mask value should be defined as all 1's. However, some drivers have it set to 0's. // To ensure consistency & correctness across all drivers, we're setting them to 0xFF. - RENDER_BACKEND.stencilFunc(stencilState.getFuncFront(), stencilState.getRefFront(), 0xFF); + RENDER_BACKEND.stencilFunc(glCtx.stencilState.getFuncFront(), glCtx.stencilState.getRefFront(), 0xFF); RENDER_BACKEND.stencilMask(0xFF); - // Compute stencil bit mask — driver clamps stencil masks to buffer depth + // Compute stencil bit mask - driver clamps stencil masks to buffer depth // GL_STENCIL_BITS was removed in core profile; query via default FBO attachment final int stencilBits = RENDER_BACKEND.getFramebufferAttachmentParameteri(GL30.GL_DRAW_FRAMEBUFFER, GL11.GL_STENCIL, GL30.GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE); - stencilBitMask = stencilBits >= 32 ? 0xFFFFFFFF : (1 << stencilBits) - 1; + glCtx.stencilBitMask = stencilBits >= 32 ? 0xFFFFFFFF : (1 << stencilBits) - 1; // Initialize stencil masks from computed bit mask - stencilState.setValueMaskFront(stencilBitMask); - stencilState.setValueMaskBack(stencilBitMask); - stencilState.setWriteMaskFront(stencilBitMask); - stencilState.setWriteMaskBack(stencilBitMask); + glCtx.stencilState.setValueMaskFront(glCtx.stencilBitMask); + glCtx.stencilState.setValueMaskBack(glCtx.stencilBitMask); + glCtx.stencilState.setWriteMaskFront(glCtx.stencilBitMask); + glCtx.stencilState.setWriteMaskBack(glCtx.stencilBitMask); final FloatBuffer lwRange = BufferUtils.createFloatBuffer(16); RENDER_BACKEND.getFloat(GL12.GL_ALIASED_LINE_WIDTH_RANGE, lwRange); @@ -649,25 +594,22 @@ public class GLStateManager { RENDER_BACKEND.vertexAttrib4f(1, 1.0f, 1.0f, 1.0f, 1.0f); // COLOR = white RENDER_BACKEND.vertexAttrib3f(4, 0.0f, 0.0f, 1.0f); // NORMAL = +Z - if (BYPASS_CACHE) { - LOGGER.info("GLStateManager cache bypassed"); - } - if (initConfig != null && initConfig.isLwjglDebug()) { + if (initConfig != null && (initConfig.isLwjglDebug() || CaptureGate.enabledAtStartup())) { if (RENDER_BACKEND.supportsDebugOutput()) { - LOGGER.info("Enabling additional LWJGL debug output"); - - GLDebug.setupDebugMessageCallback(); GLDebug.initDebugState(); - + if (initConfig.isLwjglDebug()) { + LOGGER.info("Enabling additional LWJGL debug output"); + GLDebug.setupDebugMessageCallback(); + } GLDebug.debugMessage("Angelica Debug Annotator Initialized"); } else { - LOGGER.info("LWJGL debug output requested but unavailable in this GL context (requires GL 4.3 or GL_KHR_debug); skipping"); + LOGGER.info("Debug annotations requested but unavailable in this context (requires GL 4.3 / GL_KHR_debug or SDL debug labels); skipping"); } } defaultVAO = RENDER_BACKEND.genVertexArrays(); RENDER_BACKEND.bindVertexArray(defaultVAO); - boundVAO = defaultVAO; + glCtx.boundVAO = defaultVAO; VAOManager.init(defaultVAO); if (defaultVAO != 0) { RENDER_BACKEND.provokingVertex(GL32.GL_LAST_VERTEX_CONVENTION); @@ -684,19 +626,9 @@ public class GLStateManager { } } - public static void assertMainThread() { - if (Thread.currentThread() != CurrentThread && !runningSplash) { - LOGGER.info("Call from not the Current Thread! - " + Thread.currentThread().getName() + " Current thread: " + CurrentThread.getName()); - } - } - - public static boolean shouldBypassCache() { - // Bypass cache when not using the main DrawableGL context - return BYPASS_CACHE || !isCachingEnabled(); - } - // LWJGL Overrides public static void glEnable(int cap) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordEnable(cap); @@ -706,22 +638,22 @@ public class GLStateManager { } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { - clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].enable(); - clipPlaneGeneration++; + glCtx.clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].enable(); + glCtx.clipPlaneGeneration++; return; } switch (cap) { case GL11.GL_ALPHA_TEST -> enableAlphaTest(); - case GL11.GL_AUTO_NORMAL -> autoNormalState.enable(); + case GL11.GL_AUTO_NORMAL -> glCtx.autoNormalState.enable(); case GL11.GL_BLEND -> enableBlend(); case GL11.GL_COLOR_MATERIAL -> enableColorMaterial(); - case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.enable(); + case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.enable(); case GL11.GL_CULL_FACE -> enableCull(); case GL11.GL_DEPTH_TEST -> enableDepthTest(); - case GL11.GL_DITHER -> ditherState.enable(); + case GL11.GL_DITHER -> glCtx.ditherState.enable(); case GL11.GL_FOG -> enableFog(); - case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.enable(); + case GL11.GL_INDEX_LOGIC_OP -> glCtx.indexLogicOpState.enable(); case GL11.GL_LIGHTING -> enableLighting(); case GL11.GL_LIGHT0 -> enableLight(0); case GL11.GL_LIGHT1 -> enableLight(1); @@ -731,52 +663,53 @@ public class GLStateManager { case GL11.GL_LIGHT5 -> enableLight(5); case GL11.GL_LIGHT6 -> enableLight(6); case GL11.GL_LIGHT7 -> enableLight(7); - case GL11.GL_LINE_SMOOTH -> lineSmoothState.enable(); - case GL11.GL_LINE_STIPPLE -> lineStippleState.enable(); - case GL11.GL_MAP1_COLOR_4 -> map1Color4State.enable(); - case GL11.GL_MAP1_INDEX -> map1IndexState.enable(); - case GL11.GL_MAP1_NORMAL -> map1NormalState.enable(); - case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.enable(); - case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.enable(); - case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.enable(); - case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.enable(); - case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.enable(); - case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.enable(); - case GL11.GL_MAP2_COLOR_4 -> map2Color4State.enable(); - case GL11.GL_MAP2_INDEX -> map2IndexState.enable(); - case GL11.GL_MAP2_NORMAL -> map2NormalState.enable(); - case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.enable(); - case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.enable(); - case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.enable(); - case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.enable(); - case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.enable(); - case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.enable(); - case GL13.GL_MULTISAMPLE -> multisampleState.enable(); - case GL11.GL_NORMALIZE -> normalizeState.enable(); - case GL11.GL_POINT_SMOOTH -> pointSmoothState.enable(); - case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.enable(); - case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.enable(); - case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.enable(); - case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.enable(); - case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.enable(); + case GL11.GL_LINE_SMOOTH -> glCtx.lineSmoothState.enable(); + case GL11.GL_LINE_STIPPLE -> glCtx.lineStippleState.enable(); + case GL11.GL_MAP1_COLOR_4 -> glCtx.map1Color4State.enable(); + case GL11.GL_MAP1_INDEX -> glCtx.map1IndexState.enable(); + case GL11.GL_MAP1_NORMAL -> glCtx.map1NormalState.enable(); + case GL11.GL_MAP1_TEXTURE_COORD_1 -> glCtx.map1TextureCoord1State.enable(); + case GL11.GL_MAP1_TEXTURE_COORD_2 -> glCtx.map1TextureCoord2State.enable(); + case GL11.GL_MAP1_TEXTURE_COORD_3 -> glCtx.map1TextureCoord3State.enable(); + case GL11.GL_MAP1_TEXTURE_COORD_4 -> glCtx.map1TextureCoord4State.enable(); + case GL11.GL_MAP1_VERTEX_3 -> glCtx.map1Vertex3State.enable(); + case GL11.GL_MAP1_VERTEX_4 -> glCtx.map1Vertex4State.enable(); + case GL11.GL_MAP2_COLOR_4 -> glCtx.map2Color4State.enable(); + case GL11.GL_MAP2_INDEX -> glCtx.map2IndexState.enable(); + case GL11.GL_MAP2_NORMAL -> glCtx.map2NormalState.enable(); + case GL11.GL_MAP2_TEXTURE_COORD_1 -> glCtx.map2TextureCoord1State.enable(); + case GL11.GL_MAP2_TEXTURE_COORD_2 -> glCtx.map2TextureCoord2State.enable(); + case GL11.GL_MAP2_TEXTURE_COORD_3 -> glCtx.map2TextureCoord3State.enable(); + case GL11.GL_MAP2_TEXTURE_COORD_4 -> glCtx.map2TextureCoord4State.enable(); + case GL11.GL_MAP2_VERTEX_3 -> glCtx.map2Vertex3State.enable(); + case GL11.GL_MAP2_VERTEX_4 -> glCtx.map2Vertex4State.enable(); + case GL13.GL_MULTISAMPLE -> glCtx.multisampleState.enable(); + case GL11.GL_NORMALIZE -> glCtx.normalizeState.enable(); + case GL11.GL_POINT_SMOOTH -> glCtx.pointSmoothState.enable(); + case GL11.GL_POLYGON_OFFSET_POINT -> glCtx.polygonOffsetPointState.enable(); + case GL11.GL_POLYGON_OFFSET_LINE -> glCtx.polygonOffsetLineState.enable(); + case GL11.GL_POLYGON_OFFSET_FILL -> glCtx.polygonOffsetFillState.enable(); + case GL11.GL_POLYGON_SMOOTH -> glCtx.polygonSmoothState.enable(); + case GL11.GL_POLYGON_STIPPLE -> glCtx.polygonStippleState.enable(); case GL12.GL_RESCALE_NORMAL -> enableRescaleNormal(); - case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.enable(); - case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.enable(); - case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.enable(); + case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> glCtx.sampleAlphaToCoverageState.enable(); + case GL13.GL_SAMPLE_ALPHA_TO_ONE -> glCtx.sampleAlphaToOneState.enable(); + case GL13.GL_SAMPLE_COVERAGE -> glCtx.sampleCoverageState.enable(); case GL11.GL_SCISSOR_TEST -> enableScissorTest(); - case GL11.GL_STENCIL_TEST -> stencilTest.enable(); - case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).enable(); + case GL11.GL_STENCIL_TEST -> glCtx.stencilTest.enable(); + case GL11.GL_TEXTURE_1D -> glCtx.textures.getTexture1DStates(glCtx.activeTextureUnit.getValue()).enable(); case GL11.GL_TEXTURE_2D -> enableTexture(); - case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).enable(); - case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).enable(); - case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).enable(); - case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).enable(); - case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).enable(); + case GL12.GL_TEXTURE_3D -> glCtx.textures.getTexture3DStates(glCtx.activeTextureUnit.getValue()).enable(); + case GL11.GL_TEXTURE_GEN_S -> glCtx.textures.getTexGenSStates(glCtx.activeTextureUnit.getValue()).enable(); + case GL11.GL_TEXTURE_GEN_T -> glCtx.textures.getTexGenTStates(glCtx.activeTextureUnit.getValue()).enable(); + case GL11.GL_TEXTURE_GEN_R -> glCtx.textures.getTexGenRStates(glCtx.activeTextureUnit.getValue()).enable(); + case GL11.GL_TEXTURE_GEN_Q -> glCtx.textures.getTexGenQStates(glCtx.activeTextureUnit.getValue()).enable(); default -> RENDER_BACKEND.enable(cap); } } public static void glDisable(int cap) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordDisable(cap); @@ -786,22 +719,22 @@ public class GLStateManager { } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { - clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].disable(); - clipPlaneGeneration++; + glCtx.clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].disable(); + glCtx.clipPlaneGeneration++; return; } switch (cap) { case GL11.GL_ALPHA_TEST -> disableAlphaTest(); - case GL11.GL_AUTO_NORMAL -> autoNormalState.disable(); + case GL11.GL_AUTO_NORMAL -> glCtx.autoNormalState.disable(); case GL11.GL_BLEND -> disableBlend(); case GL11.GL_COLOR_MATERIAL -> disableColorMaterial(); - case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.disable(); + case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.disable(); case GL11.GL_CULL_FACE -> disableCull(); case GL11.GL_DEPTH_TEST -> disableDepthTest(); - case GL11.GL_DITHER -> ditherState.disable(); + case GL11.GL_DITHER -> glCtx.ditherState.disable(); case GL11.GL_FOG -> disableFog(); - case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.disable(); + case GL11.GL_INDEX_LOGIC_OP -> glCtx.indexLogicOpState.disable(); case GL11.GL_LIGHTING -> disableLighting(); case GL11.GL_LIGHT0 -> disableLight(0); case GL11.GL_LIGHT1 -> disableLight(1); @@ -811,204 +744,207 @@ public class GLStateManager { case GL11.GL_LIGHT5 -> disableLight(5); case GL11.GL_LIGHT6 -> disableLight(6); case GL11.GL_LIGHT7 -> disableLight(7); - case GL11.GL_LINE_SMOOTH -> lineSmoothState.disable(); - case GL11.GL_LINE_STIPPLE -> lineStippleState.disable(); - case GL11.GL_MAP1_COLOR_4 -> map1Color4State.disable(); - case GL11.GL_MAP1_INDEX -> map1IndexState.disable(); - case GL11.GL_MAP1_NORMAL -> map1NormalState.disable(); - case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.disable(); - case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.disable(); - case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.disable(); - case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.disable(); - case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.disable(); - case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.disable(); - case GL11.GL_MAP2_COLOR_4 -> map2Color4State.disable(); - case GL11.GL_MAP2_INDEX -> map2IndexState.disable(); - case GL11.GL_MAP2_NORMAL -> map2NormalState.disable(); - case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.disable(); - case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.disable(); - case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.disable(); - case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.disable(); - case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.disable(); - case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.disable(); - case GL13.GL_MULTISAMPLE -> multisampleState.disable(); - case GL11.GL_NORMALIZE -> normalizeState.disable(); - case GL11.GL_POINT_SMOOTH -> pointSmoothState.disable(); - case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.disable(); - case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.disable(); - case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.disable(); - case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.disable(); - case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.disable(); + case GL11.GL_LINE_SMOOTH -> glCtx.lineSmoothState.disable(); + case GL11.GL_LINE_STIPPLE -> glCtx.lineStippleState.disable(); + case GL11.GL_MAP1_COLOR_4 -> glCtx.map1Color4State.disable(); + case GL11.GL_MAP1_INDEX -> glCtx.map1IndexState.disable(); + case GL11.GL_MAP1_NORMAL -> glCtx.map1NormalState.disable(); + case GL11.GL_MAP1_TEXTURE_COORD_1 -> glCtx.map1TextureCoord1State.disable(); + case GL11.GL_MAP1_TEXTURE_COORD_2 -> glCtx.map1TextureCoord2State.disable(); + case GL11.GL_MAP1_TEXTURE_COORD_3 -> glCtx.map1TextureCoord3State.disable(); + case GL11.GL_MAP1_TEXTURE_COORD_4 -> glCtx.map1TextureCoord4State.disable(); + case GL11.GL_MAP1_VERTEX_3 -> glCtx.map1Vertex3State.disable(); + case GL11.GL_MAP1_VERTEX_4 -> glCtx.map1Vertex4State.disable(); + case GL11.GL_MAP2_COLOR_4 -> glCtx.map2Color4State.disable(); + case GL11.GL_MAP2_INDEX -> glCtx.map2IndexState.disable(); + case GL11.GL_MAP2_NORMAL -> glCtx.map2NormalState.disable(); + case GL11.GL_MAP2_TEXTURE_COORD_1 -> glCtx.map2TextureCoord1State.disable(); + case GL11.GL_MAP2_TEXTURE_COORD_2 -> glCtx.map2TextureCoord2State.disable(); + case GL11.GL_MAP2_TEXTURE_COORD_3 -> glCtx.map2TextureCoord3State.disable(); + case GL11.GL_MAP2_TEXTURE_COORD_4 -> glCtx.map2TextureCoord4State.disable(); + case GL11.GL_MAP2_VERTEX_3 -> glCtx.map2Vertex3State.disable(); + case GL11.GL_MAP2_VERTEX_4 -> glCtx.map2Vertex4State.disable(); + case GL13.GL_MULTISAMPLE -> glCtx.multisampleState.disable(); + case GL11.GL_NORMALIZE -> glCtx.normalizeState.disable(); + case GL11.GL_POINT_SMOOTH -> glCtx.pointSmoothState.disable(); + case GL11.GL_POLYGON_OFFSET_POINT -> glCtx.polygonOffsetPointState.disable(); + case GL11.GL_POLYGON_OFFSET_LINE -> glCtx.polygonOffsetLineState.disable(); + case GL11.GL_POLYGON_OFFSET_FILL -> glCtx.polygonOffsetFillState.disable(); + case GL11.GL_POLYGON_SMOOTH -> glCtx.polygonSmoothState.disable(); + case GL11.GL_POLYGON_STIPPLE -> glCtx.polygonStippleState.disable(); case GL12.GL_RESCALE_NORMAL -> disableRescaleNormal(); - case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.disable(); - case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.disable(); - case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.disable(); + case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> glCtx.sampleAlphaToCoverageState.disable(); + case GL13.GL_SAMPLE_ALPHA_TO_ONE -> glCtx.sampleAlphaToOneState.disable(); + case GL13.GL_SAMPLE_COVERAGE -> glCtx.sampleCoverageState.disable(); case GL11.GL_SCISSOR_TEST -> disableScissorTest(); - case GL11.GL_STENCIL_TEST -> stencilTest.disable(); - case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).disable(); + case GL11.GL_STENCIL_TEST -> glCtx.stencilTest.disable(); + case GL11.GL_TEXTURE_1D -> glCtx.textures.getTexture1DStates(glCtx.activeTextureUnit.getValue()).disable(); case GL11.GL_TEXTURE_2D -> disableTexture(); - case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).disable(); - case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).disable(); - case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).disable(); - case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).disable(); - case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).disable(); + case GL12.GL_TEXTURE_3D -> glCtx.textures.getTexture3DStates(glCtx.activeTextureUnit.getValue()).disable(); + case GL11.GL_TEXTURE_GEN_S -> glCtx.textures.getTexGenSStates(glCtx.activeTextureUnit.getValue()).disable(); + case GL11.GL_TEXTURE_GEN_T -> glCtx.textures.getTexGenTStates(glCtx.activeTextureUnit.getValue()).disable(); + case GL11.GL_TEXTURE_GEN_R -> glCtx.textures.getTexGenRStates(glCtx.activeTextureUnit.getValue()).disable(); + case GL11.GL_TEXTURE_GEN_Q -> glCtx.textures.getTexGenQStates(glCtx.activeTextureUnit.getValue()).disable(); default -> RENDER_BACKEND.disable(cap); } } public static boolean glIsEnabled(int cap) { - if (shouldBypassCache()) { + final GLContextState glCtx = ctx(); + if (!isCachingEnabled()) { return RENDER_BACKEND.getBoolean(cap); } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { - return clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].isEnabled(); + return glCtx.clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].isEnabled(); } return switch (cap) { - case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled(); - case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled(); - case GL11.GL_BLEND -> blendMode.isEnabled(); - case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled(); - case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled(); - case GL11.GL_CULL_FACE -> cullState.isEnabled(); - case GL11.GL_DEPTH_TEST -> depthTest.isEnabled(); - case GL11.GL_DITHER -> ditherState.isEnabled(); - case GL11.GL_FOG -> fogMode.isEnabled(); - case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled(); - case GL11.GL_LIGHTING -> lightingState.isEnabled(); - case GL11.GL_LIGHT0 -> lightStates[0].isEnabled(); - case GL11.GL_LIGHT1 -> lightStates[1].isEnabled(); - case GL11.GL_LIGHT2 -> lightStates[2].isEnabled(); - case GL11.GL_LIGHT3 -> lightStates[3].isEnabled(); - case GL11.GL_LIGHT4 -> lightStates[4].isEnabled(); - case GL11.GL_LIGHT5 -> lightStates[5].isEnabled(); - case GL11.GL_LIGHT6 -> lightStates[6].isEnabled(); - case GL11.GL_LIGHT7 -> lightStates[7].isEnabled(); - case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled(); - case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled(); - case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled(); - case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled(); - case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled(); - case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled(); - case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled(); - case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled(); - case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled(); - case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled(); - case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled(); - case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled(); - case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled(); - case GL11.GL_NORMALIZE -> normalizeState.isEnabled(); - case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled(); - case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled(); - case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled(); - case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled(); - case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled(); - case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled(); - case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled(); - case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled(); - case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled(); - case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled(); - case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_ALPHA_TEST -> glCtx.alphaTest.isEnabled(); + case GL11.GL_AUTO_NORMAL -> glCtx.autoNormalState.isEnabled(); + case GL11.GL_BLEND -> glCtx.blendMode.isEnabled(); + case GL11.GL_COLOR_MATERIAL -> glCtx.colorMaterial.isEnabled(); + case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.isEnabled(); + case GL11.GL_CULL_FACE -> glCtx.cullState.isEnabled(); + case GL11.GL_DEPTH_TEST -> glCtx.depthTest.isEnabled(); + case GL11.GL_DITHER -> glCtx.ditherState.isEnabled(); + case GL11.GL_FOG -> glCtx.fogMode.isEnabled(); + case GL11.GL_INDEX_LOGIC_OP -> glCtx.indexLogicOpState.isEnabled(); + case GL11.GL_LIGHTING -> glCtx.lightingState.isEnabled(); + case GL11.GL_LIGHT0 -> glCtx.lightStates[0].isEnabled(); + case GL11.GL_LIGHT1 -> glCtx.lightStates[1].isEnabled(); + case GL11.GL_LIGHT2 -> glCtx.lightStates[2].isEnabled(); + case GL11.GL_LIGHT3 -> glCtx.lightStates[3].isEnabled(); + case GL11.GL_LIGHT4 -> glCtx.lightStates[4].isEnabled(); + case GL11.GL_LIGHT5 -> glCtx.lightStates[5].isEnabled(); + case GL11.GL_LIGHT6 -> glCtx.lightStates[6].isEnabled(); + case GL11.GL_LIGHT7 -> glCtx.lightStates[7].isEnabled(); + case GL11.GL_LINE_SMOOTH -> glCtx.lineSmoothState.isEnabled(); + case GL11.GL_LINE_STIPPLE -> glCtx.lineStippleState.isEnabled(); + case GL11.GL_MAP1_COLOR_4 -> glCtx.map1Color4State.isEnabled(); + case GL11.GL_MAP1_INDEX -> glCtx.map1IndexState.isEnabled(); + case GL11.GL_MAP1_NORMAL -> glCtx.map1NormalState.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_1 -> glCtx.map1TextureCoord1State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_2 -> glCtx.map1TextureCoord2State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_3 -> glCtx.map1TextureCoord3State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_4 -> glCtx.map1TextureCoord4State.isEnabled(); + case GL11.GL_MAP1_VERTEX_3 -> glCtx.map1Vertex3State.isEnabled(); + case GL11.GL_MAP1_VERTEX_4 -> glCtx.map1Vertex4State.isEnabled(); + case GL11.GL_MAP2_COLOR_4 -> glCtx.map2Color4State.isEnabled(); + case GL11.GL_MAP2_INDEX -> glCtx.map2IndexState.isEnabled(); + case GL11.GL_MAP2_NORMAL -> glCtx.map2NormalState.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_1 -> glCtx.map2TextureCoord1State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_2 -> glCtx.map2TextureCoord2State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_3 -> glCtx.map2TextureCoord3State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_4 -> glCtx.map2TextureCoord4State.isEnabled(); + case GL11.GL_MAP2_VERTEX_3 -> glCtx.map2Vertex3State.isEnabled(); + case GL11.GL_MAP2_VERTEX_4 -> glCtx.map2Vertex4State.isEnabled(); + case GL13.GL_MULTISAMPLE -> glCtx.multisampleState.isEnabled(); + case GL11.GL_NORMALIZE -> glCtx.normalizeState.isEnabled(); + case GL11.GL_POINT_SMOOTH -> glCtx.pointSmoothState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_POINT -> glCtx.polygonOffsetPointState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_LINE -> glCtx.polygonOffsetLineState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_FILL -> glCtx.polygonOffsetFillState.isEnabled(); + case GL11.GL_POLYGON_SMOOTH -> glCtx.polygonSmoothState.isEnabled(); + case GL11.GL_POLYGON_STIPPLE -> glCtx.polygonStippleState.isEnabled(); + case GL12.GL_RESCALE_NORMAL -> glCtx.rescaleNormalState.isEnabled(); + case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> glCtx.sampleAlphaToCoverageState.isEnabled(); + case GL13.GL_SAMPLE_ALPHA_TO_ONE -> glCtx.sampleAlphaToOneState.isEnabled(); + case GL13.GL_SAMPLE_COVERAGE -> glCtx.sampleCoverageState.isEnabled(); + case GL11.GL_SCISSOR_TEST -> glCtx.scissorTest.isEnabled(); + case GL11.GL_STENCIL_TEST -> glCtx.stencilTest.isEnabled(); + case GL11.GL_TEXTURE_1D -> glCtx.textures.getTexture1DStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_2D -> glCtx.textures.getTextureUnitStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL12.GL_TEXTURE_3D -> glCtx.textures.getTexture3DStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_S -> glCtx.textures.getTexGenSStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_T -> glCtx.textures.getTexGenTStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_R -> glCtx.textures.getTexGenRStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_Q -> glCtx.textures.getTexGenQStates(glCtx.activeTextureUnit.getValue()).isEnabled(); default -> RENDER_BACKEND.getBoolean(cap); }; } public static boolean glGetBoolean(int pname) { - if (shouldBypassCache()) { + final GLContextState glCtx = ctx(); + if (!isCachingEnabled()) { return RENDER_BACKEND.getBoolean(pname); } // Handle clip planes dynamically (supports up to MAX_CLIP_PLANES) if (pname >= GL11.GL_CLIP_PLANE0 && pname < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) { - return clipPlaneStates[pname - GL11.GL_CLIP_PLANE0].isEnabled(); + return glCtx.clipPlaneStates[pname - GL11.GL_CLIP_PLANE0].isEnabled(); } return switch (pname) { - case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled(); - case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled(); - case GL11.GL_BLEND -> blendMode.isEnabled(); - case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled(); - case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled(); - case GL11.GL_CULL_FACE -> cullState.isEnabled(); - case GL11.GL_DEPTH_TEST -> depthTest.isEnabled(); - case GL11.GL_DEPTH_WRITEMASK -> depthState.isEnabled(); - case GL11.GL_DITHER -> ditherState.isEnabled(); - case GL11.GL_FOG -> fogMode.isEnabled(); - case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled(); - case GL11.GL_LIGHTING -> lightingState.isEnabled(); - case GL11.GL_LIGHT0 -> lightStates[0].isEnabled(); - case GL11.GL_LIGHT1 -> lightStates[1].isEnabled(); - case GL11.GL_LIGHT2 -> lightStates[2].isEnabled(); - case GL11.GL_LIGHT3 -> lightStates[3].isEnabled(); - case GL11.GL_LIGHT4 -> lightStates[4].isEnabled(); - case GL11.GL_LIGHT5 -> lightStates[5].isEnabled(); - case GL11.GL_LIGHT6 -> lightStates[6].isEnabled(); - case GL11.GL_LIGHT7 -> lightStates[7].isEnabled(); - case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled(); - case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled(); - case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled(); - case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled(); - case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled(); - case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled(); - case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled(); - case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled(); - case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled(); - case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled(); - case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled(); - case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled(); - case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled(); - case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled(); - case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled(); - case GL11.GL_NORMALIZE -> normalizeState.isEnabled(); - case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled(); - case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled(); - case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled(); - case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled(); - case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled(); - case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled(); - case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled(); - case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled(); - case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled(); - case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled(); - case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled(); - case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled(); - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.localViewer != 0.0f; - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.twoSide != 0.0f; + case GL11.GL_ALPHA_TEST -> glCtx.alphaTest.isEnabled(); + case GL11.GL_AUTO_NORMAL -> glCtx.autoNormalState.isEnabled(); + case GL11.GL_BLEND -> glCtx.blendMode.isEnabled(); + case GL11.GL_COLOR_MATERIAL -> glCtx.colorMaterial.isEnabled(); + case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.isEnabled(); + case GL11.GL_CULL_FACE -> glCtx.cullState.isEnabled(); + case GL11.GL_DEPTH_TEST -> glCtx.depthTest.isEnabled(); + case GL11.GL_DEPTH_WRITEMASK -> glCtx.depthState.isEnabled(); + case GL11.GL_DITHER -> glCtx.ditherState.isEnabled(); + case GL11.GL_FOG -> glCtx.fogMode.isEnabled(); + case GL11.GL_INDEX_LOGIC_OP -> glCtx.indexLogicOpState.isEnabled(); + case GL11.GL_LIGHTING -> glCtx.lightingState.isEnabled(); + case GL11.GL_LIGHT0 -> glCtx.lightStates[0].isEnabled(); + case GL11.GL_LIGHT1 -> glCtx.lightStates[1].isEnabled(); + case GL11.GL_LIGHT2 -> glCtx.lightStates[2].isEnabled(); + case GL11.GL_LIGHT3 -> glCtx.lightStates[3].isEnabled(); + case GL11.GL_LIGHT4 -> glCtx.lightStates[4].isEnabled(); + case GL11.GL_LIGHT5 -> glCtx.lightStates[5].isEnabled(); + case GL11.GL_LIGHT6 -> glCtx.lightStates[6].isEnabled(); + case GL11.GL_LIGHT7 -> glCtx.lightStates[7].isEnabled(); + case GL11.GL_LINE_SMOOTH -> glCtx.lineSmoothState.isEnabled(); + case GL11.GL_LINE_STIPPLE -> glCtx.lineStippleState.isEnabled(); + case GL11.GL_MAP1_COLOR_4 -> glCtx.map1Color4State.isEnabled(); + case GL11.GL_MAP1_INDEX -> glCtx.map1IndexState.isEnabled(); + case GL11.GL_MAP1_NORMAL -> glCtx.map1NormalState.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_1 -> glCtx.map1TextureCoord1State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_2 -> glCtx.map1TextureCoord2State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_3 -> glCtx.map1TextureCoord3State.isEnabled(); + case GL11.GL_MAP1_TEXTURE_COORD_4 -> glCtx.map1TextureCoord4State.isEnabled(); + case GL11.GL_MAP1_VERTEX_3 -> glCtx.map1Vertex3State.isEnabled(); + case GL11.GL_MAP1_VERTEX_4 -> glCtx.map1Vertex4State.isEnabled(); + case GL11.GL_MAP2_COLOR_4 -> glCtx.map2Color4State.isEnabled(); + case GL11.GL_MAP2_INDEX -> glCtx.map2IndexState.isEnabled(); + case GL11.GL_MAP2_NORMAL -> glCtx.map2NormalState.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_1 -> glCtx.map2TextureCoord1State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_2 -> glCtx.map2TextureCoord2State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_3 -> glCtx.map2TextureCoord3State.isEnabled(); + case GL11.GL_MAP2_TEXTURE_COORD_4 -> glCtx.map2TextureCoord4State.isEnabled(); + case GL11.GL_MAP2_VERTEX_3 -> glCtx.map2Vertex3State.isEnabled(); + case GL11.GL_MAP2_VERTEX_4 -> glCtx.map2Vertex4State.isEnabled(); + case GL13.GL_MULTISAMPLE -> glCtx.multisampleState.isEnabled(); + case GL11.GL_NORMALIZE -> glCtx.normalizeState.isEnabled(); + case GL11.GL_POINT_SMOOTH -> glCtx.pointSmoothState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_POINT -> glCtx.polygonOffsetPointState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_LINE -> glCtx.polygonOffsetLineState.isEnabled(); + case GL11.GL_POLYGON_OFFSET_FILL -> glCtx.polygonOffsetFillState.isEnabled(); + case GL11.GL_POLYGON_SMOOTH -> glCtx.polygonSmoothState.isEnabled(); + case GL11.GL_POLYGON_STIPPLE -> glCtx.polygonStippleState.isEnabled(); + case GL12.GL_RESCALE_NORMAL -> glCtx.rescaleNormalState.isEnabled(); + case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> glCtx.sampleAlphaToCoverageState.isEnabled(); + case GL13.GL_SAMPLE_ALPHA_TO_ONE -> glCtx.sampleAlphaToOneState.isEnabled(); + case GL13.GL_SAMPLE_COVERAGE -> glCtx.sampleCoverageState.isEnabled(); + case GL11.GL_SCISSOR_TEST -> glCtx.scissorTest.isEnabled(); + case GL11.GL_STENCIL_TEST -> glCtx.stencilTest.isEnabled(); + case GL11.GL_TEXTURE_1D -> glCtx.textures.getTexture1DStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_2D -> glCtx.textures.getTextureUnitStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL12.GL_TEXTURE_3D -> glCtx.textures.getTexture3DStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_S -> glCtx.textures.getTexGenSStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_T -> glCtx.textures.getTexGenTStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_R -> glCtx.textures.getTexGenRStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_TEXTURE_GEN_Q -> glCtx.textures.getTexGenQStates(glCtx.activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> glCtx.lightModel.localViewer != 0.0f; + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> glCtx.lightModel.twoSide != 0.0f; default -> RENDER_BACKEND.getBoolean(pname); }; } public static void glGetBoolean(int pname, ByteBuffer params) { - if (shouldBypassCache()) { + final GLContextState glCtx = ctx(); + if (!isCachingEnabled()) { RENDER_BACKEND.getBoolean(pname, params); return; } @@ -1016,10 +952,10 @@ public class GLStateManager { switch (pname) { case GL11.GL_COLOR_WRITEMASK -> { final int pos = params.position(); - params.put(pos, (byte) (colorMask.red ? GL11.GL_TRUE : GL11.GL_FALSE)); - params.put(pos + 1, (byte) (colorMask.green ? GL11.GL_TRUE : GL11.GL_FALSE)); - params.put(pos + 2, (byte) (colorMask.blue ? GL11.GL_TRUE : GL11.GL_FALSE)); - params.put(pos + 3, (byte) (colorMask.alpha ? GL11.GL_TRUE : GL11.GL_FALSE)); + params.put(pos, (byte) (glCtx.colorMask.red ? GL11.GL_TRUE : GL11.GL_FALSE)); + params.put(pos + 1, (byte) (glCtx.colorMask.green ? GL11.GL_TRUE : GL11.GL_FALSE)); + params.put(pos + 2, (byte) (glCtx.colorMask.blue ? GL11.GL_TRUE : GL11.GL_FALSE)); + params.put(pos + 3, (byte) (glCtx.colorMask.alpha ? GL11.GL_TRUE : GL11.GL_FALSE)); } default -> { if (!HAS_MULTIPLE_SET.contains(pname)) { @@ -1038,81 +974,90 @@ public class GLStateManager { } public static int glGetInteger(int pname) { - if (shouldBypassCache()) { + final GLContextState glCtx = ctx(); + if (!isCachingEnabled()) { return RENDER_BACKEND.getInteger(pname); } return switch (pname) { - case GL11.GL_ALPHA_TEST_FUNC -> alphaState.getFunction(); - case GL11.GL_DEPTH_FUNC -> depthState.getFunc(); - case GL11.GL_LIST_BASE -> listBase; + case GL11.GL_ALPHA_TEST_FUNC -> glCtx.alphaState.getFunction(); + case GL11.GL_DEPTH_FUNC -> glCtx.depthState.getFunc(); + case GL11.GL_LIST_BASE -> glCtx.listBase; case GL11.GL_LIST_MODE -> DisplayListManager.getListMode(); - case GL11.GL_MATRIX_MODE -> matrixMode.getMode(); - case GL11.GL_SHADE_MODEL -> shadeModelState.getValue(); + case GL11.GL_MATRIX_MODE -> glCtx.matrixMode.getMode(); + case GL11.GL_SHADE_MODEL -> glCtx.shadeModelState.getValue(); // GL_TEXTURE_2D makes no sense here, but some mod still queries it... case GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_BINDING_2D -> getBoundTextureForServerState(); case GL13.GL_ACTIVE_TEXTURE -> GL13.GL_TEXTURE0 + getActiveTextureUnitForServerState(); - case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue(); - case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue(); - case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix); - case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix); + case GL11.GL_COLOR_MATERIAL_FACE -> glCtx.colorMaterialFace.getValue(); + case GL11.GL_COLOR_MATERIAL_PARAMETER -> glCtx.colorMaterialParameter.getValue(); + case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(glCtx.modelViewMatrix); + case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(glCtx.projectionMatrix); + case GL11.GL_DEPTH_WRITEMASK -> glCtx.depthState.isEnabled() ? GL11.GL_TRUE : GL11.GL_FALSE; + case GL11.GL_CULL_FACE_MODE -> glCtx.polygonState.getCullFaceMode(); + case GL11.GL_FRONT_FACE -> glCtx.polygonState.getFrontFace(); + case GL11.GL_POLYGON_MODE -> glCtx.polygonState.getFrontMode(); + case GL11.GL_UNPACK_ALIGNMENT -> glCtx.pixelUnpackState.alignment(); + case GL11.GL_UNPACK_ROW_LENGTH -> glCtx.pixelUnpackState.rowLength(); + case GL11.GL_UNPACK_SKIP_ROWS -> glCtx.pixelUnpackState.skipRows(); + case GL11.GL_UNPACK_SKIP_PIXELS -> glCtx.pixelUnpackState.skipPixels(); - case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.colorControl; + case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> glCtx.lightModel.colorControl; - case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha(); - case GL11.GL_BLEND_DST, GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb(); - case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha(); - case GL11.GL_BLEND_SRC, GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb(); - case GL14.GL_BLEND_EQUATION -> blendState.getEquationRgb(); - case GL20.GL_BLEND_EQUATION_ALPHA -> blendState.getEquationAlpha(); + case GL14.GL_BLEND_DST_ALPHA -> glCtx.blendState.getDstAlpha(); + case GL11.GL_BLEND_DST, GL14.GL_BLEND_DST_RGB -> glCtx.blendState.getDstRgb(); + case GL14.GL_BLEND_SRC_ALPHA -> glCtx.blendState.getSrcAlpha(); + case GL11.GL_BLEND_SRC, GL14.GL_BLEND_SRC_RGB -> glCtx.blendState.getSrcRgb(); + case GL14.GL_BLEND_EQUATION -> glCtx.blendState.getEquationRgb(); + case GL20.GL_BLEND_EQUATION_ALPHA -> glCtx.blendState.getEquationAlpha(); - case GL11.GL_LOGIC_OP_MODE -> logicOpMode.getValue(); - case GL11.GL_DRAW_BUFFER -> drawBuffer.getValue(); + case GL11.GL_LOGIC_OP_MODE -> glCtx.logicOpMode.getValue(); + case GL11.GL_DRAW_BUFFER -> glCtx.drawBuffer.getValue(); - case GL11.GL_CULL_FACE_MODE -> polygonState.getCullFaceMode(); - case GL11.GL_FRONT_FACE -> polygonState.getFrontFace(); + case GL11.GL_STENCIL_FUNC -> glCtx.stencilState.getFuncFront(); + case GL11.GL_STENCIL_REF -> glCtx.stencilState.getRefFront(); + case GL11.GL_STENCIL_VALUE_MASK -> glCtx.stencilState.getValueMaskFront(); + case GL11.GL_STENCIL_FAIL -> glCtx.stencilState.getFailOpFront(); + case GL11.GL_STENCIL_PASS_DEPTH_FAIL -> glCtx.stencilState.getZFailOpFront(); + case GL11.GL_STENCIL_PASS_DEPTH_PASS -> glCtx.stencilState.getZPassOpFront(); + case GL11.GL_STENCIL_WRITEMASK -> glCtx.stencilState.getWriteMaskFront(); + case GL11.GL_STENCIL_CLEAR_VALUE -> glCtx.stencilState.getClearValue(); - case GL11.GL_STENCIL_FUNC -> stencilState.getFuncFront(); - case GL11.GL_STENCIL_REF -> stencilState.getRefFront(); - case GL11.GL_STENCIL_VALUE_MASK -> stencilState.getValueMaskFront(); - case GL11.GL_STENCIL_FAIL -> stencilState.getFailOpFront(); - case GL11.GL_STENCIL_PASS_DEPTH_FAIL -> stencilState.getZFailOpFront(); - case GL11.GL_STENCIL_PASS_DEPTH_PASS -> stencilState.getZPassOpFront(); - case GL11.GL_STENCIL_WRITEMASK -> stencilState.getWriteMaskFront(); - case GL11.GL_STENCIL_CLEAR_VALUE -> stencilState.getClearValue(); - - case GL15.GL_ARRAY_BUFFER_BINDING -> boundVBO; + case GL15.GL_ARRAY_BUFFER_BINDING -> glCtx.boundVBO; case GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING -> VAOManager.boundEBO; - case GL21.GL_PIXEL_UNPACK_BUFFER_BINDING -> boundPixelUnpackBuffer; - case GL21.GL_PIXEL_PACK_BUFFER_BINDING -> boundPixelPackBuffer; + case GL21.GL_PIXEL_UNPACK_BUFFER_BINDING -> glCtx.boundPixelUnpackBuffer; + case GL21.GL_PIXEL_PACK_BUFFER_BINDING -> glCtx.boundPixelPackBuffer; - case GL20.GL_CURRENT_PROGRAM -> activeProgram; + case GL20.GL_CURRENT_PROGRAM -> glCtx.activeProgram; - case GL30.GL_VERTEX_ARRAY_BINDING -> boundVAO; + case GL30.GL_VERTEX_ARRAY_BINDING -> glCtx.boundVAO; - case GL30.GL_DRAW_FRAMEBUFFER_BINDING -> drawFramebuffer; - case GL30.GL_READ_FRAMEBUFFER_BINDING -> readFramebuffer; + case GL30.GL_DRAW_FRAMEBUFFER_BINDING -> glCtx.drawFramebuffer; + case GL30.GL_READ_FRAMEBUFFER_BINDING -> glCtx.readFramebuffer; default -> switch (pname) { - case GL11.GL_FOG_MODE -> fogState.getFogMode(); - case GL11.GL_LINE_STIPPLE_PATTERN -> lineState.getStipplePattern() & 0xFFFF; - case GL11.GL_LINE_STIPPLE_REPEAT -> lineState.getStippleFactor(); + case GL11.GL_FOG_MODE -> glCtx.fogState.getFogMode(); + case GL11.GL_LINE_STIPPLE_PATTERN -> glCtx.lineState.getStipplePattern() & 0xFFFF; + case GL11.GL_LINE_STIPPLE_REPEAT -> glCtx.lineState.getStippleFactor(); + case GL11.GL_LIST_INDEX -> DisplayListManager.isRecording() ? Math.max(DisplayListManager.getRecordingListId(), 0) : 0; default -> RENDER_BACKEND.getInteger(pname); }; }; } public static void glGetInteger(int pname, IntBuffer params) { - if (shouldBypassCache()) { + if (!isCachingEnabled()) { RENDER_BACKEND.getInteger(pname, params); return; } switch (pname) { - case GL11.GL_VIEWPORT -> viewportState.get(params); + case GL11.GL_VIEWPORT -> ctx().viewportState.get(params); case GL11.GL_POLYGON_MODE -> { - params.put(0, polygonState.getFrontMode()); - params.put(1, polygonState.getBackMode()); + final PolygonState polygon = ctx().polygonState; + final int pos = params.position(); + params.put(pos, polygon.getFrontMode()); + params.put(pos + 1, polygon.getBackMode()); } default -> { if (!HAS_MULTIPLE_SET.contains(pname)) { @@ -1125,11 +1070,12 @@ public class GLStateManager { } public static void glGetMaterial(int face, int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); final MaterialStateStack state; if (face == GL11.GL_FRONT) { - state = frontMaterial; + state = glCtx.frontMaterial; } else if (face == GL11.GL_BACK) { - state = backMaterial; + state = glCtx.backMaterial; } else { throw new RuntimeException("Invalid face parameter specified to glGetMaterial: " + face); } @@ -1147,7 +1093,7 @@ public class GLStateManager { } public static void glGetLight(int light, int pname, FloatBuffer params) { - final LightStateStack state = lightDataStates[light - GL11.GL_LIGHT0]; + final LightStateStack state = ctx().lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { case GL11.GL_AMBIENT -> state.ambient.get(0, params); case GL11.GL_DIFFUSE -> state.diffuse.get(0, params); @@ -1165,28 +1111,29 @@ public class GLStateManager { } public static void glGetFloat(int pname, FloatBuffer params) { - if (shouldBypassCache()) { + final GLContextState glCtx = ctx(); + if (!isCachingEnabled()) { RENDER_BACKEND.getFloat(pname, params); return; } switch (pname) { - case GL11.GL_MODELVIEW_MATRIX -> modelViewMatrix.get(0, params); - case GL11.GL_PROJECTION_MATRIX -> projectionMatrix.get(0, params); - case GL11.GL_TEXTURE_MATRIX -> textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params); - case GL11.GL_COLOR_CLEAR_VALUE -> clearColor.get(params); - case GL11.GL_CURRENT_COLOR -> color.get(params); + case GL11.GL_MODELVIEW_MATRIX -> glCtx.modelViewMatrix.get(0, params); + case GL11.GL_PROJECTION_MATRIX -> glCtx.projectionMatrix.get(0, params); + case GL11.GL_TEXTURE_MATRIX -> glCtx.textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params); + case GL11.GL_COLOR_CLEAR_VALUE -> glCtx.clearColor.get(params); + case GL11.GL_CURRENT_COLOR -> glCtx.color.get(params); case GL11.GL_DEPTH_RANGE -> { final int pos = params.position(); - params.put(pos, (float) viewportState.depthRangeNear); - params.put(pos + 1, (float) viewportState.depthRangeFar); + params.put(pos, (float) glCtx.viewportState.depthRangeNear); + params.put(pos + 1, (float) glCtx.viewportState.depthRangeFar); } case GL14.GL_BLEND_COLOR -> { final int pos = params.position(); - params.put(pos, blendState.getBlendColorR()); - params.put(pos + 1, blendState.getBlendColorG()); - params.put(pos + 2, blendState.getBlendColorB()); - params.put(pos + 3, blendState.getBlendColorA()); + params.put(pos, glCtx.blendState.getBlendColorR()); + params.put(pos + 1, glCtx.blendState.getBlendColorG()); + params.put(pos + 2, glCtx.blendState.getBlendColorB()); + params.put(pos + 3, glCtx.blendState.getBlendColorA()); } case GL11.GL_CURRENT_NORMAL -> { final Vector3f normal = ShaderManager.getCurrentNormal(); @@ -1204,14 +1151,14 @@ public class GLStateManager { params.put(pos + 3, tc.w); } case GL11.GL_FOG_COLOR -> { - final FloatBuffer fogBuf = fogState.getFogColorBuffer(); + final FloatBuffer fogBuf = glCtx.fogState.getFogColorBuffer(); final int pos = params.position(); params.put(pos, fogBuf.get(0)); params.put(pos + 1, fogBuf.get(1)); params.put(pos + 2, fogBuf.get(2)); params.put(pos + 3, fogBuf.get(3)); } - case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.ambient.get(0, params); + case GL11.GL_LIGHT_MODEL_AMBIENT -> glCtx.lightModel.ambient.get(0, params); default -> { if (!HAS_MULTIPLE_SET.contains(pname)) { params.put(0, glGetFloat(pname)); @@ -1223,14 +1170,15 @@ public class GLStateManager { } public static float glGetFloat(int pname) { + final GLContextState glCtx = ctx(); return switch (pname) { - case GL11.GL_ALPHA_TEST_REF -> alphaState.getReference(); - case GL11.GL_FOG_DENSITY -> fogState.getDensity(); - case GL11.GL_FOG_START -> fogState.getStart(); - case GL11.GL_FOG_END -> fogState.getEnd(); - case GL11.GL_DEPTH_CLEAR_VALUE -> (float) depthState.getClearValue(); - case GL11.GL_LINE_WIDTH -> lineState.getWidth(); - case GL11.GL_POINT_SIZE -> pointState.getSize(); + case GL11.GL_ALPHA_TEST_REF -> glCtx.alphaState.getReference(); + case GL11.GL_FOG_DENSITY -> glCtx.fogState.getDensity(); + case GL11.GL_FOG_START -> glCtx.fogState.getStart(); + case GL11.GL_FOG_END -> glCtx.fogState.getEnd(); + case GL11.GL_DEPTH_CLEAR_VALUE -> (float) glCtx.depthState.getClearValue(); + case GL11.GL_LINE_WIDTH -> glCtx.lineState.getWidth(); + case GL11.GL_POINT_SIZE -> glCtx.pointState.getSize(); default -> RENDER_BACKEND.getFloat(pname); }; } @@ -1254,6 +1202,7 @@ public class GLStateManager { // GLStateManager Functions public static void glBlendColor(float red, float green, float blue, float alpha) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordBlendColor(red, green, blue, alpha); @@ -1262,14 +1211,12 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || red != blendState.getBlendColorR() || green != blendState.getBlendColorG() || blue != blendState.getBlendColorB() || alpha != blendState.getBlendColorA()) { - if (caching) { - blendState.setBlendColorR(red); - blendState.setBlendColorG(green); - blendState.setBlendColorB(blue); - blendState.setBlendColorA(alpha); - } + final boolean bypass = !caching; + if (bypass || red != glCtx.blendState.getBlendColorR() || green != glCtx.blendState.getBlendColorG() || blue != glCtx.blendState.getBlendColorB() || alpha != glCtx.blendState.getBlendColorA()) { + glCtx.blendState.setBlendColorR(red); + glCtx.blendState.setBlendColorG(green); + glCtx.blendState.setBlendColorB(blue); + glCtx.blendState.setBlendColorA(alpha); RENDER_BACKEND.blendColor(red, green, blue, alpha); } } @@ -1287,7 +1234,7 @@ public class GLStateManager { bh.deferBlendModeToggle(true); return; } - blendMode.enable(); + ctx().blendMode.enable(); } public static void disableBlend() { @@ -1303,7 +1250,7 @@ public class GLStateManager { bh.deferBlendModeToggle(false); return; } - blendMode.disable(); + ctx().blendMode.disable(); } public static void enableScissorTest() { @@ -1314,7 +1261,7 @@ public class GLStateManager { return; } } - scissorTest.enable(); + ctx().scissorTest.enable(); } public static void disableScissorTest() { @@ -1325,10 +1272,11 @@ public class GLStateManager { return; } } - scissorTest.disable(); + ctx().scissorTest.disable(); } public static void glBlendFunc(int srcFactor, int dstFactor) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor); @@ -1341,10 +1289,9 @@ public class GLStateManager { bh.deferBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor); return; } - // Cache thread check - only update state on main thread, but always make GL call if needed final boolean caching = isCachingEnabled(); if (GLSMConfig.hudCacheOverride) { - if (caching) blendState.setAll(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); + glCtx.blendState.setAll(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); RENDER_BACKEND.blendFuncSeparate(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); if (GLSMHooks.BLEND_FUNC_CHANGE.hasListeners()) { GLSMHooks.blendFuncChangeEvent.srcRgb = srcFactor; @@ -1355,13 +1302,13 @@ public class GLStateManager { } return; } - final boolean bypass = BYPASS_CACHE || !caching; + final boolean bypass = !caching; if (bypass - || blendState.getSrcRgb() != srcFactor - || blendState.getDstRgb() != dstFactor - || blendState.getSrcAlpha() != srcFactor - || blendState.getDstAlpha() != dstFactor) { - if (caching) blendState.setAll(srcFactor, dstFactor, srcFactor, dstFactor); + || glCtx.blendState.getSrcRgb() != srcFactor + || glCtx.blendState.getDstRgb() != dstFactor + || glCtx.blendState.getSrcAlpha() != srcFactor + || glCtx.blendState.getDstAlpha() != dstFactor) { + glCtx.blendState.setAll(srcFactor, dstFactor, srcFactor, dstFactor); RENDER_BACKEND.blendFunc(srcFactor, dstFactor); if (GLSMHooks.BLEND_FUNC_CHANGE.hasListeners()) { GLSMHooks.blendFuncChangeEvent.srcRgb = srcFactor; @@ -1374,36 +1321,35 @@ public class GLStateManager { } public static void glBlendEquation(int mode) { + final GLContextState glCtx = ctx(); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glBlendEquation"); } final boolean caching = isCachingEnabled(); - final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || blendState.getEquationRgb() != mode || blendState.getEquationAlpha() != mode) { - if (caching) { - blendState.setEquationRgb(mode); - blendState.setEquationAlpha(mode); - } + final boolean bypass = !caching; + if (bypass || glCtx.blendState.getEquationRgb() != mode || glCtx.blendState.getEquationAlpha() != mode) { + glCtx.blendState.setEquationRgb(mode); + glCtx.blendState.setEquationAlpha(mode); RENDER_BACKEND.blendEquation(mode); } } public static void glBlendEquationSeparate(int modeRGB, int modeAlpha) { + final GLContextState glCtx = ctx(); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glBlendEquationSeparate"); } final boolean caching = isCachingEnabled(); - final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || blendState.getEquationRgb() != modeRGB || blendState.getEquationAlpha() != modeAlpha) { - if (caching) { - blendState.setEquationRgb(modeRGB); - blendState.setEquationAlpha(modeAlpha); - } + final boolean bypass = !caching; + if (bypass || glCtx.blendState.getEquationRgb() != modeRGB || glCtx.blendState.getEquationAlpha() != modeAlpha) { + glCtx.blendState.setEquationRgb(modeRGB); + glCtx.blendState.setEquationAlpha(modeAlpha); RENDER_BACKEND.blendEquationSeparate(modeRGB, modeAlpha); } } public static void tryBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); @@ -1420,11 +1366,10 @@ public class GLStateManager { srcAlpha = GL11.GL_ONE; dstAlpha = GL11.GL_ONE_MINUS_SRC_ALPHA; } - // Cache thread check - only update state on main thread, but always make GL call if needed final boolean caching = isCachingEnabled(); - final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || blendState.getSrcRgb() != srcRgb || blendState.getDstRgb() != dstRgb || blendState.getSrcAlpha() != srcAlpha || blendState.getDstAlpha() != dstAlpha) { - if (caching) blendState.setAll(srcRgb, dstRgb, srcAlpha, dstAlpha); + final boolean bypass = !caching; + if (bypass || glCtx.blendState.getSrcRgb() != srcRgb || glCtx.blendState.getDstRgb() != dstRgb || glCtx.blendState.getSrcAlpha() != srcAlpha || glCtx.blendState.getDstAlpha() != dstAlpha) { + glCtx.blendState.setAll(srcRgb, dstRgb, srcAlpha, dstAlpha); RENDER_BACKEND.blendFuncSeparate(srcRgb, dstRgb, srcAlpha, dstAlpha); if (GLSMHooks.BLEND_FUNC_CHANGE.hasListeners()) { GLSMHooks.blendFuncChangeEvent.srcRgb = srcRgb; @@ -1460,7 +1405,7 @@ public class GLStateManager { ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - dirtyNormalAttrib = true; + ctx().dirtyNormalAttrib = true; } public static void glNormal3d(double nx, double ny, double nz) { @@ -1470,7 +1415,7 @@ public class GLStateManager { ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - dirtyNormalAttrib = true; + ctx().dirtyNormalAttrib = true; } public static void glNormal3f(float nx, float ny, float nz) { @@ -1479,7 +1424,7 @@ public class GLStateManager { ImmediateModeRecorder.setNormal(nx, ny, nz); return; } - dirtyNormalAttrib = true; + ctx().dirtyNormalAttrib = true; } public static void glNormal3i(int nx, int ny, int nz) { @@ -1489,10 +1434,11 @@ public class GLStateManager { ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - dirtyNormalAttrib = true; + ctx().dirtyNormalAttrib = true; } public static void glDepthFunc(int func) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordDepthFunc(func); @@ -1501,13 +1447,14 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || func != depthState.getFunc()) { - if (caching) depthState.setFunc(func); + if (!caching || func != glCtx.depthState.getFunc()) { + glCtx.depthState.setFunc(func); RENDER_BACKEND.depthFunc(func); } } public static void glDepthMask(boolean mask) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordDepthMask(mask); @@ -1521,8 +1468,8 @@ public class GLStateManager { return; } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || mask != depthState.isEnabled()) { - if (caching) depthState.setEnabled(mask); + if (!caching || mask != glCtx.depthState.isEnabled()) { + glCtx.depthState.setEnabled(mask); RENDER_BACKEND.depthMask(mask); } } @@ -1630,20 +1577,19 @@ public class GLStateManager { public static float i2f(int i) {return ((i - Integer.MIN_VALUE) & 0xFFFFFFFFL) / 4294967295.0F;} private static boolean changeColor(float red, float green, float blue, float alpha) { + final GLContextState glCtx = ctx(); // Helper function for glColor* final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || red != color.getRed() || green != color.getGreen() || blue != color.getBlue() || alpha != color.getAlpha()) { - if (caching) { - color.setRed(red); - color.setGreen(green); - color.setBlue(blue); - color.setAlpha(alpha); - colorGeneration++; - } + if (!caching || red != glCtx.color.getRed() || green != glCtx.color.getGreen() || blue != glCtx.color.getBlue() || alpha != glCtx.color.getAlpha()) { + glCtx.color.setRed(red); + glCtx.color.setGreen(green); + glCtx.color.setBlue(blue); + glCtx.color.setAlpha(alpha); + glCtx.colorGeneration++; if (ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setColor(red, green, blue, alpha); } - dirtyColorAttrib = true; + glCtx.dirtyColorAttrib = true; // Only set while an enchantment-glint span is active final GlintColorHandler glintHandler = GLSMHooks.glintColorHandler; if (glintHandler != null) { @@ -1658,10 +1604,11 @@ public class GLStateManager { public static void clearCurrentColor() { // Marks the cache dirty, doesn't actually reset the color - color.set(DirtyColor); + ctx().color.set(DirtyColor); } public static void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordColorMask(red, green, blue, alpha); @@ -1674,17 +1621,17 @@ public class GLStateManager { dch.deferColorMask(red, green, blue, alpha); return; } - // Cache thread check - only update state on main thread, but always make GL call if needed final boolean caching = isCachingEnabled(); - final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || red != colorMask.red || green != colorMask.green || blue != colorMask.blue || alpha != colorMask.alpha) { - if (caching) colorMask.setAll(red, green, blue, alpha); + final boolean bypass = !caching; + if (bypass || red != glCtx.colorMask.red || green != glCtx.colorMask.green || blue != glCtx.colorMask.blue || alpha != glCtx.colorMask.alpha) { + glCtx.colorMask.setAll(red, green, blue, alpha); RENDER_BACKEND.colorMask(red, green, blue, alpha); } } // Clear Color public static void glClearColor(float red, float green, float blue, float alpha) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordClearColor(red, green, blue, alpha); @@ -1693,13 +1640,11 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || red != clearColor.getRed() || green != clearColor.getGreen() || blue != clearColor.getBlue() || alpha != clearColor.getAlpha()) { - if (caching) { - clearColor.setRed(red); - clearColor.setGreen(green); - clearColor.setBlue(blue); - clearColor.setAlpha(alpha); - } + if (!caching || red != glCtx.clearColor.getRed() || green != glCtx.clearColor.getGreen() || blue != glCtx.clearColor.getBlue() || alpha != glCtx.clearColor.getAlpha()) { + glCtx.clearColor.setRed(red); + glCtx.clearColor.setGreen(green); + glCtx.clearColor.setBlue(blue); + glCtx.clearColor.setAlpha(alpha); RENDER_BACKEND.clearColor(red, green, blue, alpha); } } @@ -1712,12 +1657,13 @@ public class GLStateManager { return; } } - if (isCachingEnabled()) depthState.setClearValue(depth); + if (isCachingEnabled()) ctx().depthState.setClearValue(depth); RENDER_BACKEND.clearDepth(depth); } // ALPHA public static void enableAlphaTest() { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordEnable(GL11.GL_ALPHA_TEST); @@ -1730,14 +1676,15 @@ public class GLStateManager { ah.deferAlphaTestToggle(true); return; } - alphaTest.enable(); - fragmentGeneration++; + glCtx.alphaTest.enable(); + glCtx.fragmentGeneration++; if (GLSMHooks.ALPHA_STATE_CHANGE.hasListeners()) { GLSMHooks.ALPHA_STATE_CHANGE.post(GLSMHooks.alphaStateChangeEvent); } } public static void disableAlphaTest() { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordDisable(GL11.GL_ALPHA_TEST); @@ -1750,14 +1697,15 @@ public class GLStateManager { ah.deferAlphaTestToggle(false); return; } - alphaTest.disable(); - fragmentGeneration++; + glCtx.alphaTest.disable(); + glCtx.fragmentGeneration++; if (GLSMHooks.ALPHA_STATE_CHANGE.hasListeners()) { GLSMHooks.ALPHA_STATE_CHANGE.post(GLSMHooks.alphaStateChangeEvent); } } public static void glAlphaFunc(int function, float reference) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordAlphaFunc(function, reference); @@ -1771,9 +1719,9 @@ public class GLStateManager { return; } if (isCachingEnabled()) { - alphaState.setFunction(function); - alphaState.setReference(reference); - fragmentGeneration++; + glCtx.alphaState.setFunction(function); + glCtx.alphaState.setReference(reference); + glCtx.fragmentGeneration++; if (GLSMHooks.ALPHA_STATE_CHANGE.hasListeners()) { GLSMHooks.ALPHA_STATE_CHANGE.post(GLSMHooks.alphaStateChangeEvent); } @@ -1790,13 +1738,29 @@ public class GLStateManager { } } final int newTexture = texture - GL13.GL_TEXTURE0; + if (!isValidTextureUnit(newTexture, texture)) { + return; + } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || getActiveTextureUnit() != newTexture) { - if (caching) activeTextureUnit.setValue(newTexture); + if (!caching || getActiveTextureUnit() != newTexture) { + ctx().activeTextureUnit.setValue(newTexture); RENDER_BACKEND.activeTexture(texture); } } + private static boolean isValidTextureUnit(int unit, int rawEnum) { + if (unit >= 0 && unit < MAX_TEXTURE_UNITS) { + return true; + } + if (!warnedInvalidTextureUnit) { + warnedInvalidTextureUnit = true; + LOGGER.warn("glActiveTexture({}) is not a valid texture unit enum (expected GL_TEXTURE0..GL_TEXTURE{}); ignoring", rawEnum, MAX_TEXTURE_UNITS - 1, new Throwable("call site")); + } + return false; + } + + private static boolean warnedInvalidTextureUnit = false; + public static void glActiveTextureARB(int texture) { final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { @@ -1806,23 +1770,26 @@ public class GLStateManager { } } final int newTexture = texture - GL13.GL_TEXTURE0; + if (!isValidTextureUnit(newTexture, texture)) { + return; + } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || getActiveTextureUnit() != newTexture) { - if (caching) activeTextureUnit.setValue(newTexture); + if (!caching || getActiveTextureUnit() != newTexture) { + ctx().activeTextureUnit.setValue(newTexture); RENDER_BACKEND.activeTexture(texture); } } public static void glClientActiveTexture(int texture) { - clientActiveTextureUnit = texture - GL13.GL_TEXTURE0; + ctx().clientActiveTextureUnit = texture - GL13.GL_TEXTURE0; } public static int getClientActiveTextureUnit() { - return clientActiveTextureUnit; + return ctx().clientActiveTextureUnit; } private static int texCoordAttributeLocation() { - return switch (clientActiveTextureUnit) { + return switch (ctx().clientActiveTextureUnit) { case 0 -> Usage.PRIMARY_UV.getAttributeLocation(); case 1 -> Usage.SECONDARY_UV.getAttributeLocation(); default -> -1; @@ -1830,14 +1797,15 @@ public class GLStateManager { } private static int getBoundTexture() { - return getBoundTexture(activeTextureUnit.getValue()); + return getBoundTexture(ctx().activeTextureUnit.getValue()); } private static int getBoundTexture(int unit) { - return textures.getTextureUnitBindings(unit).getBinding(); + return ctx().textures.getTextureUnitBindings(unit).getBinding(); } public static void glBindTexture(int target, int texture) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordBindTexture(target, texture); @@ -1850,29 +1818,23 @@ public class GLStateManager { deferredDeleteTextures.remove(texture); } - if (target != GL11.GL_TEXTURE_2D) { - // Non-2D targets (e.g. GL_TEXTURE_2D_ARRAY) pass through without caching - logUncachedTextureTarget(target); - RENDER_BACKEND.bindTexture(target, texture); - return; - } - if (!isCachingEnabled()) { RENDER_BACKEND.bindTexture(target, texture); return; } - final int activeUnit = GLStateManager.activeTextureUnit.getValue(); - final TextureBinding textureUnit = textures.getTextureUnitBindings(activeUnit); + final int activeUnit = glCtx.activeTextureUnit.getValue(); + final TextureBinding textureUnit = glCtx.textures.getTextureUnitBindings(activeUnit); final int cachedBinding = textureUnit.getBinding(); - if (cachedBinding != texture) { + if (cachedBinding != texture || (texture == 0 && textureUnit.getTarget() != target)) { + if (Tracy.ENABLED) texBindMisses++; RENDER_BACKEND.bindTexture(target, texture); - textureUnit.setBinding(texture); - if (texture != 0 && activeUnit > maxBoundTextureUnit) { - maxBoundTextureUnit = activeUnit; + textureUnit.setBinding(texture, target); + if (texture != 0) { + trackMaxBoundTextureUnit(activeUnit); } - if (!lockBindCallback && activeTextureUnit.getValue() == 0) { + if (!lockBindCallback && target == GL11.GL_TEXTURE_2D && glCtx.activeTextureUnit.getValue() == 0) { lockBindCallback = true; if (GLSMHooks.TEXTURE_BIND.hasListeners()) { GLSMHooks.textureBindEvent.textureId = texture; @@ -1885,37 +1847,48 @@ public class GLStateManager { } private static int changeFormatIfDeprecated(int internalformat) { - switch (internalformat) { - case GL11.GL_ALPHA4 -> internalformat = GL11.GL_RGBA4; - case GL11.GL_ALPHA8 -> internalformat = GL11.GL_RGBA8; - case GL11.GL_ALPHA12 -> internalformat = GL11.GL_RGBA12; - case GL11.GL_ALPHA16 -> internalformat = GL11.GL_RGBA16; + internalformat = GLESFormatRemap.promoteAlphaFormat(internalformat); + if (RenderSystem.isGLES()) { + internalformat = GLESFormatRemap.remapInternalFormat(internalformat); } return internalformat; } - private static void logUncachedTextureTarget(int target) { - final int bit = switch (target) { - case GL11.GL_TEXTURE_1D -> 0; - case GL30.GL_TEXTURE_2D_ARRAY -> 1; - case GL12.GL_TEXTURE_3D -> 2; - case GL13.GL_TEXTURE_CUBE_MAP -> 3; - case GL31.GL_TEXTURE_RECTANGLE -> 4; - case GL32.GL_TEXTURE_2D_MULTISAMPLE -> 5; - default -> 6; - }; - final long mask = 1L << bit; - if ((loggedUncachedTextureTargets & mask) == 0) { - loggedUncachedTextureTargets |= mask; - LOGGER.debug("glBindTexture target {} not cached by GLSM, passing through", target); + public static final class GLESTexImageRemap { + private final GLESFormatRemap.Result r; + private GLESTexImageRemap(GLESFormatRemap.Result r) { this.r = r; } + public int internalFormat() { return r.internalFormat(); } + public int format() { return r.format(); } + public int type() { return r.type(); } + } + + public static GLESTexImageRemap remapTexImageForGLES(int internalformat, int format, int type) { + return new GLESTexImageRemap(GLESFormatRemap.apply(internalformat, format, type, RenderSystem.isGLES())); + } + + static { + if (ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN) { + LOGGER.warn("GLSM GLES pixel-type remap assumes little-endian host; big-endian detected - BGRA uploads may be byte-swapped"); } } + private static int remapPixelTypeForGLES(int format, int type) { + return RenderSystem.isGLES() ? GLESFormatRemap.remapPixelType(format, type) : type; + } + + private static int remapTypeForRemappedInternalFormat(int internalformat, int type) { + if (!RenderSystem.isGLES()) return type; + if (!GLESFormatRemap.isGenericPixelType(type)) return type; + return GLESFormatRemap.typeForInternalFormatES32(internalformat, type); + } + public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexImage2DCmd.fromIntBuffer(target, level, internalformat, width, height, border, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexImage2DCmd.fromIntBuffer(target, level, internalformat, width, height, border, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -1929,9 +1902,11 @@ public class GLStateManager { public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, FloatBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexImage2DCmd.fromFloatBuffer(target, level, internalformat, width, height, border, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexImage2DCmd.fromFloatBuffer(target, level, internalformat, width, height, border, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -1945,9 +1920,11 @@ public class GLStateManager { public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, DoubleBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexImage2DCmd.fromDoubleBuffer(target, level, internalformat, width, height, border, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexImage2DCmd.fromDoubleBuffer(target, level, internalformat, width, height, border, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -1961,9 +1938,11 @@ public class GLStateManager { public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexImage2DCmd.fromByteBuffer(target, level, internalformat, width, height, border, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexImage2DCmd.fromByteBuffer(target, level, internalformat, width, height, border, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -1977,6 +1956,8 @@ public class GLStateManager { public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glTexImage2D with buffer offset"); } @@ -1991,7 +1972,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord(s, 0.0f, 0.0f, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord1d(double s) { @@ -2000,7 +1981,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord((float) s, 0.0f, 0.0f, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord2f(float s, float t) { @@ -2009,7 +1990,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord(s, t, 0.0f, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord2d(double s, double t) { @@ -2018,7 +1999,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord((float) s, (float) t, 0.0f, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord3f(float s, float t, float r) { @@ -2027,7 +2008,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord(s, t, r, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord3d(double s, double t, double r) { @@ -2036,7 +2017,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord((float) s, (float) t, (float) r, 1.0f); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord4f(float s, float t, float r, float q) { @@ -2045,7 +2026,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord(s, t, r, q); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glTexCoord4d(double s, double t, double r, double q) { @@ -2054,7 +2035,7 @@ public class GLStateManager { return; } ShaderManager.setCurrentTexCoord((float) s, (float) t, (float) r, (float) q); - dirtyTexCoordAttrib = true; + ctx().dirtyTexCoordAttrib = true; } public static void glDeleteTextures(int id) { @@ -2079,15 +2060,16 @@ public class GLStateManager { * So... we shrink the texture to 1x1 to free GPU memory, unbind from all units, but keep the name valid. * */ private static void deferDeleteTexture(int id) { + final GLContextState glCtx = ctx(); if (id == 0) return; - final int savedUnit = GLStateManager.activeTextureUnit.getValue(); - final int savedBinding = textures.getTextureUnitBindings(savedUnit).getBinding(); + final int savedUnit = glCtx.activeTextureUnit.getValue(); + final int savedBinding = glCtx.textures.getTextureUnitBindings(savedUnit).getBinding(); boolean changedUnit = false; // Unbind from all units that have this texture - for (int i = 0; i <= maxBoundTextureUnit; i++) { - if (textures.getTextureUnitBindings(i).getBinding() == id) { + for (int i = 0; i <= glCtx.maxBoundTextureUnit; i++) { + if (glCtx.textures.getTextureUnitBindings(i).getBinding() == id) { if (i != savedUnit) { RENDER_BACKEND.activeTexture(GL13.GL_TEXTURE0 + i); changedUnit = true; @@ -2140,13 +2122,7 @@ public class GLStateManager { return; } } - final int textureUnit = getActiveTextureUnit(); - if (GLSMHooks.TEXTURE_UNIT_STATE.hasListeners()) { - GLSMHooks.textureUnitStateEvent.unit = textureUnit; - GLSMHooks.textureUnitStateEvent.enabled = true; - GLSMHooks.TEXTURE_UNIT_STATE.post(GLSMHooks.textureUnitStateEvent); - } - textures.getTextureUnitStates(textureUnit).enable(); + ctx().textures.getTextureUnitStates(getActiveTextureUnit()).enable(); } public static void disableTexture() { @@ -2157,13 +2133,7 @@ public class GLStateManager { return; } } - final int textureUnit = getActiveTextureUnit(); - if (GLSMHooks.TEXTURE_UNIT_STATE.hasListeners()) { - GLSMHooks.textureUnitStateEvent.unit = textureUnit; - GLSMHooks.textureUnitStateEvent.enabled = false; - GLSMHooks.TEXTURE_UNIT_STATE.post(GLSMHooks.textureUnitStateEvent); - } - textures.getTextureUnitStates(textureUnit).disable(); + ctx().textures.getTextureUnitStates(getActiveTextureUnit()).disable(); } private static final String PIXELTRANSFER_MSG = "glPixelTransfer is not available in GL 3.3 core profile."; @@ -2202,7 +2172,7 @@ public class GLStateManager { } public static void glBegin(int mode) { - unit23TexCoordSetDuringDraw = false; + ctx().unit23TexCoordSetDuringDraw = false; if (DisplayListManager.isRecording()) { ImmediateModeRecorder.begin(mode); return; @@ -2288,6 +2258,7 @@ public class GLStateManager { } public static void glDrawElements(int mode, ByteBuffer indices) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2312,6 +2283,7 @@ public class GLStateManager { } public static void glDrawElements(int mode, IntBuffer indices) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2336,6 +2308,7 @@ public class GLStateManager { } public static void glDrawElements(int mode, ShortBuffer indices) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2360,6 +2333,7 @@ public class GLStateManager { } public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2384,6 +2358,7 @@ public class GLStateManager { } public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2421,28 +2396,27 @@ public class GLStateManager { return; } } - if (isCachingEnabled()) drawBuffer.setValue(mode); + if (isCachingEnabled()) ctx().drawBuffer.setValue(mode); RENDER_BACKEND.drawBuffer(mode); } public static void glMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { - ShaderManager.getInstance().preDraw(); - prepareClientArrays(); + if (Tracy.ENABLED) drawCalls += drawcount; RENDER_BACKEND.multiDrawElementsIndirect(mode, type, indirect, drawcount, stride); } public static void glMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { - ShaderManager.getInstance().preDraw(); - prepareClientArrays(); + if (Tracy.ENABLED) drawCalls += drawcount; RENDER_BACKEND.multiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex); } public static void glDrawElementsBaseVertex(int mode, int count, int type, long indices, int basevertex) { - preDraw(mode); + if (Tracy.ENABLED) drawCalls++; RENDER_BACKEND.drawElementsBaseVertex(mode, count, type, indices, basevertex); } public static void glDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) { + if (Tracy.ENABLED) drawCalls++; if (mode == GL11.GL_QUADS) { QuadConverter.drawQuadElementsAsTrianglesInstanced(count, type, indices, primcount); return; @@ -2452,6 +2426,7 @@ public class GLStateManager { } public static void glDrawArraysInstanced(int mode, int first, int count, int primcount) { + if (Tracy.ENABLED) drawCalls++; if (mode == GL11.GL_QUADS) { QuadConverter.drawQuadsAsTrianglesInstanced(first, count, primcount); } else if (mode == GL11.GL_QUAD_STRIP) { @@ -2466,6 +2441,34 @@ public class GLStateManager { } } + public static void glDrawRangeElements(int mode, int start, int end, int count, int type, long indices) { + ShaderManager.getInstance().preDraw(); + prepareClientArrays(); + RENDER_BACKEND.drawRangeElements(mode, start, end, count, type, indices); + } + + public static void glDrawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) { + RENDER_BACKEND.drawRangeElementsBaseVertex(mode, start, end, count, type, indices, baseVertex); + } + + public static void glMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { + ShaderManager.getInstance().preDraw(); + prepareClientArrays(); + RENDER_BACKEND.multiDrawArrays(mode, firsts, counts); + } + + public static void glPrimitiveRestartIndex(int index) { + RENDER_BACKEND.primitiveRestartIndex(index); + } + + public static void glPointParameterf(int pname, float param) { + RENDER_BACKEND.pointParameterf(pname, param); + } + + public static void glPointParameteri(int pname, int param) { + RENDER_BACKEND.pointParameteri(pname, param); + } + private static void prepareClientArrays() { if (VAOManager.hasAnyClientSideEnabledAttrib()) { VAOManager.uploadClientArraysToVBO(); @@ -2473,6 +2476,7 @@ public class GLStateManager { } public static void glDrawArrays(int mode, int first, int count) { + if (Tracy.ENABLED) drawCalls++; CommandRecorder savedRecorder = null; final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { @@ -2505,7 +2509,7 @@ public class GLStateManager { private static void ffpClientArrayPointer(int index, int size, int type, boolean normalized, int stride, long offset) { if (VAOManager.isGenericPointerEnabled(index)) return; - VAOManager.setAttribute(index, size, type, normalized, stride, offset, boundVBO); + VAOManager.setAttribute(index, size, type, normalized, stride, offset, ctx().boundVBO); VAOManager.markConventional(index); RENDER_BACKEND.vertexAttribPointer(index, size, type, normalized, stride, offset); } @@ -2684,7 +2688,7 @@ public class GLStateManager { } public static void glVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, long offset) { - VAOManager.setAttribute(index, size, type, normalized, stride, offset, boundVBO); + VAOManager.setAttribute(index, size, type, normalized, stride, offset, ctx().boundVBO); RENDER_BACKEND.vertexAttribPointer(index, size, type, normalized, stride, offset); } @@ -2713,7 +2717,7 @@ public class GLStateManager { } public static void glVertexAttribIPointer(int index, int size, int type, int stride, long offset) { - VAOManager.setAttribute(index, size, type, false, stride, offset, boundVBO); + VAOManager.setAttribute(index, size, type, false, stride, offset, ctx().boundVBO); RENDER_BACKEND.vertexAttribIPointer(index, size, type, stride, offset); } @@ -2760,33 +2764,31 @@ public class GLStateManager { return switch (cap) { case GL11.GL_COLOR_ARRAY -> VertexFlags.COLOR_BIT; case GL11.GL_NORMAL_ARRAY -> VertexFlags.NORMAL_BIT; - case GL11.GL_TEXTURE_COORD_ARRAY -> switch (clientActiveTextureUnit) { + case GL11.GL_TEXTURE_COORD_ARRAY -> switch (ctx().clientActiveTextureUnit) { case 0 -> VertexFlags.TEXTURE_BIT; case 1 -> VertexFlags.BRIGHTNESS_BIT; default -> 0; }; - default -> 0; // GL_VERTEX_ARRAY — position is implicit + default -> 0; // GL_VERTEX_ARRAY - position is implicit }; } - private static final int CLIENT_ATTRIB_STACK_DEPTH = 16; - private static final int[] clientAttribSavedTextureUnit = new int[CLIENT_ATTRIB_STACK_DEPTH]; - private static final int[] clientAttribSavedVertexFlags = new int[CLIENT_ATTRIB_STACK_DEPTH]; - private static int clientAttribStackPointer = 0; - + static final int CLIENT_ATTRIB_STACK_DEPTH = 16; public static void glPushClientAttrib(int mask) { - if (clientAttribStackPointer < CLIENT_ATTRIB_STACK_DEPTH) { - clientAttribSavedTextureUnit[clientAttribStackPointer] = clientActiveTextureUnit; - clientAttribSavedVertexFlags[clientAttribStackPointer] = VAOManager.getCurrentVertexFlags(); - clientAttribStackPointer++; + final GLContextState glCtx = ctx(); + if (glCtx.clientAttribStackPointer < CLIENT_ATTRIB_STACK_DEPTH) { + glCtx.clientAttribSavedTextureUnit[glCtx.clientAttribStackPointer] = glCtx.clientActiveTextureUnit; + glCtx.clientAttribSavedVertexFlags[glCtx.clientAttribStackPointer] = VAOManager.getCurrentVertexFlags(); + glCtx.clientAttribStackPointer++; } } public static void glPopClientAttrib() { - if (clientAttribStackPointer > 0) { - clientAttribStackPointer--; - clientActiveTextureUnit = clientAttribSavedTextureUnit[clientAttribStackPointer]; - VAOManager.setCurrentVertexFlags(clientAttribSavedVertexFlags[clientAttribStackPointer]); + final GLContextState glCtx = ctx(); + if (glCtx.clientAttribStackPointer > 0) { + glCtx.clientAttribStackPointer--; + glCtx.clientActiveTextureUnit = glCtx.clientAttribSavedTextureUnit[glCtx.clientAttribStackPointer]; + VAOManager.setCurrentVertexFlags(glCtx.clientAttribSavedVertexFlags[glCtx.clientAttribStackPointer]); } } @@ -2908,7 +2910,7 @@ public class GLStateManager { return; } } - if (isCachingEnabled()) logicOpMode.setValue(opcode); + if (isCachingEnabled()) ctx().logicOpMode.setValue(opcode); RENDER_BACKEND.logicOp(opcode); } @@ -2924,7 +2926,7 @@ public class GLStateManager { return; } } - cullState.enable(); + ctx().cullState.enable(); } public static void disableCull() { @@ -2935,7 +2937,7 @@ public class GLStateManager { return; } } - cullState.disable(); + ctx().cullState.disable(); } public static void enableDepthTest() { @@ -2946,7 +2948,7 @@ public class GLStateManager { return; } } - depthTest.enable(); + ctx().depthTest.enable(); } public static void disableDepthTest() { @@ -2957,7 +2959,7 @@ public class GLStateManager { return; } } - depthTest.disable(); + ctx().depthTest.disable(); } public static void enableLighting() { @@ -2968,7 +2970,7 @@ public class GLStateManager { return; } } - lightingState.enable(); + ctx().lightingState.enable(); } public static void enableLight(int light) { @@ -2979,7 +2981,7 @@ public class GLStateManager { return; } } - lightStates[light].enable(); + ctx().lightStates[light].enable(); } public static void enableColorMaterial() { @@ -2990,7 +2992,7 @@ public class GLStateManager { return; } } - colorMaterial.enable(); + ctx().colorMaterial.enable(); bakeCurrentColorIntoTrackedMaterial(); } @@ -3003,36 +3005,37 @@ public class GLStateManager { } } bakeCurrentColorIntoTrackedMaterial(); - colorMaterial.disable(); + ctx().colorMaterial.disable(); } private static void bakeCurrentColorIntoTrackedMaterial() { + final GLContextState glCtx = ctx(); final float r = getColor().getRed(); final float g = getColor().getGreen(); final float b = getColor().getBlue(); final float a = getColor().getAlpha(); - if (colorMaterialFace.getValue() == GL11.GL_FRONT || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) { - switch (colorMaterialParameter.getValue()) { + if (glCtx.colorMaterialFace.getValue() == GL11.GL_FRONT || glCtx.colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) { + switch (glCtx.colorMaterialParameter.getValue()) { case GL11.GL_AMBIENT_AND_DIFFUSE -> { - frontMaterial.ambient.set(r, g, b, a); - frontMaterial.diffuse.set(r, g, b, a); + glCtx.frontMaterial.ambient.set(r, g, b, a); + glCtx.frontMaterial.diffuse.set(r, g, b, a); } - case GL11.GL_AMBIENT -> frontMaterial.ambient.set(r, g, b, a); - case GL11.GL_DIFFUSE -> frontMaterial.diffuse.set(r, g, b, a); - case GL11.GL_SPECULAR -> frontMaterial.specular.set(r, g, b, a); - case GL11.GL_EMISSION -> frontMaterial.emission.set(r, g, b, a); + case GL11.GL_AMBIENT -> glCtx.frontMaterial.ambient.set(r, g, b, a); + case GL11.GL_DIFFUSE -> glCtx.frontMaterial.diffuse.set(r, g, b, a); + case GL11.GL_SPECULAR -> glCtx.frontMaterial.specular.set(r, g, b, a); + case GL11.GL_EMISSION -> glCtx.frontMaterial.emission.set(r, g, b, a); } } - if (colorMaterialFace.getValue() == GL11.GL_BACK || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) { - switch (colorMaterialParameter.getValue()) { + if (glCtx.colorMaterialFace.getValue() == GL11.GL_BACK || glCtx.colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) { + switch (glCtx.colorMaterialParameter.getValue()) { case GL11.GL_AMBIENT_AND_DIFFUSE -> { - backMaterial.ambient.set(r, g, b, a); - backMaterial.diffuse.set(r, g, b, a); + glCtx.backMaterial.ambient.set(r, g, b, a); + glCtx.backMaterial.diffuse.set(r, g, b, a); } - case GL11.GL_AMBIENT -> backMaterial.ambient.set(r, g, b, a); - case GL11.GL_DIFFUSE -> backMaterial.diffuse.set(r, g, b, a); - case GL11.GL_SPECULAR -> backMaterial.specular.set(r, g, b, a); - case GL11.GL_EMISSION -> backMaterial.emission.set(r, g, b, a); + case GL11.GL_AMBIENT -> glCtx.backMaterial.ambient.set(r, g, b, a); + case GL11.GL_DIFFUSE -> glCtx.backMaterial.diffuse.set(r, g, b, a); + case GL11.GL_SPECULAR -> glCtx.backMaterial.specular.set(r, g, b, a); + case GL11.GL_EMISSION -> glCtx.backMaterial.emission.set(r, g, b, a); } } } @@ -3045,7 +3048,7 @@ public class GLStateManager { return; } } - lightingState.disable(); + ctx().lightingState.disable(); } public static void disableLight(int light) { @@ -3056,7 +3059,7 @@ public class GLStateManager { return; } } - lightStates[light].disable(); + ctx().lightStates[light].disable(); } public static void enableRescaleNormal() { @@ -3067,7 +3070,7 @@ public class GLStateManager { return; } } - rescaleNormalState.enable(); + ctx().rescaleNormalState.enable(); } public static void disableRescaleNormal() { @@ -3078,7 +3081,7 @@ public class GLStateManager { return; } } - rescaleNormalState.disable(); + ctx().rescaleNormalState.disable(); } public static void enableFog() { @@ -3089,7 +3092,7 @@ public class GLStateManager { return; } } - fogMode.enable(); + ctx().fogMode.enable(); if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } @@ -3103,13 +3106,14 @@ public class GLStateManager { return; } } - fogMode.disable(); + ctx().fogMode.disable(); if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } } public static void glFog(int pname, FloatBuffer param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordFog(pname, param); @@ -3123,11 +3127,11 @@ public class GLStateManager { final float green = param.get(1); final float blue = param.get(2); - fogState.getFogColor().set(red, green, blue); - fogState.setFogAlpha(param.get(3)); - fogState.getFogColorBuffer().clear(); - fogState.getFogColorBuffer().put((FloatBuffer) param.position(0)).flip(); - fragmentGeneration++; + glCtx.fogState.getFogColor().set(red, green, blue); + glCtx.fogState.setFogAlpha(param.get(3)); + glCtx.fogState.getFogColorBuffer().clear(); + glCtx.fogState.getFogColorBuffer().put((FloatBuffer) param.position(0)).flip(); + glCtx.fragmentGeneration++; if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } @@ -3138,26 +3142,26 @@ public class GLStateManager { } public static Vector3d getFogColor() { - return fogState.getFogColor(); + return ctx().fogState.getFogColor(); } public static void fogColor(float red, float green, float blue, float alpha) { + final GLContextState glCtx = ctx(); final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || red != fogState.getFogColor().x || green != fogState.getFogColor().y || blue != fogState.getFogColor().z || alpha != fogState.getFogAlpha()) { - if (caching) { - fogState.getFogColor().set(red, green, blue); - fogState.setFogAlpha(alpha); - fogState.getFogColorBuffer().clear(); - fogState.getFogColorBuffer().put(red).put(green).put(blue).put(alpha).flip(); - fragmentGeneration++; - if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { - GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); - } + if (!caching || red != glCtx.fogState.getFogColor().x || green != glCtx.fogState.getFogColor().y || blue != glCtx.fogState.getFogColor().z || alpha != glCtx.fogState.getFogAlpha()) { + glCtx.fogState.getFogColor().set(red, green, blue); + glCtx.fogState.setFogAlpha(alpha); + glCtx.fogState.getFogColorBuffer().clear(); + glCtx.fogState.getFogColorBuffer().put(red).put(green).put(blue).put(alpha).flip(); + glCtx.fragmentGeneration++; + if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { + GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } } } public static void glFogf(int pname, float param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordFogf(pname, param); @@ -3169,14 +3173,14 @@ public class GLStateManager { if (isCachingEnabled()) { boolean changed = false; switch (pname) { - case GL11.GL_FOG_DENSITY -> { if (BYPASS_CACHE || fogState.getDensity() != param) { fogState.setDensity(param); changed = true; } } - case GL11.GL_FOG_START -> { if (BYPASS_CACHE || fogState.getStart() != param) { fogState.setStart(param); changed = true; } } - case GL11.GL_FOG_END -> { if (BYPASS_CACHE || fogState.getEnd() != param) { fogState.setEnd(param); changed = true; } } - case GL11.GL_FOG_MODE -> { if (BYPASS_CACHE || fogState.getFogMode() != (int) param) { fogState.setFogMode((int) param); changed = true; } } + case GL11.GL_FOG_DENSITY -> { if (!isCachingEnabled() || glCtx.fogState.getDensity() != param) { glCtx.fogState.setDensity(param); changed = true; } } + case GL11.GL_FOG_START -> { if (!isCachingEnabled() || glCtx.fogState.getStart() != param) { glCtx.fogState.setStart(param); changed = true; } } + case GL11.GL_FOG_END -> { if (!isCachingEnabled() || glCtx.fogState.getEnd() != param) { glCtx.fogState.setEnd(param); changed = true; } } + case GL11.GL_FOG_MODE -> { if (!isCachingEnabled() || glCtx.fogState.getFogMode() != (int) param) { glCtx.fogState.setFogMode((int) param); changed = true; } } default -> {} } if (changed) { - fragmentGeneration++; + glCtx.fragmentGeneration++; if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } @@ -3185,6 +3189,7 @@ public class GLStateManager { } public static void glFogi(int pname, int param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordFogi(pname, param); @@ -3193,9 +3198,9 @@ public class GLStateManager { } } // Update cached state (FFP shader reads from cache) - if (isCachingEnabled() && pname == GL11.GL_FOG_MODE && (BYPASS_CACHE || fogState.getFogMode() != param)) { - fogState.setFogMode(param); - fragmentGeneration++; + if (isCachingEnabled() && pname == GL11.GL_FOG_MODE && (!isCachingEnabled() || glCtx.fogState.getFogMode() != param)) { + glCtx.fogState.setFogMode(param); + glCtx.fragmentGeneration++; if (GLSMHooks.FOG_STATE_CHANGE.hasListeners()) { GLSMHooks.FOG_STATE_CHANGE.post(GLSMHooks.fogStateChangeEvent); } @@ -3207,6 +3212,7 @@ public class GLStateManager { } public static void glShadeModel(int mode) { + final GLContextState glCtx = ctx(); final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { DisplayListManager.recordShadeModel(mode); @@ -3215,18 +3221,17 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - final int oldValue = shadeModelState.getValue(); - final boolean needsUpdate = BYPASS_CACHE || !caching || oldValue != mode; + final int oldValue = glCtx.shadeModelState.getValue(); + final boolean needsUpdate = !caching || oldValue != mode; if (needsUpdate) { - if (caching) { - shadeModelState.setValue(mode); - } + glCtx.shadeModelState.setValue(mode); } } // Iris Functions private static void onDeleteTexture(int id) { + final GLContextState glCtx = ctx(); TextureInfoCache.INSTANCE.onDeleteTexture(id); if (GLSMHooks.TEXTURE_DELETE.hasListeners()) { GLSMHooks.textureDeleteEvent.textureId = id; @@ -3234,18 +3239,34 @@ public class GLStateManager { } // Always delete - for (int i = 0; i <= maxBoundTextureUnit; i++) { - if (textures.getTextureUnitBindings(i).getBinding() == id) { - textures.getTextureUnitBindings(i).setBinding(0); + for (int i = 0; i <= glCtx.maxBoundTextureUnit; i++) { + if (glCtx.textures.getTextureUnitBindings(i).getBinding() == id) { + glCtx.textures.getTextureUnitBindings(i).setBinding(0); + } + } + + for (int i = 0; i <= glCtx.maxBoundImageUnit; i++) { + final ImageUnitBinding image = glCtx.imageUnits.get(i); + if (image != null && image.getTexture() == id) { + image.setBinding(0, 0, false, 0, 0, 0); } } } + private static final ThreadLocal autoVaoBound = ThreadLocal.withInitial(() -> Boolean.FALSE); + public static void makeCurrent(Drawable drawable) throws LWJGLException { - drawable.makeCurrent(); + final boolean handled = BackendManager.RENDER_BACKEND != null && BackendManager.RENDER_BACKEND.handleMakeCurrent(drawable); + if (!handled) { + drawable.makeCurrent(); + } CurrentThread = Thread.currentThread(); - // Post-splash: single context, always cache + if (!splashComplete && CurrentThread != MainThread && !autoVaoBound.get()) { + autoVaoBound.set(Boolean.TRUE); + glBindVertexArray(glGenVertexArrays()); + } + if (splashComplete) return; if (drawableGL == null) { @@ -3271,14 +3292,62 @@ public class GLStateManager { // else: Thread switching to non-DrawableGL, wasn't holder - no change needed } + public static void releaseContext(Drawable drawable) throws LWJGLException { + final boolean handled = BackendManager.RENDER_BACKEND != null && BackendManager.RENDER_BACKEND.handleReleaseContext(drawable); + if (!handled) { + drawable.releaseContext(); + } + if (drawableGLHolder == Thread.currentThread()) { + drawableGLHolder = null; + } + if (!splashComplete && MainThread != null && Thread.currentThread() != MainThread) { + markSplashComplete("releaseContext"); + } + } + + public static boolean isCurrent() { + if (BackendManager.RENDER_BACKEND == null) { + return Thread.currentThread() == MainThread; + } + return BackendManager.RENDER_BACKEND.isCurrent(); + } + + public static void swapBuffers() throws LWJGLException { + if (BackendManager.RENDER_BACKEND != null && BackendManager.RENDER_BACKEND.handleSwapBuffers()) { + return; + } + Display.swapBuffers(); + } + + public static void updateDisplay() throws LWJGLException { + updateDisplay(true); + } + + public static void updateDisplay(boolean processMessages) throws LWJGLException { + if (Thread.currentThread() != MainThread) { + swapBuffers(); + if (processMessages) Display.processMessages(); + return; + } + Display.update(processMessages); + } + /** * Mark splash as complete - enables fast path that always caches. Called when finish() permanently switches to DrawableGL for the main game loop. */ - public static void markSplashComplete() { + public static void markSplashComplete(String source) { + if (splashComplete) return; + LOGGER.info("Splash complete (source={}, thread={})", source, Thread.currentThread().getName()); splashComplete = true; + stateSeedPending = true; drawableGLHolder = null; drawableGL = null; ImmediateModeRecorder.cleanupOrphanTessellators(); + if (GLSMHooks.LOADING_CHECKPOINT.hasListeners()) { + GLSMHooks.loadingCheckpointEvent.requiresSync = true; + GLSMHooks.LOADING_CHECKPOINT.post(GLSMHooks.loadingCheckpointEvent); + GLSMHooks.loadingCheckpointEvent.requiresSync = false; + } } public static void glNewList(int list, int mode) { @@ -3329,6 +3398,10 @@ public class GLStateManager { } public static void glCallList(int list) { + if (!GLDebug.isActive()) { + DisplayListManager.glCallList(list); + return; + } GLDebug.pushGroup("glCallList ", list); try { DisplayListManager.glCallList(list); @@ -3338,25 +3411,26 @@ public class GLStateManager { } public static void pushState(int mask) { - if (attribDepth >= MAX_ATTRIB_STACK_DEPTH) { + final GLContextState glCtx = ctx(); + if (glCtx.attribDepth >= MAX_ATTRIB_STACK_DEPTH) { throw new IllegalStateException("Attrib stack overflow: max depth " + MAX_ATTRIB_STACK_DEPTH + " reached"); } - attribs.push(mask); + glCtx.attribs.push(mask); // Snapshot generation counters so we can detect actual changes at pop time - savedMvGen[attribDepth] = mvGeneration; - savedMvLinearGen[attribDepth] = mvLinearGeneration; - savedProjGen[attribDepth] = projGeneration; - savedTexMatGen[attribDepth] = texMatrixGeneration; - savedLightingGen[attribDepth] = lightingGeneration; - savedFragmentGen[attribDepth] = fragmentGeneration; - savedColorGen[attribDepth] = colorGeneration; - savedNormalGen[attribDepth] = ShaderManager.getNormalGeneration(); - savedTexCoordGen[attribDepth] = ShaderManager.getTexCoordGeneration(); + glCtx.savedMvGen[glCtx.attribDepth] = glCtx.mvGeneration; + glCtx.savedMvLinearGen[glCtx.attribDepth] = glCtx.mvLinearGeneration; + glCtx.savedProjGen[glCtx.attribDepth] = glCtx.projGeneration; + glCtx.savedTexMatGen[glCtx.attribDepth] = glCtx.texMatrixGeneration; + glCtx.savedLightingGen[glCtx.attribDepth] = glCtx.lightingGeneration; + glCtx.savedFragmentGen[glCtx.attribDepth] = glCtx.fragmentGeneration; + glCtx.savedColorGen[glCtx.attribDepth] = glCtx.colorGeneration; + glCtx.savedNormalGen[glCtx.attribDepth] = ShaderManager.getNormalGeneration(); + glCtx.savedTexCoordGen[glCtx.attribDepth] = ShaderManager.getTexCoordGeneration(); // Clear modified list for this depth level - modifiedAtDepth[attribDepth].clear(); - attribDepth++; + glCtx.modifiedAtDepth[glCtx.attribDepth].clear(); + glCtx.attribDepth++; // Only iterate non-boolean stacks - BooleanStateStack uses global depth tracking // so pushDepth() is a no-op for them @@ -3367,17 +3441,20 @@ public class GLStateManager { } public static void popState() { - final int mask = attribs.popInt(); - attribDepth--; + final GLContextState glCtx = ctx(); + final int mask = glCtx.attribs.popInt(); + glCtx.attribDepth--; // First: restore BooleanStateStack states that were actually modified (fast path) // These use lazy copy-on-write with global depth tracking - final List> modified = modifiedAtDepth[attribDepth]; + final List> modified = glCtx.modifiedAtDepth[glCtx.attribDepth]; for (int i = 0; i < modified.size(); i++) { modified.get(i).popDepth(); } modified.clear(); + captureRestoreChanges(mask); + // Second: restore non-boolean state stacks the traditional way final IStateStack[] nonBooleanStacks = Feature.maskToNonBooleanStacks(mask); for (IStateStack stack : nonBooleanStacks) { @@ -3389,87 +3466,188 @@ public class GLStateManager { applyRestoredState(mask); } + private static void captureRestoreChanges(int mask) { + final GLContextState glCtx = ctx(); + if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0) { + glCtx.restoreDepthChanged = glCtx.depthState.topChanged(); + } + if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) { + glCtx.restoreBlendChanged = glCtx.blendState.topChanged(); + glCtx.restoreColorMaskChanged = glCtx.colorMask.topChanged(); + glCtx.restoreClearColorChanged = glCtx.clearColor.topChanged(); + glCtx.restoreDrawBufferChanged = glCtx.drawBuffer.topChanged(); + glCtx.restoreLogicOpChanged = glCtx.logicOpMode.topChanged(); + } + if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0) { + glCtx.restoreStencilChanged = glCtx.stencilState.topChanged(); + } + if ((mask & GL11.GL_VIEWPORT_BIT) != 0) { + glCtx.restoreViewportChanged = glCtx.viewportState.topChanged(); + } + if ((mask & GL11.GL_LINE_BIT) != 0) { + glCtx.restoreLineChanged = glCtx.lineState.topChanged(); + } + if ((mask & GL11.GL_POINT_BIT) != 0) { + glCtx.restorePointChanged = glCtx.pointState.topChanged(); + } + if ((mask & GL11.GL_POLYGON_BIT) != 0) { + glCtx.restorePolygonChanged = glCtx.polygonState.topChanged(); + } + if ((mask & GL11.GL_TEXTURE_BIT) != 0) { + for (int i = 0; i < MAX_TEXTURE_UNITS; i++) { + glCtx.restoreUnitChanged[i] = glCtx.textures.getTextureUnitBindings(i).topChanged(); + } + glCtx.restoreActiveUnitChanged = glCtx.activeTextureUnit.topChanged(); + } + } + + public static void replayStateToBackend() { + final GLContextState glCtx = ctx(); + if (RENDER_BACKEND == null) return; + + final List booleanStates = glCtx.allBooleanStates; + for (int i = 0; i < booleanStates.size(); i++) { + booleanStates.get(i).applyToBackend(); + } + + RENDER_BACKEND.depthFunc(glCtx.depthState.getFunc()); + RENDER_BACKEND.depthMask(glCtx.depthState.isEnabled()); + RENDER_BACKEND.clearDepth(glCtx.depthState.getClearValue()); + + RENDER_BACKEND.blendFuncSeparate(glCtx.blendState.getSrcRgb(), glCtx.blendState.getDstRgb(), glCtx.blendState.getSrcAlpha(), glCtx.blendState.getDstAlpha()); + RENDER_BACKEND.blendEquationSeparate(glCtx.blendState.getEquationRgb(), glCtx.blendState.getEquationAlpha()); + RENDER_BACKEND.blendColor(glCtx.blendState.getBlendColorR(), glCtx.blendState.getBlendColorG(), glCtx.blendState.getBlendColorB(), glCtx.blendState.getBlendColorA()); + RENDER_BACKEND.colorMask(glCtx.colorMask.red, glCtx.colorMask.green, glCtx.colorMask.blue, glCtx.colorMask.alpha); + RENDER_BACKEND.clearColor(glCtx.clearColor.getRed(), glCtx.clearColor.getGreen(), glCtx.clearColor.getBlue(), glCtx.clearColor.getAlpha()); + RENDER_BACKEND.logicOp(glCtx.logicOpMode.getValue()); + + RENDER_BACKEND.stencilFuncSeparate(GL11.GL_FRONT, glCtx.stencilState.getFuncFront(), glCtx.stencilState.getRefFront(), glCtx.stencilState.getValueMaskFront()); + RENDER_BACKEND.stencilFuncSeparate(GL11.GL_BACK, glCtx.stencilState.getFuncBack(), glCtx.stencilState.getRefBack(), glCtx.stencilState.getValueMaskBack()); + RENDER_BACKEND.stencilOpSeparate(GL11.GL_FRONT, glCtx.stencilState.getFailOpFront(), glCtx.stencilState.getZFailOpFront(), glCtx.stencilState.getZPassOpFront()); + RENDER_BACKEND.stencilOpSeparate(GL11.GL_BACK, glCtx.stencilState.getFailOpBack(), glCtx.stencilState.getZFailOpBack(), glCtx.stencilState.getZPassOpBack()); + RENDER_BACKEND.stencilMaskSeparate(GL11.GL_FRONT, glCtx.stencilState.getWriteMaskFront()); + RENDER_BACKEND.stencilMaskSeparate(GL11.GL_BACK, glCtx.stencilState.getWriteMaskBack()); + RENDER_BACKEND.clearStencil(glCtx.stencilState.getClearValue()); + + RENDER_BACKEND.viewport(glCtx.viewportState.x, glCtx.viewportState.y, glCtx.viewportState.width, glCtx.viewportState.height); + RENDER_BACKEND.depthRange(glCtx.viewportState.depthRangeNear, glCtx.viewportState.depthRangeFar); + RENDER_BACKEND.lineWidth(Math.clamp(glCtx.lineState.getWidth(), lineWidthMin, lineWidthMax)); + RENDER_BACKEND.pointSize(glCtx.pointState.getSize()); + + RENDER_BACKEND.polygonMode(GL11.GL_FRONT_AND_BACK, glCtx.polygonState.getFrontMode()); + applyPolygonOffset(glCtx); + RENDER_BACKEND.cullFace(glCtx.polygonState.getCullFaceMode()); + RENDER_BACKEND.frontFace(glCtx.polygonState.getFrontFace()); + } + + private static void applyPolygonOffset(GLContextState glCtx) { + final float clamp = glCtx.polygonState.getOffsetClamp(); + if (clamp == 0.0f) { + RENDER_BACKEND.polygonOffset(glCtx.polygonState.getOffsetFactor(), glCtx.polygonState.getOffsetUnits()); + } else { + RENDER_BACKEND.polygonOffsetClamp(glCtx.polygonState.getOffsetFactor(), glCtx.polygonState.getOffsetUnits(), clamp); + } + } + /** * After popping GLSM stacks, apply restored state to the GL driver. */ private static void applyRestoredState(int mask) { - if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0) { - RENDER_BACKEND.depthFunc(depthState.getFunc()); - RENDER_BACKEND.depthMask(depthState.isEnabled()); - RENDER_BACKEND.clearDepth(depthState.getClearValue()); + final GLContextState glCtx = ctx(); + if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0 && glCtx.restoreDepthChanged) { + RENDER_BACKEND.depthFunc(glCtx.depthState.getFunc()); + RENDER_BACKEND.depthMask(glCtx.depthState.isEnabled()); + RENDER_BACKEND.clearDepth(glCtx.depthState.getClearValue()); } if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) { - RENDER_BACKEND.blendFuncSeparate(blendState.getSrcRgb(), blendState.getDstRgb(), blendState.getSrcAlpha(), blendState.getDstAlpha()); - RENDER_BACKEND.blendEquationSeparate(blendState.getEquationRgb(), blendState.getEquationAlpha()); - RENDER_BACKEND.blendColor(blendState.getBlendColorR(), blendState.getBlendColorG(), blendState.getBlendColorB(), blendState.getBlendColorA()); - RENDER_BACKEND.colorMask(colorMask.red, colorMask.green, colorMask.blue, colorMask.alpha); - RENDER_BACKEND.clearColor(clearColor.getRed(), clearColor.getGreen(), clearColor.getBlue(), clearColor.getAlpha()); - // Draw buffer is per-framebuffer state; only restore on the default framebuffer - if (drawFramebuffer == 0) { - RENDER_BACKEND.drawBuffer(drawBuffer.getValue()); + if (glCtx.restoreBlendChanged) { + RENDER_BACKEND.blendFuncSeparate(glCtx.blendState.getSrcRgb(), glCtx.blendState.getDstRgb(), glCtx.blendState.getSrcAlpha(), glCtx.blendState.getDstAlpha()); + RENDER_BACKEND.blendEquationSeparate(glCtx.blendState.getEquationRgb(), glCtx.blendState.getEquationAlpha()); + RENDER_BACKEND.blendColor(glCtx.blendState.getBlendColorR(), glCtx.blendState.getBlendColorG(), glCtx.blendState.getBlendColorB(), glCtx.blendState.getBlendColorA()); + } + if (glCtx.restoreColorMaskChanged) { + RENDER_BACKEND.colorMask(glCtx.colorMask.red, glCtx.colorMask.green, glCtx.colorMask.blue, glCtx.colorMask.alpha); + } + if (glCtx.restoreClearColorChanged) { + RENDER_BACKEND.clearColor(glCtx.clearColor.getRed(), glCtx.clearColor.getGreen(), glCtx.clearColor.getBlue(), glCtx.clearColor.getAlpha()); + } + // Draw buffer is per-framebuffer state; only restore on the default framebuffer + if (glCtx.restoreDrawBufferChanged && glCtx.drawFramebuffer == 0) { + RENDER_BACKEND.drawBuffer(glCtx.drawBuffer.getValue()); + } + if (glCtx.restoreLogicOpChanged) { + RENDER_BACKEND.logicOp(glCtx.logicOpMode.getValue()); } - RENDER_BACKEND.logicOp(logicOpMode.getValue()); } - if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0) { - RENDER_BACKEND.stencilFuncSeparate(GL11.GL_FRONT, stencilState.getFuncFront(), stencilState.getRefFront(), stencilState.getValueMaskFront()); - RENDER_BACKEND.stencilFuncSeparate(GL11.GL_BACK, stencilState.getFuncBack(), stencilState.getRefBack(), stencilState.getValueMaskBack()); - RENDER_BACKEND.stencilOpSeparate(GL11.GL_FRONT, stencilState.getFailOpFront(), stencilState.getZFailOpFront(), stencilState.getZPassOpFront()); - RENDER_BACKEND.stencilOpSeparate(GL11.GL_BACK, stencilState.getFailOpBack(), stencilState.getZFailOpBack(), stencilState.getZPassOpBack()); - RENDER_BACKEND.stencilMaskSeparate(GL11.GL_FRONT, stencilState.getWriteMaskFront()); - RENDER_BACKEND.stencilMaskSeparate(GL11.GL_BACK, stencilState.getWriteMaskBack()); - RENDER_BACKEND.clearStencil(stencilState.getClearValue()); + if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0 && glCtx.restoreStencilChanged) { + RENDER_BACKEND.stencilFuncSeparate(GL11.GL_FRONT, glCtx.stencilState.getFuncFront(), glCtx.stencilState.getRefFront(), glCtx.stencilState.getValueMaskFront()); + RENDER_BACKEND.stencilFuncSeparate(GL11.GL_BACK, glCtx.stencilState.getFuncBack(), glCtx.stencilState.getRefBack(), glCtx.stencilState.getValueMaskBack()); + RENDER_BACKEND.stencilOpSeparate(GL11.GL_FRONT, glCtx.stencilState.getFailOpFront(), glCtx.stencilState.getZFailOpFront(), glCtx.stencilState.getZPassOpFront()); + RENDER_BACKEND.stencilOpSeparate(GL11.GL_BACK, glCtx.stencilState.getFailOpBack(), glCtx.stencilState.getZFailOpBack(), glCtx.stencilState.getZPassOpBack()); + RENDER_BACKEND.stencilMaskSeparate(GL11.GL_FRONT, glCtx.stencilState.getWriteMaskFront()); + RENDER_BACKEND.stencilMaskSeparate(GL11.GL_BACK, glCtx.stencilState.getWriteMaskBack()); + RENDER_BACKEND.clearStencil(glCtx.stencilState.getClearValue()); } - if ((mask & GL11.GL_VIEWPORT_BIT) != 0) { - RENDER_BACKEND.viewport(viewportState.x, viewportState.y, viewportState.width, viewportState.height); - RENDER_BACKEND.depthRange(viewportState.depthRangeNear, viewportState.depthRangeFar); + if ((mask & GL11.GL_VIEWPORT_BIT) != 0 && glCtx.restoreViewportChanged) { + RENDER_BACKEND.viewport(glCtx.viewportState.x, glCtx.viewportState.y, glCtx.viewportState.width, glCtx.viewportState.height); + RENDER_BACKEND.depthRange(glCtx.viewportState.depthRangeNear, glCtx.viewportState.depthRangeFar); } - if ((mask & GL11.GL_LINE_BIT) != 0) { - RENDER_BACKEND.lineWidth(Math.max(lineWidthMin, Math.min(lineWidthMax, lineState.getWidth()))); + if ((mask & GL11.GL_LINE_BIT) != 0 && glCtx.restoreLineChanged) { + RENDER_BACKEND.lineWidth(Math.clamp(glCtx.lineState.getWidth(), lineWidthMin, lineWidthMax)); } - if ((mask & GL11.GL_POINT_BIT) != 0) { - RENDER_BACKEND.pointSize(pointState.getSize()); + if ((mask & GL11.GL_POINT_BIT) != 0 && glCtx.restorePointChanged) { + RENDER_BACKEND.pointSize(glCtx.pointState.getSize()); } - if ((mask & GL11.GL_POLYGON_BIT) != 0) { + if ((mask & GL11.GL_POLYGON_BIT) != 0 && glCtx.restorePolygonChanged) { // Core profile only supports GL_FRONT_AND_BACK; use frontMode (front/back are always kept in sync since glPolygonMode also forces GL_FRONT_AND_BACK) - RENDER_BACKEND.polygonMode(GL11.GL_FRONT_AND_BACK, polygonState.getFrontMode()); - RENDER_BACKEND.polygonOffset(polygonState.getOffsetFactor(), polygonState.getOffsetUnits()); - RENDER_BACKEND.cullFace(polygonState.getCullFaceMode()); - RENDER_BACKEND.frontFace(polygonState.getFrontFace()); + RENDER_BACKEND.polygonMode(GL11.GL_FRONT_AND_BACK, glCtx.polygonState.getFrontMode()); + applyPolygonOffset(glCtx); + RENDER_BACKEND.cullFace(glCtx.polygonState.getCullFaceMode()); + RENDER_BACKEND.frontFace(glCtx.polygonState.getFrontFace()); } if ((mask & GL11.GL_TEXTURE_BIT) != 0) { - // Restore texture bindings for all units, then restore active unit. activeTextureUnit stores the 0-based index, glActiveTexture needs GL_TEXTURE0 + index. + // Restore only the units whose binding changed, then restore the active unit. + // activeTextureUnit stores the 0-based index, glActiveTexture needs GL_TEXTURE0 + index. + boolean unitTouched = false; for (int i = 0; i < MAX_TEXTURE_UNITS; i++) { - RENDER_BACKEND.activeTexture(GL13.GL_TEXTURE0 + i); - RENDER_BACKEND.bindTexture(GL11.GL_TEXTURE_2D, textures.getTextureUnitBindings(i).getBinding()); + if (glCtx.restoreUnitChanged[i]) { + final TextureBinding restored = glCtx.textures.getTextureUnitBindings(i); + final int restoredTarget = restored.getTarget() != 0 ? restored.getTarget() : GL11.GL_TEXTURE_2D; + RENDER_BACKEND.activeTexture(GL13.GL_TEXTURE0 + i); + RENDER_BACKEND.bindTexture(restoredTarget, restored.getBinding()); + unitTouched = true; + } + } + if (unitTouched || glCtx.restoreActiveUnitChanged) { + RENDER_BACKEND.activeTexture(GL13.GL_TEXTURE0 + glCtx.activeTextureUnit.getValue()); } - RENDER_BACKEND.activeTexture(GL13.GL_TEXTURE0 + activeTextureUnit.getValue()); } // Bump generation counters only if state actually changed during this push/pop scope. - // If nothing changed, the shader already has the right uniforms — no need to re-upload. - final int depth = attribDepth; // already decremented by popState() - if ((mask & GL11.GL_LIGHTING_BIT) != 0 && lightingGeneration != savedLightingGen[depth]) lightingGeneration++; - if ((mask & GL11.GL_FOG_BIT) != 0 && fragmentGeneration != savedFragmentGen[depth]) fragmentGeneration++; - if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0 && fragmentGeneration != savedFragmentGen[depth]) fragmentGeneration++; // alpha ref - if ((mask & GL11.GL_TEXTURE_BIT) != 0 && fragmentGeneration != savedFragmentGen[depth]) fragmentGeneration++; // texenv state + // If nothing changed, the shader already has the right uniforms - no need to re-upload. + final int depth = glCtx.attribDepth; // already decremented by popState() + if ((mask & GL11.GL_LIGHTING_BIT) != 0 && glCtx.lightingGeneration != glCtx.savedLightingGen[depth]) glCtx.lightingGeneration++; + if ((mask & GL11.GL_FOG_BIT) != 0 && glCtx.fragmentGeneration != glCtx.savedFragmentGen[depth]) glCtx.fragmentGeneration++; + if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0 && glCtx.fragmentGeneration != glCtx.savedFragmentGen[depth]) glCtx.fragmentGeneration++; // alpha ref + if ((mask & GL11.GL_TEXTURE_BIT) != 0 && glCtx.fragmentGeneration != glCtx.savedFragmentGen[depth]) glCtx.fragmentGeneration++; // texenv state if ((mask & GL11.GL_TRANSFORM_BIT) != 0) { - if (mvGeneration != savedMvGen[depth]) mvGeneration++; - if (mvLinearGeneration != savedMvLinearGen[depth]) mvLinearGeneration++; - if (projGeneration != savedProjGen[depth]) projGeneration++; - if (texMatrixGeneration != savedTexMatGen[depth]) texMatrixGeneration++; + if (glCtx.mvGeneration != glCtx.savedMvGen[depth]) glCtx.mvGeneration++; + if (glCtx.mvLinearGeneration != glCtx.savedMvLinearGen[depth]) glCtx.mvLinearGeneration++; + if (glCtx.projGeneration != glCtx.savedProjGen[depth]) glCtx.projGeneration++; + if (glCtx.texMatrixGeneration != glCtx.savedTexMatGen[depth]) glCtx.texMatrixGeneration++; } if ((mask & GL11.GL_CURRENT_BIT) != 0) { - if (colorGeneration != savedColorGen[depth]) { - colorGeneration++; - dirtyColorAttrib = true; + if (glCtx.colorGeneration != glCtx.savedColorGen[depth]) { + glCtx.colorGeneration++; + glCtx.dirtyColorAttrib = true; } - if (ShaderManager.getNormalGeneration() != savedNormalGen[depth]) { + if (ShaderManager.getNormalGeneration() != glCtx.savedNormalGen[depth]) { ShaderManager.bumpNormalGeneration(); - dirtyNormalAttrib = true; + glCtx.dirtyNormalAttrib = true; } - if (ShaderManager.getTexCoordGeneration() != savedTexCoordGen[depth]) { + if (ShaderManager.getTexCoordGeneration() != glCtx.savedTexCoordGen[depth]) { ShaderManager.bumpTexCoordGeneration(); - dirtyTexCoordAttrib = true; + glCtx.dirtyTexCoordAttrib = true; } } } @@ -3498,6 +3676,7 @@ public class GLStateManager { } public static void glPopAttrib() { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordPopAttrib(); @@ -3506,13 +3685,13 @@ public class GLStateManager { } } GLDebug.popGroup(); - poppingAttributes = true; + glCtx.poppingAttributes = true; GLDebug.pushGroup("popState"); try { popState(); } finally { GLDebug.popGroup(); - poppingAttributes = false; + glCtx.poppingAttributes = false; } } @@ -3525,7 +3704,7 @@ public class GLStateManager { return; } } - matrixMode.setMode(mode); + ctx().matrixMode.setMode(mode); } public static void glLoadMatrix(FloatBuffer m) { @@ -3565,32 +3744,35 @@ public class GLStateManager { } public static void setModelViewMatrix(Matrix4fc m) { + final GLContextState glCtx = ctx(); if (isCachingEnabled()) { - modelViewMatrix.set(m); - mvGeneration++; - mvLinearGeneration++; + glCtx.modelViewMatrix.set(m); + glCtx.mvGeneration++; + glCtx.mvLinearGeneration++; } } public static void setProjectionMatrix(Matrix4fc m) { + final GLContextState glCtx = ctx(); if (isCachingEnabled()) { - projectionMatrix.set(m); - projGeneration++; + glCtx.projectionMatrix.set(m); + glCtx.projGeneration++; } } public static Matrix4fStack getMatrixStack() { - switch (matrixMode.getMode()) { + final GLContextState glCtx = ctx(); + switch (glCtx.matrixMode.getMode()) { case GL11.GL_MODELVIEW -> { - return modelViewMatrix; + return glCtx.modelViewMatrix; } case GL11.GL_PROJECTION -> { - return projectionMatrix; + return glCtx.projectionMatrix; } case GL11.GL_TEXTURE -> { - return textures.getTextureUnitMatrix(getActiveTextureUnit()); + return glCtx.textures.getTextureUnitMatrix(getActiveTextureUnit()); } - default -> throw new IllegalStateException("Unknown matrix mode: " + matrixMode.getMode()); + default -> throw new IllegalStateException("Unknown matrix mode: " + glCtx.matrixMode.getMode()); } } @@ -3600,13 +3782,14 @@ public class GLStateManager { } private static void bumpMatrixGeneration(boolean linearChanged) { - switch (matrixMode.getMode()) { + final GLContextState glCtx = ctx(); + switch (glCtx.matrixMode.getMode()) { case GL11.GL_MODELVIEW -> { - mvGeneration++; - if (linearChanged) mvLinearGeneration++; + glCtx.mvGeneration++; + if (linearChanged) glCtx.mvLinearGeneration++; } - case GL11.GL_PROJECTION -> projGeneration++; - case GL11.GL_TEXTURE -> texMatrixGeneration++; + case GL11.GL_PROJECTION -> glCtx.projGeneration++; + case GL11.GL_TEXTURE -> glCtx.texMatrixGeneration++; } } @@ -3672,7 +3855,7 @@ public class GLStateManager { public static void glMultMatrix(FloatBuffer floatBuffer) { multMatrix.set(floatBuffer); - final int currentMode = matrixMode.getMode(); + final int currentMode = ctx().matrixMode.getMode(); if (DisplayListManager.isRecording()) { DisplayListManager.updateRelativeTransform(multMatrix); @@ -3812,6 +3995,8 @@ public class GLStateManager { } private static final Matrix4f gluMatrix = new Matrix4f(); + private static final Matrix4f gluMatrix2 = new Matrix4f(); + private static final Vector4f gluVec4 = new Vector4f(); private static final FloatBuffer gluBuffer = BufferUtils.createFloatBuffer(16); public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) { @@ -3839,6 +4024,47 @@ public class GLStateManager { GLStateManager.glScalef(viewport.get(viewport.position() + 2) / deltaX, viewport.get(viewport.position() + 3) / deltaY, 1.0f); } + public static int gluBuild2DMipmaps(int target, int components, int width, int height, int format, int type, ByteBuffer data) { + if (width < 1 || height < 1) return GLU.GLU_INVALID_VALUE; + glTexImage2D(target, 0, components, width, height, 0, format, type, data); + glGenerateMipmap(target); + return 0; + } + + public static String gluErrorString(int errorCode) { + return switch (errorCode) { + case GLU.GLU_INVALID_ENUM -> "Invalid enum (glu)"; + case GLU.GLU_INVALID_VALUE -> "Invalid value (glu)"; + case GLU.GLU_OUT_OF_MEMORY -> "Out of memory (glu)"; + case GL11.GL_NO_ERROR -> "No error"; + case GL11.GL_INVALID_ENUM -> "Invalid enum"; + case GL11.GL_INVALID_VALUE -> "Invalid value"; + case GL11.GL_INVALID_OPERATION -> "Invalid operation"; + case GL11.GL_OUT_OF_MEMORY -> "Out of memory"; + default -> "Unknown error: " + errorCode; + }; + } + + public static boolean gluUnProject(float winx, float winy, float winz, FloatBuffer modelMatrix, FloatBuffer projMatrix, IntBuffer viewport, FloatBuffer obj_pos) { + gluMatrix.set(projMatrix).mul(gluMatrix2.set(modelMatrix)); + if (Math.abs(gluMatrix.determinant()) < 1.0e-10f) return false; + gluMatrix.invert(gluMatrix); + + float ndcX = (winx - viewport.get(viewport.position())) / viewport.get(viewport.position() + 2) * 2.0f - 1.0f; + float ndcY = (winy - viewport.get(viewport.position() + 1)) / viewport.get(viewport.position() + 3) * 2.0f - 1.0f; + float ndcZ = winz * 2.0f - 1.0f; + + gluVec4.set(ndcX, ndcY, ndcZ, 1.0f); + gluMatrix.transform(gluVec4); + if (gluVec4.w == 0.0f) return false; + + float invW = 1.0f / gluVec4.w; + obj_pos.put(obj_pos.position(), gluVec4.x * invW); + obj_pos.put(obj_pos.position() + 1, gluVec4.y * invW); + obj_pos.put(obj_pos.position() + 2, gluVec4.z * invW); + return true; + } + public static void glViewport(int x, int y, int width, int height) { final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { @@ -3850,12 +4076,12 @@ public class GLStateManager { RENDER_BACKEND.viewport(x, y, width, height); // Only update cached state when caching is enabled if (isCachingEnabled()) { - viewportState.setViewPort(x, y, width, height); + ctx().viewportState.setViewPort(x, y, width, height); } } public static int getActiveTextureUnit() { - return activeTextureUnit.getValue(); + return ctx().activeTextureUnit.getValue(); } public static int getListMode() { @@ -3865,7 +4091,7 @@ public class GLStateManager { private static boolean handleRemovedTexParam(int target, int pname, int value) { if (pname == GL14.GL_GENERATE_MIPMAP) { if (target == GL11.GL_TEXTURE_2D) { - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState()); + final TextureInfo info = getBoundTextureInfo(); if (info != null) info.setGenerateMipmap(value != 0); } return true; @@ -3875,7 +4101,7 @@ public class GLStateManager { private static void maybeGenerateMipmap(int target, int level) { if (target != GL11.GL_TEXTURE_2D) return; - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState()); + final TextureInfo info = getBoundTextureInfo(); if (info != null && info.isGenerateMipmap() && level == info.getBaseLevel() && level < info.getMaxLevel()) { RENDER_BACKEND.generateMipmap(target); } @@ -3885,41 +4111,44 @@ public class GLStateManager { if (target != GL11.GL_TEXTURE_2D) { return true; } - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture); + return updateTexParameteriCache(TextureInfoCache.INSTANCE.getInfo(texture), pname, param); + } + + static boolean updateTexParameteriCache(TextureInfo info, int pname, int param) { if (info == null) { return true; } switch (pname) { case GL11.GL_TEXTURE_MIN_FILTER -> { - if (info.getMinFilter() == param && !shouldBypassCache()) return false; + if (info.getMinFilter() == param && isCachingEnabled()) return false; info.setMinFilter(param); } case GL11.GL_TEXTURE_MAG_FILTER -> { - if (info.getMagFilter() == param && !shouldBypassCache()) return false; + if (info.getMagFilter() == param && isCachingEnabled()) return false; info.setMagFilter(param); } case GL11.GL_TEXTURE_WRAP_S -> { - if (info.getWrapS() == param && !shouldBypassCache()) return false; + if (info.getWrapS() == param && isCachingEnabled()) return false; info.setWrapS(param); } case GL11.GL_TEXTURE_WRAP_T -> { - if (info.getWrapT() == param && !shouldBypassCache()) return false; + if (info.getWrapT() == param && isCachingEnabled()) return false; info.setWrapT(param); } case GL12.GL_TEXTURE_BASE_LEVEL -> { - if (info.getBaseLevel() == param && !shouldBypassCache()) return false; + if (info.getBaseLevel() == param && isCachingEnabled()) return false; info.setBaseLevel(param); } case GL12.GL_TEXTURE_MAX_LEVEL -> { - if (info.getMaxLevel() == param && !shouldBypassCache()) return false; + if (info.getMaxLevel() == param && isCachingEnabled()) return false; info.setMaxLevel(param); } case GL12.GL_TEXTURE_MIN_LOD -> { - if (info.getMinLod() == param && !shouldBypassCache()) return false; + if (info.getMinLod() == param && isCachingEnabled()) return false; info.setMinLod(param); } case GL12.GL_TEXTURE_MAX_LOD -> { - if (info.getMaxLod() == param && !shouldBypassCache()) return false; + if (info.getMaxLod() == param && isCachingEnabled()) return false; info.setMaxLod(param); } } @@ -3932,7 +4161,9 @@ public class GLStateManager { final int val = params.get(params.position()); final int remapped = remapTexClamp(pname, val); if (remapped != val) params.put(params.position(), remapped); - updateTexParameteriCache(target, getBoundTextureForServerState(), pname, remapped); + if (target == GL11.GL_TEXTURE_2D) { + updateTexParameteriCache(getBoundTextureInfo(), pname, remapped); + } } RENDER_BACKEND.texParameteriv(target, pname, params); } @@ -3943,7 +4174,9 @@ public class GLStateManager { final float val = params.get(params.position()); final float remapped = remapTexClamp(pname, val); if (remapped != val) params.put(params.position(), remapped); - updateTexParameterfCache(target, getBoundTextureForServerState(), pname, remapped); + if (target == GL11.GL_TEXTURE_2D) { + updateTexParameterfCache(getBoundTextureInfo(), pname, remapped); + } } RENDER_BACKEND.texParameterfv(target, pname, params); } @@ -3962,7 +4195,7 @@ public class GLStateManager { RENDER_BACKEND.texParameteri(target, pname, param); return; } - if (!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, param)) return; + if (!updateTexParameteriCache(getBoundTextureInfo(), pname, param)) return; RENDER_BACKEND.texParameteri(target, pname, param); } @@ -3971,17 +4204,20 @@ public class GLStateManager { if (target != GL11.GL_TEXTURE_2D) { return true; } - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture); + return updateTexParameterfCache(TextureInfoCache.INSTANCE.getInfo(texture), pname, param); + } + + static boolean updateTexParameterfCache(TextureInfo info, int pname, float param) { if (info == null) { return true; } switch (pname) { case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> { - if (info.getMaxAnisotropy() == param && !shouldBypassCache()) return false; + if (info.getMaxAnisotropy() == param && isCachingEnabled()) return false; info.setMaxAnisotropy(param); } case GL14.GL_TEXTURE_LOD_BIAS -> { - if (info.getLodBias() == param && !shouldBypassCache()) return false; + if (info.getLodBias() == param && isCachingEnabled()) return false; info.setLodBias(param); } } @@ -4002,18 +4238,21 @@ public class GLStateManager { RENDER_BACKEND.texParameterf(target, pname, param); return; } - if (!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, param)) return; + if (!updateTexParameterfCache(getBoundTextureInfo(), pname, param)) return; RENDER_BACKEND.texParameterf(target, pname, param); } public static int getTexParameterOrDefault(int texture, int pname, IntSupplier defaultSupplier) { - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture); + return getTexParameterOrDefault(TextureInfoCache.INSTANCE.getInfo(texture), pname, defaultSupplier); + } + + static int getTexParameterOrDefault(TextureInfo info, int pname, IntSupplier defaultSupplier) { if (info == null) { if (isRecordingDisplayList()) { - throw new IllegalStateException(String.format( - "glGetTexParameteri called during display list recording with no cached TextureInfo for texture %d. " + - "Cannot query OpenGL state during compilation!", texture)); + throw new IllegalStateException( + "glGetTexParameteri called during display list recording with no cached TextureInfo. " + + "Cannot query OpenGL state during compilation!"); } return defaultSupplier.getAsInt(); } @@ -4030,8 +4269,8 @@ public class GLStateManager { default -> { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( - "glGetTexParameteri called during display list recording with uncached pname 0x%s for texture %d. " + - "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture)); + "glGetTexParameteri called during display list recording with uncached pname 0x%s. " + + "Cannot query OpenGL state during compilation!", Integer.toHexString(pname))); } yield defaultSupplier.getAsInt(); } @@ -4039,23 +4278,22 @@ public class GLStateManager { } public static int glGetTexParameteri(int target, int pname) { - if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { + if (target != GL11.GL_TEXTURE_2D || !isCachingEnabled()) { return RENDER_BACKEND.getTexParameteri(target, pname); } - return getTexParameterOrDefault(getBoundTextureForServerState(), pname, () -> RENDER_BACKEND.getTexParameteri(target, pname)); + return getTexParameterOrDefault(getBoundTextureInfo(), pname, () -> RENDER_BACKEND.getTexParameteri(target, pname)); } public static float glGetTexParameterf(int target, int pname) { - if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { + if (target != GL11.GL_TEXTURE_2D || !isCachingEnabled()) { return RENDER_BACKEND.getTexParameterf(target, pname); } - final int boundTexture = getBoundTextureForServerState(); - final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(boundTexture); + final TextureInfo info = getBoundTextureInfo(); if(info == null) { if (isRecordingDisplayList()) { - throw new IllegalStateException(String.format( - "glGetTexParameterf called during display list recording with no cached TextureInfo for texture %d. " + - "Cannot query OpenGL state during compilation!", boundTexture)); + throw new IllegalStateException( + "glGetTexParameterf called during display list recording with no cached TextureInfo. " + + "Cannot query OpenGL state during compilation!"); } return RENDER_BACKEND.getTexParameterf(target, pname); } @@ -4066,8 +4304,8 @@ public class GLStateManager { default -> { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( - "glGetTexParameterf called during display list recording with uncached pname 0x%s for texture %d. " + - "Cannot query OpenGL state during compilation!", Integer.toHexString(pname), boundTexture)); + "glGetTexParameterf called during display list recording with uncached pname 0x%s. " + + "Cannot query OpenGL state during compilation!", Integer.toHexString(pname))); } yield RENDER_BACKEND.getTexParameterf(target, pname); } @@ -4075,7 +4313,7 @@ public class GLStateManager { } public static int glGetTexLevelParameteri(int target, int level, int pname) { - if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) { + if (target != GL11.GL_TEXTURE_2D || !isCachingEnabled()) { return RENDER_BACKEND.getTexLevelParameteri(target, level, pname); } final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState()); @@ -4107,34 +4345,105 @@ public class GLStateManager { }; } - public static void glGetTexImage(int target, int level, int format, int type, java.nio.ByteBuffer pixels) { + public static void glGetTexImage(int target, int level, int format, int type, ByteBuffer pixels) { + if (RenderSystem.isGLES()) { + getTexImageViaFboReadPixels(target, level, format, type, pixels); + return; + } suspendPixelPackBuffer(); RENDER_BACKEND.getTexImage(target, level, format, type, pixels); restorePixelPackBuffer(); } - public static void glGetTexImage(int target, int level, int format, int type, java.nio.IntBuffer pixels) { + public static void glGetTexImage(int target, int level, int format, int type, IntBuffer pixels) { + if (RenderSystem.isGLES()) { + getTexImageViaFboReadPixels(target, level, format, type, pixels); + return; + } suspendPixelPackBuffer(); RENDER_BACKEND.getTexImage(target, level, format, type, pixels); restorePixelPackBuffer(); } + private static void getTexImageViaFboReadPixels(int target, int level, int format, int type, Buffer pixels) { + if (target != GL11.GL_TEXTURE_2D) { + LOGGER.warn("glGetTexImage ES: unsupported target 0x{}", Integer.toHexString(target)); + return; + } + final int texId = getBoundTextureForServerState(); + if (texId == 0) return; + final int width = RENDER_BACKEND.getTexLevelParameteri(target, level, GL11.GL_TEXTURE_WIDTH); + final int height = RENDER_BACKEND.getTexLevelParameteri(target, level, GL11.GL_TEXTURE_HEIGHT); + if (width <= 0 || height <= 0) return; + + final int prevReadFb = RENDER_BACKEND.getInteger(GL30.GL_READ_FRAMEBUFFER_BINDING); + final int fbo = RENDER_BACKEND.genFramebuffers(); + try { + RENDER_BACKEND.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fbo); + RENDER_BACKEND.framebufferTexture2D(GL30.GL_READ_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, target, texId, level); + final int status = RENDER_BACKEND.checkFramebufferStatus(GL30.GL_READ_FRAMEBUFFER); + if (status != GL30.GL_FRAMEBUFFER_COMPLETE) { + LOGGER.warn("glGetTexImage ES: FBO incomplete (0x{})", Integer.toHexString(status)); + return; + } + final int esType = remapPixelTypeForGLES(format, type); + final boolean bgra = format == GL12.GL_BGRA; + final int esFormat = bgra ? GL11.GL_RGBA : format; + suspendPixelPackBuffer(); + try { + if (pixels instanceof ByteBuffer bb) { + RENDER_BACKEND.readPixels(0, 0, width, height, esFormat, esType, bb); + } else if (pixels instanceof IntBuffer ib) { + RENDER_BACKEND.readPixels(0, 0, width, height, esFormat, esType, ib); + } + if (bgra) swapRedBlueInPlace(pixels); + } finally { + restorePixelPackBuffer(); + } + } finally { + RENDER_BACKEND.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, prevReadFb); + RENDER_BACKEND.deleteFramebuffers(fbo); + } + } + + private static void swapRedBlueInPlace(Buffer pixels) { + if (pixels instanceof ByteBuffer bb) { + final int p = bb.position(); + final int lim = bb.limit(); + for (int i = p; i + 3 < lim; i += 4) { + final byte r = bb.get(i); + bb.put(i, bb.get(i + 2)); + bb.put(i + 2, r); + } + } else if (pixels instanceof IntBuffer ib) { + final int p = ib.position(); + final int lim = ib.limit(); + for (int i = p; i < lim; i++) { + final int w = ib.get(i); + ib.put(i, (w & 0xFF00FF00) | ((w & 0xFF) << 16) | ((w >> 16) & 0xFF)); + } + } + } + public static void glReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer pixels) { + type = remapPixelTypeForGLES(format, type); suspendPixelPackBuffer(); RENDER_BACKEND.readPixels(x, y, width, height, format, type, pixels); restorePixelPackBuffer(); } public static void glReadPixels(int x, int y, int width, int height, int format, int type, FloatBuffer pixels) { + type = remapPixelTypeForGLES(format, type); suspendPixelPackBuffer(); RENDER_BACKEND.readPixels(x, y, width, height, format, type, pixels); restorePixelPackBuffer(); } public static void glReadPixels(int x, int y, int width, int height, int format, int type, IntBuffer pixels) { + type = remapPixelTypeForGLES(format, type); suspendPixelPackBuffer(); RENDER_BACKEND.readPixels(x, y, width, height, format, type, pixels); restorePixelPackBuffer(); } public static void glTexStorage2D(int target, int levels, int internalFormat, int width, int height) { RENDER_BACKEND.texStorage2D(target, levels, internalFormat, width, height); } - public static void glClearTexImage(int texture, int level, int format, int type, java.nio.ByteBuffer data) { RENDER_BACKEND.clearTexImage(texture, level, format, type); } + public static void glClearTexImage(int texture, int level, int format, int type, ByteBuffer data) { RENDER_BACKEND.clearTexImage(texture, level, format, type); } public static int glGenSamplers() { return RENDER_BACKEND.genSamplers(); } public static void glDeleteSamplers(int sampler) { RENDER_BACKEND.deleteSamplers(sampler); } @@ -4143,69 +4452,73 @@ public class GLStateManager { public static void glSamplerParameterf(int sampler, int pname, float param) { RENDER_BACKEND.samplerParameterf(sampler, pname, param); } private static boolean glMaterialFront(int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); return switch (pname) { - case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params); - case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params); - case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params); - case GL11.GL_EMISSION -> frontMaterial.setEmission(params); - case GL11.GL_SHININESS -> frontMaterial.setShininess(params); + case GL11.GL_AMBIENT -> glCtx.frontMaterial.setAmbient(params); + case GL11.GL_DIFFUSE -> glCtx.frontMaterial.setDiffuse(params); + case GL11.GL_SPECULAR -> glCtx.frontMaterial.setSpecular(params); + case GL11.GL_EMISSION -> glCtx.frontMaterial.setEmission(params); + case GL11.GL_SHININESS -> glCtx.frontMaterial.setShininess(params); case GL11.GL_AMBIENT_AND_DIFFUSE -> { - final boolean a = frontMaterial.setAmbient(params); - final boolean d = frontMaterial.setDiffuse(params); + final boolean a = glCtx.frontMaterial.setAmbient(params); + final boolean d = glCtx.frontMaterial.setDiffuse(params); yield a || d; } - case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params); + case GL11.GL_COLOR_INDEXES -> glCtx.frontMaterial.setColorIndexes(params); default -> false; }; } private static boolean glMaterialBack(int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); return switch (pname) { - case GL11.GL_AMBIENT -> backMaterial.setAmbient(params); - case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params); - case GL11.GL_SPECULAR -> backMaterial.setSpecular(params); - case GL11.GL_EMISSION -> backMaterial.setEmission(params); - case GL11.GL_SHININESS -> backMaterial.setShininess(params); + case GL11.GL_AMBIENT -> glCtx.backMaterial.setAmbient(params); + case GL11.GL_DIFFUSE -> glCtx.backMaterial.setDiffuse(params); + case GL11.GL_SPECULAR -> glCtx.backMaterial.setSpecular(params); + case GL11.GL_EMISSION -> glCtx.backMaterial.setEmission(params); + case GL11.GL_SHININESS -> glCtx.backMaterial.setShininess(params); case GL11.GL_AMBIENT_AND_DIFFUSE -> { - final boolean a = backMaterial.setAmbient(params); - final boolean d = backMaterial.setDiffuse(params); + final boolean a = glCtx.backMaterial.setAmbient(params); + final boolean d = glCtx.backMaterial.setDiffuse(params); yield a || d; } - case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params); + case GL11.GL_COLOR_INDEXES -> glCtx.backMaterial.setColorIndexes(params); default -> false; }; } private static boolean glMaterialFront(int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); return switch (pname) { - case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params); - case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params); - case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params); - case GL11.GL_EMISSION -> frontMaterial.setEmission(params); - case GL11.GL_SHININESS -> frontMaterial.setShininess(params); + case GL11.GL_AMBIENT -> glCtx.frontMaterial.setAmbient(params); + case GL11.GL_DIFFUSE -> glCtx.frontMaterial.setDiffuse(params); + case GL11.GL_SPECULAR -> glCtx.frontMaterial.setSpecular(params); + case GL11.GL_EMISSION -> glCtx.frontMaterial.setEmission(params); + case GL11.GL_SHININESS -> glCtx.frontMaterial.setShininess(params); case GL11.GL_AMBIENT_AND_DIFFUSE -> { - final boolean a = frontMaterial.setAmbient(params); - final boolean d = frontMaterial.setDiffuse(params); + final boolean a = glCtx.frontMaterial.setAmbient(params); + final boolean d = glCtx.frontMaterial.setDiffuse(params); yield a || d; } - case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params); + case GL11.GL_COLOR_INDEXES -> glCtx.frontMaterial.setColorIndexes(params); default -> false; }; } private static boolean glMaterialBack(int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); return switch (pname) { - case GL11.GL_AMBIENT -> backMaterial.setAmbient(params); - case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params); - case GL11.GL_SPECULAR -> backMaterial.setSpecular(params); - case GL11.GL_EMISSION -> backMaterial.setEmission(params); - case GL11.GL_SHININESS -> backMaterial.setShininess(params); + case GL11.GL_AMBIENT -> glCtx.backMaterial.setAmbient(params); + case GL11.GL_DIFFUSE -> glCtx.backMaterial.setDiffuse(params); + case GL11.GL_SPECULAR -> glCtx.backMaterial.setSpecular(params); + case GL11.GL_EMISSION -> glCtx.backMaterial.setEmission(params); + case GL11.GL_SHININESS -> glCtx.backMaterial.setShininess(params); case GL11.GL_AMBIENT_AND_DIFFUSE -> { - final boolean a = backMaterial.setAmbient(params); - final boolean d = backMaterial.setDiffuse(params); + final boolean a = glCtx.backMaterial.setAmbient(params); + final boolean d = glCtx.backMaterial.setDiffuse(params); yield a || d; } - case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params); + case GL11.GL_COLOR_INDEXES -> glCtx.backMaterial.setColorIndexes(params); default -> false; }; } @@ -4230,7 +4543,7 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } - if (changed) lightingGeneration++; + if (changed) ctx().lightingGeneration++; } public static void glMaterial(int face, int pname, IntBuffer params) { @@ -4261,10 +4574,11 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } - if (changed) lightingGeneration++; + if (changed) ctx().lightingGeneration++; } public static void glMaterialf(int face, int pname, float val) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordMaterialf(face, pname, val); @@ -4279,17 +4593,17 @@ public class GLStateManager { boolean changed = false; if (face == GL11.GL_FRONT) { - changed = frontMaterial.setShininess(val); + changed = glCtx.frontMaterial.setShininess(val); } else if (face == GL11.GL_BACK) { - changed = backMaterial.setShininess(val); + changed = glCtx.backMaterial.setShininess(val); } else if (face == GL11.GL_FRONT_AND_BACK) { - final boolean f = frontMaterial.setShininess(val); - final boolean b = backMaterial.setShininess(val); + final boolean f = glCtx.frontMaterial.setShininess(val); + final boolean b = glCtx.backMaterial.setShininess(val); changed = f || b; } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glMateriali(int face, int pname, int val) { @@ -4299,6 +4613,7 @@ public class GLStateManager { } public static void glLight(int light, int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLight(light, pname, params); @@ -4306,7 +4621,7 @@ public class GLStateManager { return; } } - final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; + final LightStateStack lightState = glCtx.lightDataStates[light - GL11.GL_LIGHT0]; final boolean changed = switch (pname) { case GL11.GL_AMBIENT -> lightState.setAmbient(params); case GL11.GL_DIFFUSE -> lightState.setDiffuse(params); @@ -4320,10 +4635,11 @@ public class GLStateManager { case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLight(int light, int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); // For IntBuffer version, we need to convert to float for recording final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { @@ -4339,7 +4655,7 @@ public class GLStateManager { return; } } - final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; + final LightStateStack lightState = glCtx.lightDataStates[light - GL11.GL_LIGHT0]; final boolean changed = switch (pname) { case GL11.GL_AMBIENT -> lightState.setAmbient(params); case GL11.GL_DIFFUSE -> lightState.setDiffuse(params); @@ -4353,10 +4669,11 @@ public class GLStateManager { case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLightf(int light, int pname, float param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLightf(light, pname, param); @@ -4364,7 +4681,7 @@ public class GLStateManager { return; } } - final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; + final LightStateStack lightState = glCtx.lightDataStates[light - GL11.GL_LIGHT0]; final boolean changed = switch (pname) { case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param); case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param); @@ -4373,10 +4690,11 @@ public class GLStateManager { case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLighti(int light, int pname, int param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLighti(light, pname, param); @@ -4384,7 +4702,7 @@ public class GLStateManager { return; } } - final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0]; + final LightStateStack lightState = glCtx.lightDataStates[light - GL11.GL_LIGHT0]; final boolean changed = switch (pname) { case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param); case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param); @@ -4393,10 +4711,11 @@ public class GLStateManager { case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLightModel(int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLightModel(pname, params); @@ -4405,15 +4724,16 @@ public class GLStateManager { } } final boolean changed = switch (pname) { - case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params); - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params); - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params); + case GL11.GL_LIGHT_MODEL_AMBIENT -> glCtx.lightModel.setAmbient(params); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> glCtx.lightModel.setLocalViewer(params); + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> glCtx.lightModel.setTwoSide(params); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLightModel(int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); // For IntBuffer version, we need to convert to float for recording final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { @@ -4430,16 +4750,17 @@ public class GLStateManager { } } final boolean changed = switch (pname) { - case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params); - case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(params); - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params); - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params); + case GL11.GL_LIGHT_MODEL_AMBIENT -> glCtx.lightModel.setAmbient(params); + case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> glCtx.lightModel.setColorControl(params); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> glCtx.lightModel.setLocalViewer(params); + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> glCtx.lightModel.setTwoSide(params); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } public static void glLightModelf(int pname, float param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLightModelf(pname, param); @@ -4450,15 +4771,16 @@ public class GLStateManager { if (isCachingEnabled()) { final boolean changed = switch (pname) { - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param); - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> glCtx.lightModel.setLocalViewer(param); + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> glCtx.lightModel.setTwoSide(param); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } } public static void glLightModeli(int pname, int param) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLightModeli(pname, param); @@ -4469,16 +4791,17 @@ public class GLStateManager { if (isCachingEnabled()) { final boolean changed = switch (pname) { - case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(param); - case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param); - case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param); + case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> glCtx.lightModel.setColorControl(param); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> glCtx.lightModel.setLocalViewer(param); + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> glCtx.lightModel.setTwoSide(param); default -> false; }; - if (changed) lightingGeneration++; + if (changed) glCtx.lightingGeneration++; } } public static void glColorMaterial(int face, int mode) { + final GLContextState glCtx = ctx(); final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { DisplayListManager.recordColorMaterial(face, mode); @@ -4487,21 +4810,20 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || colorMaterialFace.getValue() != face || colorMaterialParameter.getValue() != mode) { - if (caching) { - colorMaterialFace.setValue(face); - colorMaterialParameter.setValue(mode); - lightingGeneration++; - } + if (!caching || glCtx.colorMaterialFace.getValue() != face || glCtx.colorMaterialParameter.getValue() != mode) { + glCtx.colorMaterialFace.setValue(face); + glCtx.colorMaterialParameter.setValue(mode); + glCtx.lightingGeneration++; } } public static void glDepthRange(double near, double far) { - if (isCachingEnabled()) viewportState.setDepthRange(near, far); + if (isCachingEnabled()) ctx().viewportState.setDepthRange(near, far); RENDER_BACKEND.depthRange(near, far); } public static void glUseProgram(int program) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordUseProgram(program); @@ -4512,11 +4834,10 @@ public class GLStateManager { final ShaderManager ffp = ShaderManager.getInstance(); if (program == 0 && ffp.isEnabled()) { - final int prev = activeProgram; + final int prev = glCtx.activeProgram; final boolean caching = isCachingEnabled(); - if (caching) { - activeProgram = 0; // Track that FFP was requested - } + if (prev != 0) glCtx.programGeneration++; + glCtx.activeProgram = 0; // Track that FFP was requested if (GLSMHooks.PROGRAM_CHANGE.hasListeners()) { GLSMHooks.programChangeEvent.previousProgram = prev; GLSMHooks.programChangeEvent.newProgram = 0; @@ -4533,11 +4854,11 @@ public class GLStateManager { } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || program != activeProgram) { - final int prev = activeProgram; - if (caching) { - activeProgram = program; - } + if (!caching || program != glCtx.activeProgram) { + if (Tracy.ENABLED) programSwitches++; + glCtx.programGeneration++; + final int prev = glCtx.activeProgram; + glCtx.activeProgram = program; if (GLSMHooks.PROGRAM_CHANGE.hasListeners()) { GLSMHooks.programChangeEvent.previousProgram = prev; GLSMHooks.programChangeEvent.newProgram = program; @@ -4561,6 +4882,8 @@ public class GLStateManager { // Missing GL commands from Mesa cross-check public static void glTexImage1D(int target, int level, int internalformat, int width, int border, int format, int type, ByteBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glTexImage1D"); } @@ -4571,6 +4894,8 @@ public class GLStateManager { public static void glTexImage3D(int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, ByteBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glTexImage3D"); } @@ -4581,6 +4906,8 @@ public class GLStateManager { public static void glTexImage3D(int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, IntBuffer pixels) { internalformat = changeFormatIfDeprecated(internalformat); + type = remapPixelTypeForGLES(format, type); + type = remapTypeForRemappedInternalFormat(internalformat, type); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glTexImage3D"); } @@ -4599,6 +4926,7 @@ public class GLStateManager { } public static void glLineWidth(float width) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLineWidth(width); @@ -4607,18 +4935,17 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || lineState.getWidth() != width) { - if (caching) { - lineState.setWidth(width); - } - RENDER_BACKEND.lineWidth(Math.max(lineWidthMin, Math.min(lineWidthMax, width))); + if (!caching || glCtx.lineState.getWidth() != width) { + glCtx.lineState.setWidth(width); + RENDER_BACKEND.lineWidth(Math.clamp(width, lineWidthMin, lineWidthMax)); } } public static void prepareLineEmulation(int drawMode) { + final GLContextState glCtx = ctx(); final boolean isLine = drawMode == GL11.GL_LINES || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP; - wideLineEmulationActive = isLine && lineState.getWidth() > 1.0f && wideLineEmulationEnabled; - setLineStippleActive(isLine && lineStippleState.isEnabled()); + wideLineEmulationActive = wideLineEmulationEnabled && RENDER_BACKEND.supportsGeometryShaders() && isLine && glCtx.lineState.getWidth() > 1.0f; + setLineStippleActive(isLine && glCtx.lineStippleState.isEnabled()); } public static void disableLineEmulation() { @@ -4640,9 +4967,13 @@ public class GLStateManager { RENDER_BACKEND.finish(); } + public static void setVSyncEnabled(boolean enabled) { + RENDER_BACKEND.setVSyncEnabled(enabled); + } + public static int glGetError() { - if (initConfig.noErrorChecks()) return 0; if (!RENDER_BACKEND.hasContext()) return 0; + if (initConfig.isNoErrorChecks()) return 0; return RENDER_BACKEND.getError(); } @@ -4661,27 +4992,12 @@ public class GLStateManager { // Always rename reserved words for the target GLSL version (e.g. 'sampler' at 460) src = GlslTransformUtils.renameReservedWords(src, RENDER_BACKEND.getMinGLSLVersion()); if (ShaderManager.getInstance().isEnabled()) { - src = CompatShaderTransformer.transform(src, isFragmentShader(shader)); + final int shaderType = RENDER_BACKEND.getShaderi(shader, GL20.GL_SHADER_TYPE); + src = CompatShaderTransformer.transform(src, shaderType, shaderType == GL20.GL_FRAGMENT_SHADER); } RENDER_BACKEND.shaderSource(shader, src); } - public static void glShaderSource(int shader, ByteBuffer source) { - final byte[] bytes = new byte[source.remaining()]; - final int pos = source.position(); - source.get(bytes); - source.position(pos); - glShaderSource(shader, new String(bytes, StandardCharsets.UTF_8)); - } - - public static void glShaderSource(int shader, CharSequence[] sources) { - int totalLen = 0; - for (CharSequence s : sources) totalLen += s.length(); - final StringBuilder sb = new StringBuilder(totalLen); - for (CharSequence s : sources) sb.append(s); - glShaderSource(shader, sb.toString()); - } - public static void nglShaderSource(int shader, int count, long strings, long lengths) { if (count <= 0) return; final CharSequence source; @@ -4701,6 +5017,22 @@ public class GLStateManager { return len < 0 ? MemoryUtilities.memUTF8(strAddr) : MemoryUtilities.memUTF8(strAddr, len); } + public static void glShaderSource(int shader, ByteBuffer source) { + final byte[] bytes = new byte[source.remaining()]; + final int pos = source.position(); + source.get(bytes); + source.position(pos); + glShaderSource(shader, new String(bytes, StandardCharsets.UTF_8)); + } + + public static void glShaderSource(int shader, CharSequence[] sources) { + int totalLen = 0; + for (CharSequence s : sources) totalLen += s.length(); + final StringBuilder sb = new StringBuilder(totalLen); + for (CharSequence s : sources) sb.append(s); + glShaderSource(shader, sb.toString()); + } + /** Check shader type to determine if fragment output transformation is needed. */ private static boolean isFragmentShader(int shader) { return RENDER_BACKEND.getShaderi(shader, GL20.GL_SHADER_TYPE) == GL20.GL_FRAGMENT_SHADER; @@ -4708,9 +5040,10 @@ public class GLStateManager { // Texture commands public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { + type = remapPixelTypeForGLES(format, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromByteBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromByteBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -4722,9 +5055,10 @@ public class GLStateManager { } public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { + type = remapPixelTypeForGLES(format, type); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { - DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromIntBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels, pixelUnpackState)); + DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromIntBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels, ctx().pixelUnpackState)); if (mode == RecordMode.COMPILE) { return; } @@ -4736,6 +5070,7 @@ public class GLStateManager { } public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, long pixels_buffer_offset) { + type = remapPixelTypeForGLES(format, type); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glTexSubImage2D with buffer offset"); } @@ -4760,6 +5095,7 @@ public class GLStateManager { } public static void glCopyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) { + internalFormat = changeFormatIfDeprecated(internalFormat); if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glCopyTexImage2D"); } @@ -4791,6 +5127,7 @@ public class GLStateManager { // State commands public static void glCullFace(int mode) { + final GLContextState glCtx = ctx(); final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { DisplayListManager.recordCullFace(mode); @@ -4799,15 +5136,14 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || polygonState.getCullFaceMode() != mode) { - if (caching) { - polygonState.setCullFaceMode(mode); - } + if (!caching || glCtx.polygonState.getCullFaceMode() != mode) { + glCtx.polygonState.setCullFaceMode(mode); RENDER_BACKEND.cullFace(mode); } } public static void glFrontFace(int mode) { + final GLContextState glCtx = ctx(); final RecordMode recordMode = DisplayListManager.getRecordMode(); if (recordMode != RecordMode.NONE) { DisplayListManager.recordFrontFace(mode); @@ -4816,10 +5152,8 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || polygonState.getFrontFace() != mode) { - if (caching) { - polygonState.setFrontFace(mode); - } + if (!caching || glCtx.polygonState.getFrontFace() != mode) { + glCtx.polygonState.setFrontFace(mode); RENDER_BACKEND.frontFace(mode); } } @@ -4842,6 +5176,7 @@ public class GLStateManager { } public static void glLineStipple(int factor, short pattern) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLineStipple(factor, pattern); @@ -4849,11 +5184,12 @@ public class GLStateManager { return; } } - lineState.setStippleFactor(factor); - lineState.setStipplePattern(pattern); + glCtx.lineState.setStippleFactor(factor); + glCtx.lineState.setStipplePattern(pattern); } public static void glPointSize(float size) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordPointSize(size); @@ -4862,15 +5198,14 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || pointState.getSize() != size) { - if (caching) { - pointState.setSize(size); - } + if (!caching || glCtx.pointState.getSize() != size) { + glCtx.pointState.setSize(size); RENDER_BACKEND.pointSize(size); } } public static void glPolygonMode(int face, int polygonMode) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordPolygonMode(face, polygonMode); @@ -4882,16 +5217,16 @@ public class GLStateManager { final boolean caching = isCachingEnabled(); final boolean needsUpdate; if (face == GL11.GL_FRONT) { - needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode; - if (caching && needsUpdate) polygonState.setFrontMode(polygonMode); + needsUpdate = !caching || glCtx.polygonState.getFrontMode() != polygonMode; + if (caching && needsUpdate) glCtx.polygonState.setFrontMode(polygonMode); } else if (face == GL11.GL_BACK) { - needsUpdate = BYPASS_CACHE || !caching || polygonState.getBackMode() != polygonMode; - if (caching && needsUpdate) polygonState.setBackMode(polygonMode); + needsUpdate = !caching || glCtx.polygonState.getBackMode() != polygonMode; + if (caching && needsUpdate) glCtx.polygonState.setBackMode(polygonMode); } else { // GL_FRONT_AND_BACK - needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode || polygonState.getBackMode() != polygonMode; + needsUpdate = !caching || glCtx.polygonState.getFrontMode() != polygonMode || glCtx.polygonState.getBackMode() != polygonMode; if (caching && needsUpdate) { - polygonState.setFrontMode(polygonMode); - polygonState.setBackMode(polygonMode); + glCtx.polygonState.setFrontMode(polygonMode); + glCtx.polygonState.setBackMode(polygonMode); } } if (needsUpdate) { @@ -4900,6 +5235,7 @@ public class GLStateManager { } public static void glPolygonOffset(float factor, float units) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordPolygonOffset(factor, units); @@ -4908,15 +5244,45 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || polygonState.getOffsetFactor() != factor || polygonState.getOffsetUnits() != units) { - if (caching) { - polygonState.setOffsetFactor(factor); - polygonState.setOffsetUnits(units); - } + + if (!caching || glCtx.polygonState.getOffsetFactor() != factor || glCtx.polygonState.getOffsetUnits() != units || glCtx.polygonState.getOffsetClamp() != 0.0f) { + glCtx.polygonState.setOffsetFactor(factor); + glCtx.polygonState.setOffsetUnits(units); + glCtx.polygonState.setOffsetClamp(0.0f); RENDER_BACKEND.polygonOffset(factor, units); } } + public static void glPolygonOffsetClamp(float factor, float units, float clamp) { + if (clamp == 0.0f) { + glPolygonOffset(factor, units); + return; + } + if (DisplayListManager.isRecording()) { + throw DisplayListManager.unsupportedInList("glPolygonOffsetClamp"); + } + final GLContextState glCtx = ctx(); + final boolean caching = isCachingEnabled(); + if (!caching || glCtx.polygonState.getOffsetFactor() != factor || glCtx.polygonState.getOffsetUnits() != units || glCtx.polygonState.getOffsetClamp() != clamp) { + glCtx.polygonState.setOffsetFactor(factor); + glCtx.polygonState.setOffsetUnits(units); + glCtx.polygonState.setOffsetClamp(clamp); + RENDER_BACKEND.polygonOffsetClamp(factor, units, clamp); + } + } + + public static void glMultiDrawArraysIndirectCount(int mode, long indirect, long drawcount, int maxdrawcount, int stride) { + RENDER_BACKEND.multiDrawArraysIndirectCount(mode, indirect, drawcount, maxdrawcount, stride); + } + + public static void glMultiDrawElementsIndirectCount(int mode, int type, long indirect, long drawcount, int maxdrawcount, int stride) { + RENDER_BACKEND.multiDrawElementsIndirectCount(mode, type, indirect, drawcount, maxdrawcount, stride); + } + + public static void glSpecializeShader(int shader, CharSequence entryPoint, IntBuffer constantIndex, IntBuffer constantValue) { + RENDER_BACKEND.specializeShader(shader, entryPoint, constantIndex, constantValue); + } + public static void glReadBuffer(int mode) { if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glReadBuffer"); @@ -4936,6 +5302,7 @@ public class GLStateManager { } public static void glStencilFunc(int func, int ref, int mask) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilFunc(func, ref, mask); @@ -4943,17 +5310,16 @@ public class GLStateManager { return; } } - final int clampedMask = mask & stencilBitMask; + final int clampedMask = mask & glCtx.stencilBitMask; final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != clampedMask) { - if (caching) { - stencilState.setFunc(func, ref, clampedMask); - } + if (!caching || glCtx.stencilState.getFuncFront() != func || glCtx.stencilState.getRefFront() != ref || glCtx.stencilState.getValueMaskFront() != clampedMask) { + glCtx.stencilState.setFunc(func, ref, clampedMask); RENDER_BACKEND.stencilFunc(func, ref, clampedMask); } } public static void glStencilMask(int mask) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilMask(mask); @@ -4961,17 +5327,16 @@ public class GLStateManager { return; } } - final int clampedMask = mask & stencilBitMask; + final int clampedMask = mask & glCtx.stencilBitMask; final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getWriteMaskFront() != clampedMask) { - if (caching) { - stencilState.setWriteMask(clampedMask); - } + if (!caching || glCtx.stencilState.getWriteMaskFront() != clampedMask) { + glCtx.stencilState.setWriteMask(clampedMask); RENDER_BACKEND.stencilMask(clampedMask); } } public static void glStencilOp(int fail, int zfail, int zpass) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilOp(fail, zfail, zpass); @@ -4980,18 +5345,17 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getFailOpFront() != fail || stencilState.getZFailOpFront() != zfail || stencilState.getZPassOpFront() != zpass) { - if (caching) { - stencilState.setOp(fail, zfail, zpass); - } + if (!caching || glCtx.stencilState.getFailOpFront() != fail || glCtx.stencilState.getZFailOpFront() != zfail || glCtx.stencilState.getZPassOpFront() != zpass) { + glCtx.stencilState.setOp(fail, zfail, zpass); RENDER_BACKEND.stencilOp(fail, zfail, zpass); } } // glPixelStore* isn'tcompiled into display lists, it executes immediately public static void glPixelStorei(int pname, int param) { + final GLContextState glCtx = ctx(); if (isCachingEnabled()) { - pixelUnpackState = pixelUnpackState.with(pname, param); + glCtx.pixelUnpackState = glCtx.pixelUnpackState.with(pname, param); } RENDER_BACKEND.pixelStorei(pname, param); } @@ -5003,31 +5367,32 @@ public class GLStateManager { // Display List Commands public static void glCallLists(IntBuffer lists) { while (lists.hasRemaining()) { - final int listId = lists.get() + listBase; + final int listId = lists.get() + ctx().listBase; glCallList(listId); } } public static void glCallLists(ShortBuffer lists) { while (lists.hasRemaining()) { - final int listId = (lists.get() & 0xFFFF) + listBase; + final int listId = (lists.get() & 0xFFFF) + ctx().listBase; glCallList(listId); } } public static void glCallLists(ByteBuffer lists) { while (lists.hasRemaining()) { - final int listId = (lists.get() & 0xFF) + listBase; + final int listId = (lists.get() & 0xFF) + ctx().listBase; glCallList(listId); } } public static void glListBase(int base) { - listBase = base; + ctx().listBase = base; } // Clip Plane Commands public static void glClipPlane(int plane, DoubleBuffer equation) { + final GLContextState glCtx = ctx(); if (DisplayListManager.isRecording()) { final int pos = equation.position(); DisplayListManager.recordClipPlane(plane, equation.get(pos), equation.get(pos + 1), equation.get(pos + 2), equation.get(pos + 3)); @@ -5036,20 +5401,21 @@ public class GLStateManager { final int index = plane - GL11.GL_CLIP_PLANE0; if (index < 0 || index >= MAX_CLIP_PLANES) return; final int pos = equation.position(); - clipPlaneState.setPlane(index, equation.get(pos), equation.get(pos + 1), equation.get(pos + 2), equation.get(pos + 3), modelViewMatrix); - clipPlaneGeneration++; + glCtx.clipPlaneState.setPlane(index, equation.get(pos), equation.get(pos + 1), equation.get(pos + 2), equation.get(pos + 3), glCtx.modelViewMatrix); + glCtx.clipPlaneGeneration++; } /** Returns true if any GL_CLIP_PLANE0..7 is currently enabled. */ public static boolean anyClipPlaneEnabled() { for (int i = 0; i < MAX_CLIP_PLANES; i++) { - if (clipPlaneStates[i].isEnabled()) return true; + if (ctx().clipPlaneStates[i].isEnabled()) return true; } return false; } // Clear Commands public static void glClearStencil(int s) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordClearStencil(s); @@ -5058,10 +5424,8 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getClearValue() != s) { - if (caching) { - stencilState.setClearValue(s); - } + if (!caching || glCtx.stencilState.getClearValue() != s) { + glCtx.stencilState.setClearValue(s); RENDER_BACKEND.clearStencil(s); } } @@ -5099,6 +5463,7 @@ public class GLStateManager { // Stencil Separate Functions (GL 2.0+) public static void glStencilFuncSeparate(int face, int func, int ref, int mask) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilFuncSeparate(face, func, ref, mask); @@ -5106,35 +5471,34 @@ public class GLStateManager { return; } } - final int clampedMask = mask & stencilBitMask; + final int clampedMask = mask & glCtx.stencilBitMask; final boolean caching = isCachingEnabled(); - boolean needsUpdate = BYPASS_CACHE || !caching; + boolean needsUpdate = !caching; if (!needsUpdate) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - needsUpdate = stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != clampedMask; + needsUpdate = glCtx.stencilState.getFuncFront() != func || glCtx.stencilState.getRefFront() != ref || glCtx.stencilState.getValueMaskFront() != clampedMask; } if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) { - needsUpdate = stencilState.getFuncBack() != func || stencilState.getRefBack() != ref || stencilState.getValueMaskBack() != clampedMask; + needsUpdate = glCtx.stencilState.getFuncBack() != func || glCtx.stencilState.getRefBack() != ref || glCtx.stencilState.getValueMaskBack() != clampedMask; } } if (needsUpdate) { - if (caching) { - if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setFuncFront(func); - stencilState.setRefFront(ref); - stencilState.setValueMaskFront(clampedMask); - } - if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setFuncBack(func); - stencilState.setRefBack(ref); - stencilState.setValueMaskBack(clampedMask); - } + if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setFuncFront(func); + glCtx.stencilState.setRefFront(ref); + glCtx.stencilState.setValueMaskFront(clampedMask); + } + if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setFuncBack(func); + glCtx.stencilState.setRefBack(ref); + glCtx.stencilState.setValueMaskBack(clampedMask); } RENDER_BACKEND.stencilFuncSeparate(face, func, ref, clampedMask); } } public static void glStencilMaskSeparate(int face, int mask) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilMaskSeparate(face, mask); @@ -5142,31 +5506,30 @@ public class GLStateManager { return; } } - final int clampedMask = mask & stencilBitMask; + final int clampedMask = mask & glCtx.stencilBitMask; final boolean caching = isCachingEnabled(); - boolean needsUpdate = BYPASS_CACHE || !caching; + boolean needsUpdate = !caching; if (!needsUpdate) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - needsUpdate = stencilState.getWriteMaskFront() != clampedMask; + needsUpdate = glCtx.stencilState.getWriteMaskFront() != clampedMask; } if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) { - needsUpdate = stencilState.getWriteMaskBack() != clampedMask; + needsUpdate = glCtx.stencilState.getWriteMaskBack() != clampedMask; } } if (needsUpdate) { - if (caching) { - if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setWriteMaskFront(clampedMask); - } - if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setWriteMaskBack(clampedMask); - } + if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setWriteMaskFront(clampedMask); + } + if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setWriteMaskBack(clampedMask); } RENDER_BACKEND.stencilMaskSeparate(face, clampedMask); } } public static void glStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { + final GLContextState glCtx = ctx(); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordStencilOpSeparate(face, sfail, dpfail, dppass); @@ -5175,27 +5538,25 @@ public class GLStateManager { } } final boolean caching = isCachingEnabled(); - boolean needsUpdate = BYPASS_CACHE || !caching; + boolean needsUpdate = !caching; if (!needsUpdate) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - needsUpdate = stencilState.getFailOpFront() != sfail || stencilState.getZFailOpFront() != dpfail || stencilState.getZPassOpFront() != dppass; + needsUpdate = glCtx.stencilState.getFailOpFront() != sfail || glCtx.stencilState.getZFailOpFront() != dpfail || glCtx.stencilState.getZPassOpFront() != dppass; } if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) { - needsUpdate = stencilState.getFailOpBack() != sfail || stencilState.getZFailOpBack() != dpfail || stencilState.getZPassOpBack() != dppass; + needsUpdate = glCtx.stencilState.getFailOpBack() != sfail || glCtx.stencilState.getZFailOpBack() != dpfail || glCtx.stencilState.getZPassOpBack() != dppass; } } if (needsUpdate) { - if (caching) { - if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setFailOpFront(sfail); - stencilState.setZFailOpFront(dpfail); - stencilState.setZPassOpFront(dppass); - } - if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setFailOpBack(sfail); - stencilState.setZFailOpBack(dpfail); - stencilState.setZPassOpBack(dppass); - } + if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setFailOpFront(sfail); + glCtx.stencilState.setZFailOpFront(dpfail); + glCtx.stencilState.setZPassOpFront(dppass); + } + if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { + glCtx.stencilState.setFailOpBack(sfail); + glCtx.stencilState.setZFailOpBack(dpfail); + glCtx.stencilState.setZPassOpBack(dppass); } RENDER_BACKEND.stencilOpSeparate(face, sfail, dpfail, dppass); } @@ -5207,6 +5568,15 @@ public class GLStateManager { RENDER_BACKEND.deleteBuffers(buffer); } + public static void glDeleteSync(long sync) { + RENDER_BACKEND.deleteSync(sync); + } + + public static long glFenceSync(int condition, int flags) { return RENDER_BACKEND.fenceSync(condition, flags); } + public static int glClientWaitSync(long sync, int flags, long timeout) { return RENDER_BACKEND.clientWaitSync(sync, flags, timeout); } + public static void glWaitSync(long sync, int flags, long timeout) { RENDER_BACKEND.waitSync(sync, flags, timeout); } + public static int glGetSynci(long sync, int pname, IntBuffer length) { return RENDER_BACKEND.getSynci(sync, pname, length); } + public static void glDeleteBuffers(IntBuffer buffers) { for (int i = buffers.position(); i < buffers.limit(); i++) { invalidateDeletedBuffer(buffers.get(i)); @@ -5221,13 +5591,14 @@ public class GLStateManager { } private static void invalidateDeletedBuffer(int buffer) { + final GLContextState glCtx = ctx(); if (buffer == 0) return; final boolean locked = acquireDrawLock(); try { - if (boundVBO == buffer) glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + if (glCtx.boundVBO == buffer) glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); if (VAOManager.boundEBO == buffer) glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); - if (boundPixelUnpackBuffer == buffer) glBindBuffer(GL21.GL_PIXEL_UNPACK_BUFFER, 0); - if (boundPixelPackBuffer == buffer) glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0); + if (glCtx.boundPixelUnpackBuffer == buffer) glBindBuffer(GL21.GL_PIXEL_UNPACK_BUFFER, 0); + if (glCtx.boundPixelPackBuffer == buffer) glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0); VAOManager.onDeleteBuffer(buffer); } finally { @@ -5236,17 +5607,18 @@ public class GLStateManager { } public static void glBindBuffer(int target, int buffer) { + final GLContextState glCtx = ctx(); final boolean locked = acquireDrawLock(); try { if (target == GL15.GL_ARRAY_BUFFER) { // if (boundVBO == buffer) return; TODO figure out why this breaks switching async occlusion mode - boundVBO = buffer; + glCtx.boundVBO = buffer; } else if (target == GL15.GL_ELEMENT_ARRAY_BUFFER) { VAOManager.onBindEBO(buffer); } else if (target == GL21.GL_PIXEL_UNPACK_BUFFER) { - boundPixelUnpackBuffer = buffer; + glCtx.boundPixelUnpackBuffer = buffer; } else if (target == GL21.GL_PIXEL_PACK_BUFFER) { - boundPixelPackBuffer = buffer; + glCtx.boundPixelPackBuffer = buffer; } RENDER_BACKEND.bindBuffer(target, buffer); } finally { @@ -5255,11 +5627,11 @@ public class GLStateManager { } public static void forcePixelUnpackState(PixelUnpackState target) { - PixelUnpackState.applyDiff(pixelUnpackState, target); + PixelUnpackState.applyDiff(ctx().pixelUnpackState, target); } public static void restorePixelUnpackState(PixelUnpackState applied) { - PixelUnpackState.applyDiff(applied, pixelUnpackState); + PixelUnpackState.applyDiff(applied, ctx().pixelUnpackState); } private static boolean warnedUntrackedPixelBuffer; @@ -5273,7 +5645,7 @@ public class GLStateManager { } static void suspendPixelUnpackBuffer() { - if (boundPixelUnpackBuffer != 0) { + if (ctx().boundPixelUnpackBuffer != 0) { RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_UNPACK_BUFFER, 0); } else { warnUntrackedPixelBuffer(GL21.GL_PIXEL_UNPACK_BUFFER_BINDING, "GL_PIXEL_UNPACK_BUFFER"); @@ -5281,13 +5653,14 @@ public class GLStateManager { } static void restorePixelUnpackBuffer() { - if (boundPixelUnpackBuffer != 0) { - RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_UNPACK_BUFFER, boundPixelUnpackBuffer); + final GLContextState glCtx = ctx(); + if (glCtx.boundPixelUnpackBuffer != 0) { + RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_UNPACK_BUFFER, glCtx.boundPixelUnpackBuffer); } } static void suspendPixelPackBuffer() { - if (boundPixelPackBuffer != 0) { + if (ctx().boundPixelPackBuffer != 0) { RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0); } else { warnUntrackedPixelBuffer(GL21.GL_PIXEL_PACK_BUFFER_BINDING, "GL_PIXEL_PACK_BUFFER"); @@ -5295,8 +5668,9 @@ public class GLStateManager { } static void restorePixelPackBuffer() { - if (boundPixelPackBuffer != 0) { - RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_PACK_BUFFER, boundPixelPackBuffer); + final GLContextState glCtx = ctx(); + if (glCtx.boundPixelPackBuffer != 0) { + RENDER_BACKEND.bindBuffer(GL21.GL_PIXEL_PACK_BUFFER, glCtx.boundPixelPackBuffer); } } @@ -5537,7 +5911,13 @@ public class GLStateManager { } public static void glClearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, ByteBuffer data) { RENDER_BACKEND.clearBufferSubData(target, internalFormat, offset, size, format, type, data); } + public static void glClearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) { RENDER_BACKEND.clearBufferData(target, internalformat, format, type, data); } public static boolean glIsBuffer(int buffer) { return RENDER_BACKEND.isBuffer(buffer); } + public static boolean glIsTexture(int texture) { return RENDER_BACKEND.isTexture(texture); } + public static boolean glIsFramebuffer(int framebuffer) { return RENDER_BACKEND.isFramebuffer(framebuffer); } + public static boolean glIsRenderbuffer(int renderbuffer) { return RENDER_BACKEND.isRenderbuffer(renderbuffer); } + public static boolean glIsSampler(int sampler) { return RENDER_BACKEND.isSampler(sampler); } + public static boolean glIsQuery(int query) { return RENDER_BACKEND.isQuery(query); } public static void glCopyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size) { RENDER_BACKEND.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); } private static int checkedSize(long size) { @@ -5578,6 +5958,7 @@ public class GLStateManager { } public static void glBindVertexArray(int array) { + final GLContextState glCtx = ctx(); if (DisplayListManager.isRecording()) { DisplayListManager.recordBindVAO(array); // Since the vao needs to be bound to do stuff like state setup & data upload, it'll still execute the bind call. @@ -5588,8 +5969,8 @@ public class GLStateManager { } final boolean locked = acquireDrawLock(); try { - if (boundVAO != array) { - boundVAO = array; + if (glCtx.boundVAO != array) { + glCtx.boundVAO = array; VAOManager.onBindVertexArrayPre(array); RENDER_BACKEND.bindVertexArray(array); } @@ -5599,12 +5980,13 @@ public class GLStateManager { } public static void glDeleteVertexArrays(int array) { + final GLContextState glCtx = ctx(); final boolean locked = acquireDrawLock(); try { VAOManager.onDeleteVertexArray(array); - if (array == boundVAO) { + if (array == glCtx.boundVAO) { // Deleting the bound VAO implicitly unbinds it. Rebind the default VAO. - boundVAO = defaultVAO; + glCtx.boundVAO = defaultVAO; VAOManager.onBindVertexArrayPre(defaultVAO); RENDER_BACKEND.bindVertexArray(defaultVAO); } @@ -5642,27 +6024,28 @@ public class GLStateManager { return VENDOR == NVIDIA; } - @Getter protected static int drawFramebuffer = 0; - @Getter protected static int readFramebuffer = 0; - public static void glBindFramebuffer(int target, int framebuffer) { + final GLContextState glCtx = ctx(); if (target == GL30.GL_FRAMEBUFFER) { - if (drawFramebuffer == framebuffer && readFramebuffer == framebuffer) return; - drawFramebuffer = framebuffer; - readFramebuffer = framebuffer; + if (glCtx.drawFramebuffer == framebuffer && glCtx.readFramebuffer == framebuffer) return; + if (glCtx.drawFramebuffer != framebuffer) glCtx.drawFramebufferGeneration++; + glCtx.drawFramebuffer = framebuffer; + glCtx.readFramebuffer = framebuffer; } else if (target == GL30.GL_DRAW_FRAMEBUFFER) { - if (drawFramebuffer == framebuffer) return; - drawFramebuffer = framebuffer; + if (glCtx.drawFramebuffer == framebuffer) return; + glCtx.drawFramebufferGeneration++; + glCtx.drawFramebuffer = framebuffer; } else if (target == GL30.GL_READ_FRAMEBUFFER) { - if (readFramebuffer == framebuffer) return; - readFramebuffer = framebuffer; + if (glCtx.readFramebuffer == framebuffer) return; + glCtx.readFramebuffer = framebuffer; } RENDER_BACKEND.bindFramebuffer(target, framebuffer); } public static void glDeleteFramebuffers(int framebuffer) { - if (drawFramebuffer == framebuffer) drawFramebuffer = 0; - if (readFramebuffer == framebuffer) readFramebuffer = 0; + final GLContextState glCtx = ctx(); + if (glCtx.drawFramebuffer == framebuffer) { glCtx.drawFramebuffer = 0; glCtx.drawFramebufferGeneration++; } + if (glCtx.readFramebuffer == framebuffer) glCtx.readFramebuffer = 0; RENDER_BACKEND.deleteFramebuffers(framebuffer); } @@ -5684,6 +6067,85 @@ public class GLStateManager { public static void glFramebufferTexture(int target, int attachment, int texture, int level) { RENDER_BACKEND.framebufferTexture(target, attachment, texture, level); } + public static int glGenRenderbuffers() { return RENDER_BACKEND.genRenderbuffers(); } + public static void glDeleteRenderbuffers(int renderbuffer) { RENDER_BACKEND.deleteRenderbuffers(renderbuffer); } + public static void glBindRenderbuffer(int target, int renderbuffer) { RENDER_BACKEND.bindRenderbuffer(target, renderbuffer); } + public static void glRenderbufferStorage(int target, int internalformat, int width, int height) { RENDER_BACKEND.renderbufferStorage(target, internalformat, width, height); } + public static void glRenderbufferStorageMultisample(int target, int samples, int internalformat, int width, int height) { RENDER_BACKEND.renderbufferStorageMultisample(target, samples, internalformat, width, height); } + public static void glFramebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer) { RENDER_BACKEND.framebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } + + public static void glGenQueries(IntBuffer ids) { RENDER_BACKEND.genQueries(ids); } + public static int glGenQueries() { return RENDER_BACKEND.genQueries(); } + public static void glDeleteQueries(int id) { RENDER_BACKEND.deleteQueries(id); } + public static void glBeginQuery(int target, int id) { RENDER_BACKEND.beginQuery(target, id); } + public static void glEndQuery(int target) { RENDER_BACKEND.endQuery(target); } + public static void glGetQueryObjectui(int id, int pname, IntBuffer params) { RENDER_BACKEND.getQueryObjectui(id, pname, params); } + public static int glGetQueryObjecti(int id, int pname) { return RENDER_BACKEND.getQueryObjecti(id, pname); } + + public static void glBindBufferBase(int target, int index, int buffer) { RENDER_BACKEND.bindBufferBase(target, index, buffer); } + public static int glGetUniformBlockIndex(int program, CharSequence name) { return RENDER_BACKEND.getUniformBlockIndex(program, name); } + public static void glUniformBlockBinding(int program, int blockIndex, int binding) { RENDER_BACKEND.uniformBlockBinding(program, blockIndex, binding); } + public static void glBindFragDataLocation(int program, int colorNumber, CharSequence name) { RENDER_BACKEND.bindFragDataLocation(program, colorNumber, name); } + public static void glQueryCounter(int id, int target) { RENDER_BACKEND.queryCounter(id, target); } + public static long glGetQueryObjectui64(int id, int pname) { return RENDER_BACKEND.getQueryObjectui64(id, pname); } + public static void glUniform3(int location, float[] values) { RENDER_BACKEND.uniform3fv(location, values); } + public static void glUniform4(int location, float[] values) { RENDER_BACKEND.uniform4fv(location, values); } + + public static void glGetInteger(int pname, int[] params) { + if (!isCachingEnabled() || params.length == 0) { + RENDER_BACKEND.getInteger(pname, params); + return; + } + + switch (pname) { + case GL11.GL_VIEWPORT -> { + if (params.length < 4) { + RENDER_BACKEND.getInteger(pname, params); + } else { + ctx().viewportState.get(params); + } + } + case GL11.GL_POLYGON_MODE -> { + final PolygonState polygon = ctx().polygonState; + params[0] = polygon.getFrontMode(); + if (params.length > 1) params[1] = polygon.getBackMode(); + } + default -> { + if (!HAS_MULTIPLE_SET.contains(pname)) { + params[0] = glGetInteger(pname); + } else { + RENDER_BACKEND.getInteger(pname, params); + } + } + } + } + public static long nglMapBuffer(int target, int access) { + final ByteBuffer buf = RENDER_BACKEND.mapBuffer(target, access); + return buf == null ? 0L : MemoryUtilities.memAddress0(buf); + } + public static void nglMultiDrawElementsBaseVertex(int mode, long count, int type, long indices, int primcount, long basevertex) { + RENDER_BACKEND.multiDrawElementsBaseVertex(mode, count, type, indices, primcount, basevertex); + } + + public static void glObjectLabel(int identifier, int name, CharSequence label) { RENDER_BACKEND.objectLabel(identifier, name, label); } + public static String glGetObjectLabel(int identifier, int name, int bufSize) { return RENDER_BACKEND.getObjectLabel(identifier, name); } + public static void glPushDebugGroup(int source, int id, CharSequence message) { RENDER_BACKEND.pushDebugGroup(source, id, message); } + public static void glPopDebugGroup() { RENDER_BACKEND.popDebugGroup(); } + public static void glDebugMessageInsert(int source, int type, int id, int severity, CharSequence buf) { RENDER_BACKEND.debugMessageInsert(source, type, id, severity, buf); } + public static void glDebugMessageControl(int source, int type, int severity, IntBuffer ids, boolean enabled) { RENDER_BACKEND.debugMessageControl(source, type, severity, ids, enabled); } + + public static int glGetDebugMessageLog(int count, IntBuffer sources, IntBuffer types, IntBuffer ids, IntBuffer severities, IntBuffer lengths, ByteBuffer messageLog) { + return RENDER_BACKEND.getDebugMessageLog(count, sources, types, ids, severities, lengths, messageLog); + } + + public static void registerDebugMessageListener(GLDebugMessageListener listener, long userParam) { + RENDER_BACKEND.debugMessageCallback(listener, userParam); + } + + public static void glDebugMessageCallback(KHRDebugCallback callback) { + RENDER_BACKEND.debugMessageCallback(GLDebug.adaptDebugCallback(callback), 0L); + } + public static void glGenerateMipmap(int target) { RENDER_BACKEND.generateMipmap(target); } @@ -5697,13 +6159,14 @@ public class GLStateManager { } public static void glMultiTexCoord2f(int target, float s, float t) { + final GLContextState glCtx = ctx(); if (target == GL13.GL_TEXTURE0) { if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord(s, t); return; } ShaderManager.setCurrentTexCoord(s, t, 0.0f, 1.0f); - dirtyTexCoordAttrib = true; + glCtx.dirtyTexCoordAttrib = true; } else if (target == GL13.GL_TEXTURE1) { if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setLightmapCoord(s, t); @@ -5714,7 +6177,7 @@ public class GLStateManager { final int unit = target - GL13.GL_TEXTURE0; if (unit >= 2 && unit < 4) { if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { - unit23TexCoordSetDuringDraw = true; + glCtx.unit23TexCoordSetDuringDraw = true; } ShaderManager.setCurrentTexCoord(unit, s, t, 0.0f, 1.0f); } @@ -5733,7 +6196,7 @@ public class GLStateManager { if (unit == GL13.GL_TEXTURE1) { GLSMConfig.lastBrightnessX = x; GLSMConfig.lastBrightnessY = y; - dirtyLightmapAttrib = true; + ctx().dirtyLightmapAttrib = true; if (GLSMHooks.LIGHTMAP_COORDS.hasListeners()) { GLSMHooks.lightmapCoordsEvent.x = x; GLSMHooks.lightmapCoordsEvent.y = y; @@ -5754,7 +6217,6 @@ public class GLStateManager { return true; } - private static final boolean FFP_WARN_ON_UNSUPPORTED = Boolean.parseBoolean(System.getProperty("angelica.ffp.warnOnUnsupported", "false")); private static final Set warnedFFPFunctions = new HashSet<>(); @@ -5762,10 +6224,10 @@ public class GLStateManager { * Guards against FFP features not supported in core profile. * Default: throws UnsupportedOperationException. * With {@code -Dangelica.ffp.warnOnUnsupported=true}: warns once per function (diagnostic mode). - * @return true (always — caller should skip the GL call) + * @return true (always - caller should skip the GL call) */ private static boolean guardUnsupportedFFP(String function, String explanation) { - if (!FFP_WARN_ON_UNSUPPORTED) { + if (!SystemProperties.FFP_WARN_ON_UNSUPPORTED) { throw new UnsupportedOperationException(function + ": " + explanation); } if (warnedFFPFunctions.add(function)) { @@ -5809,14 +6271,15 @@ public class GLStateManager { } public static void glTexEnv(int target, int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); if (target == GL11.GL_TEXTURE_ENV && pname == GL11.GL_TEXTURE_ENV_COLOR && params.remaining() >= 4) { final int pos = params.position(); - final var envState = textures.getTexEnvState(activeTextureUnit.getValue()); + final var envState = glCtx.textures.getTexEnvState(glCtx.activeTextureUnit.getValue()); envState.envColorR = params.get(pos); envState.envColorG = params.get(pos + 1); envState.envColorB = params.get(pos + 2); envState.envColorA = params.get(pos + 3); - fragmentGeneration++; + glCtx.fragmentGeneration++; return; } if (target == GL14.GL_TEXTURE_FILTER_CONTROL) { @@ -5839,86 +6302,87 @@ public class GLStateManager { * GL_TEXTURE_ENV parameters including GL_COMBINE sub-params are tracked in per-unit TexEnvState. */ private static void handleTexEnvScalar(int target, int pname, float param) { + final GLContextState glCtx = ctx(); if (target == GL14.GL_TEXTURE_FILTER_CONTROL) { - // LOD bias via legacy glTexEnv path — remap to core-profile glTexParameterf + // LOD bias via legacy glTexEnv path - remap to core-profile glTexParameterf glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, param); return; } if (target != GL11.GL_TEXTURE_ENV) return; - final var envState = textures.getTexEnvState(activeTextureUnit.getValue()); + final var envState = glCtx.textures.getTexEnvState(glCtx.activeTextureUnit.getValue()); final int iparam = (int) param; switch (pname) { case GL11.GL_TEXTURE_ENV_MODE -> { envState.mode = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_COMBINE_RGB -> { envState.combineRgb = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_COMBINE_ALPHA -> { envState.combineAlpha = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE0_RGB -> { envState.sourceRgb[0] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE1_RGB -> { envState.sourceRgb[1] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE2_RGB -> { envState.sourceRgb[2] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE0_ALPHA -> { envState.sourceAlpha[0] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE1_ALPHA -> { envState.sourceAlpha[1] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_SOURCE2_ALPHA -> { envState.sourceAlpha[2] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND0_RGB -> { envState.operandRgb[0] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND1_RGB -> { envState.operandRgb[1] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND2_RGB -> { envState.operandRgb[2] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND0_ALPHA -> { envState.operandAlpha[0] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND1_ALPHA -> { envState.operandAlpha[1] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_OPERAND2_ALPHA -> { envState.operandAlpha[2] = iparam; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL13.GL_RGB_SCALE -> { envState.scaleRgb = param; - fragmentGeneration++; + glCtx.fragmentGeneration++; } case GL11.GL_ALPHA_SCALE -> { envState.scaleAlpha = param; - fragmentGeneration++; + glCtx.fragmentGeneration++; } - // Silently ignore unknown pname — other mods may pass unrecognized params + // Silently ignore unknown pname - other mods may pass unrecognized params } } @@ -5927,9 +6391,10 @@ public class GLStateManager { } public static int glGetTexEnvi(int target, int pname) { + final GLContextState glCtx = ctx(); if (target != GL11.GL_TEXTURE_ENV) return 0; - final var envState = textures.getTexEnvState(activeTextureUnit.getValue()); + final var envState = glCtx.textures.getTexEnvState(glCtx.activeTextureUnit.getValue()); return switch (pname) { case GL11.GL_TEXTURE_ENV_MODE -> envState.mode; case GL13.GL_COMBINE_RGB -> envState.combineRgb; @@ -5953,9 +6418,10 @@ public class GLStateManager { } public static void glGetTexEnv(int target, int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); if (target != GL11.GL_TEXTURE_ENV) return; if (pname == GL11.GL_TEXTURE_ENV_COLOR) { - final var envState = textures.getTexEnvState(activeTextureUnit.getValue()); + final var envState = glCtx.textures.getTexEnvState(glCtx.activeTextureUnit.getValue()); params.put(params.position(), (int) (envState.envColorR * 2147483647.0f)); params.put(params.position() + 1, (int) (envState.envColorG * 2147483647.0f)); params.put(params.position() + 2, (int) (envState.envColorB * 2147483647.0f)); @@ -5966,9 +6432,10 @@ public class GLStateManager { } public static void glGetTexEnv(int target, int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); if (target != GL11.GL_TEXTURE_ENV) return; if (pname == GL11.GL_TEXTURE_ENV_COLOR) { - final var envState = textures.getTexEnvState(activeTextureUnit.getValue()); + final var envState = glCtx.textures.getTexEnvState(glCtx.activeTextureUnit.getValue()); params.put(params.position(), envState.envColorR); params.put(params.position() + 1, envState.envColorG); params.put(params.position() + 2, envState.envColorB); @@ -5978,17 +6445,16 @@ public class GLStateManager { } } - // TexGen generation counter for FFP uniform dirty tracking - public static int texGenGeneration; private static final float[] texGenTempPlane = new float[4]; public static void glTexGeni(int coord, int pname, int param) { + final GLContextState glCtx = ctx(); if (!isCachingEnabled()) return; if (pname == GL11.GL_TEXTURE_GEN_MODE) { - final int unit = activeTextureUnit.getValue(); - textures.getTexGenState(unit).setMode(coord, param); - texGenGeneration++; + final int unit = glCtx.activeTextureUnit.getValue(); + glCtx.textures.getTexGenState(unit).setMode(coord, param); + glCtx.texGenGeneration++; } } @@ -6002,14 +6468,15 @@ public class GLStateManager { } public static void glTexGen(int coord, int pname, FloatBuffer params) { + final GLContextState glCtx = ctx(); if (!isCachingEnabled()) return; - final int unit = activeTextureUnit.getValue(); - final var texGenState = textures.getTexGenState(unit); + final int unit = glCtx.activeTextureUnit.getValue(); + final var texGenState = glCtx.textures.getTexGenState(unit); final int pos = params.position(); switch (pname) { case GL11.GL_TEXTURE_GEN_MODE -> { texGenState.setMode(coord, (int) params.get(pos)); - texGenGeneration++; + glCtx.texGenGeneration++; } case GL11.GL_OBJECT_PLANE -> { texGenTempPlane[0] = params.get(pos); @@ -6017,56 +6484,59 @@ public class GLStateManager { texGenTempPlane[2] = params.get(pos + 2); texGenTempPlane[3] = params.get(pos + 3); texGenState.setObjectPlane(coord, texGenTempPlane); - texGenGeneration++; + glCtx.texGenGeneration++; } case GL11.GL_EYE_PLANE -> { texGenTempPlane[0] = params.get(pos); texGenTempPlane[1] = params.get(pos + 1); texGenTempPlane[2] = params.get(pos + 2); texGenTempPlane[3] = params.get(pos + 3); - texGenState.setEyePlane(coord, texGenTempPlane, modelViewMatrix); - texGenGeneration++; + texGenState.setEyePlane(coord, texGenTempPlane, glCtx.modelViewMatrix); + glCtx.texGenGeneration++; } } } public static void glTexGen(int coord, int pname, DoubleBuffer params) { + final GLContextState glCtx = ctx(); if (!isCachingEnabled()) return; final int pos = params.position(); texGenTempPlane[0] = (float) params.get(pos); texGenTempPlane[1] = (float) params.get(pos + 1); texGenTempPlane[2] = (float) params.get(pos + 2); texGenTempPlane[3] = (float) params.get(pos + 3); - final int unit = activeTextureUnit.getValue(); - final var texGenState = textures.getTexGenState(unit); + final int unit = glCtx.activeTextureUnit.getValue(); + final var texGenState = glCtx.textures.getTexGenState(unit); switch (pname) { case GL11.GL_TEXTURE_GEN_MODE -> { texGenState.setMode(coord, (int) params.get(pos)); - texGenGeneration++; + glCtx.texGenGeneration++; } case GL11.GL_OBJECT_PLANE -> { texGenState.setObjectPlane(coord, texGenTempPlane); - texGenGeneration++; + glCtx.texGenGeneration++; } case GL11.GL_EYE_PLANE -> { - texGenState.setEyePlane(coord, texGenTempPlane, modelViewMatrix); - texGenGeneration++; + texGenState.setEyePlane(coord, texGenTempPlane, glCtx.modelViewMatrix); + glCtx.texGenGeneration++; } } } public static void glTexGen(int coord, int pname, IntBuffer params) { + final GLContextState glCtx = ctx(); if (!isCachingEnabled()) return; if (pname == GL11.GL_TEXTURE_GEN_MODE) { - final int unit = activeTextureUnit.getValue(); - textures.getTexGenState(unit).setMode(coord, params.get(params.position())); - texGenGeneration++; + final int unit = glCtx.activeTextureUnit.getValue(); + glCtx.textures.getTexGenState(unit).setMode(coord, params.get(params.position())); + glCtx.texGenGeneration++; } } public static int glGetTexGeni(int coord, int pname) { + final GLContextState glCtx = ctx(); if (pname == GL11.GL_TEXTURE_GEN_MODE) { - return textures.getTexGenState(activeTextureUnit.getValue()).getMode(coord); + return glCtx.textures.getTexGenState(glCtx.activeTextureUnit.getValue()).getMode(coord); } return 0; } @@ -6086,7 +6556,8 @@ public class GLStateManager { } public static void glGetTexGen(int coord, int pname, FloatBuffer params) { - final var state = textures.getTexGenState(activeTextureUnit.getValue()); + final GLContextState glCtx = ctx(); + final var state = glCtx.textures.getTexGenState(glCtx.activeTextureUnit.getValue()); if (pname == GL11.GL_TEXTURE_GEN_MODE) { params.put(params.position(), (float) state.getMode(coord)); } else if (pname == GL11.GL_OBJECT_PLANE) { @@ -6105,7 +6576,8 @@ public class GLStateManager { } public static void glGetTexGen(int coord, int pname, DoubleBuffer params) { - final var state = textures.getTexGenState(activeTextureUnit.getValue()); + final GLContextState glCtx = ctx(); + final var state = glCtx.textures.getTexGenState(glCtx.activeTextureUnit.getValue()); if (pname == GL11.GL_TEXTURE_GEN_MODE) { params.put(params.position(), state.getMode(coord)); } else if (pname == GL11.GL_OBJECT_PLANE) { @@ -6198,9 +6670,12 @@ public class GLStateManager { if (hasVertex || fragmentShader == 0) return; - // Fragment-only program — generate a passthrough vertex shader + // Fragment-only program - generate a passthrough vertex shader final String fragSource = RENDER_BACKEND.getShaderSource(fragmentShader, 65536); - final String vertSource = CompatShaderTransformer.generatePassthroughVertexShader(fragSource); + String vertSource = CompatShaderTransformer.generatePassthroughVertexShader(fragSource); + if (RenderSystem.isGLES()) { + vertSource = CompatShaderTransformer.toGLES(vertSource, GL20.GL_VERTEX_SHADER, false); + } final int vertShader = RENDER_BACKEND.createShader(GL20.GL_VERTEX_SHADER); RENDER_BACKEND.shaderSource(vertShader, vertSource); @@ -6222,7 +6697,12 @@ public class GLStateManager { if (program == 0) return; CompatUniformManager.onDeleteProgram(program); - if (activeProgram == program) activeProgram = 0; + // GL defers deletion of a bound program until unbind; activeProgram stays set so the + // cache matches GL_CURRENT_PROGRAM and the next glUseProgram is not skipped as redundant. + if (GLSMHooks.PROGRAM_DELETE.hasListeners()) { + GLSMHooks.programDeleteEvent.program = program; + GLSMHooks.PROGRAM_DELETE.post(GLSMHooks.programDeleteEvent); + } RENDER_BACKEND.deleteProgram(program); } @@ -6290,7 +6770,60 @@ public class GLStateManager { return RENDER_BACKEND.isShader(obj); } - public static void glBindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { RENDER_BACKEND.bindImageTexture(unit, texture, level, layered, layer, access, format); } + public static void glBindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { + final GLContextState glCtx = ctx(); + final ImageUnitBinding binding = glCtx.imageUnits.get(unit); + if (binding == null) { + warnOnce("imageUnitRange", "glBindImageTexture unit {} exceeds GL_MAX_IMAGE_UNITS {}", unit, glCtx.imageUnits.size()); + } else { + binding.setBinding(texture, level, layered, layer, access, format); + if (texture != 0 && unit > glCtx.maxBoundImageUnit) glCtx.maxBoundImageUnit = unit; + } + RENDER_BACKEND.bindImageTexture(unit, texture, level, layered, layer, access, format); + } + + public static ImageUnitBinding getImageUnitBinding(int unit) { + return ctx().imageUnits.get(unit); + } + + private static int imageBindingOrBackend(int pname, int index) { + final ImageUnitBinding binding = !isCachingEnabled() ? null : ctx().imageUnits.get(index); + if (binding == null) return RENDER_BACKEND.getIntegerIndexed(pname, index); + return switch (pname) { + case GL42.GL_IMAGE_BINDING_NAME -> binding.getTexture(); + case GL42.GL_IMAGE_BINDING_LEVEL -> binding.getLevel(); + case GL42.GL_IMAGE_BINDING_LAYERED -> binding.isLayered() ? GL11.GL_TRUE : GL11.GL_FALSE; + case GL42.GL_IMAGE_BINDING_LAYER -> binding.getLayer(); + case GL42.GL_IMAGE_BINDING_ACCESS -> binding.getAccess(); + case GL42.GL_IMAGE_BINDING_FORMAT -> binding.getFormat(); + default -> RENDER_BACKEND.getIntegerIndexed(pname, index); + }; + } + + public static int glGetInteger(int pname, int index) { + return imageBindingOrBackend(pname, index); + } + + public static int glGetIntegeri(int pname, int index) { + return imageBindingOrBackend(pname, index); + } + + public static void glGetIntegeri(int pname, int index, IntBuffer params) { + glGetIntegeri_v(pname, index, params); + } + + public static void glGetIntegeri_v(int pname, int index, IntBuffer params) { + params.put(params.position(), imageBindingOrBackend(pname, index)); + } + + public static void glGetBooleani_v(int pname, int index, ByteBuffer params) { + params.put(params.position(), (byte) (imageBindingOrBackend(pname, index) != 0 ? GL11.GL_TRUE : GL11.GL_FALSE)); + } + + public static void glGetBooleani(int pname, int index, ByteBuffer params) { + glGetBooleani_v(pname, index, params); + } + public static void glMemoryBarrier(int barriers) { RENDER_BACKEND.memoryBarrier(barriers); } public static void glCopyImageSubData(int srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, int dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, @@ -6467,6 +7000,14 @@ public class GLStateManager { RENDER_BACKEND.getActiveUniform(program, index, length, size, type, name); } + public static void glGetActiveAttrib(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) { + RENDER_BACKEND.getActiveAttrib(program, index, length, size, type, name); + } + + public static String glGetActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) { + return RENDER_BACKEND.getActiveAttrib(program, index, maxLength, sizeType); + } + public static void glGetAttachedShaders(int program, IntBuffer count, IntBuffer shaders) { RENDER_BACKEND.getAttachedShaders(program, count, shaders); } @@ -6499,4 +7040,412 @@ public class GLStateManager { || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP || drawMode == GL11.GL_QUAD_STRIP || drawMode == GL11.GL_POLYGON; } + + public static int getProgramGeneration() { + return ctx().programGeneration; + } + + public static int getDrawFramebufferGeneration() { + return ctx().drawFramebufferGeneration; + } + + public static boolean isPoppingAttributes() { + return ctx().poppingAttributes; + } + + public static int getMvGeneration() { + return ctx().mvGeneration; + } + + public static int getMvLinearGeneration() { + return ctx().mvLinearGeneration; + } + + public static int getProjGeneration() { + return ctx().projGeneration; + } + + public static int getTexMatrixGeneration() { + return ctx().texMatrixGeneration; + } + + public static int getLightingGeneration() { + return ctx().lightingGeneration; + } + + public static int getFragmentGeneration() { + return ctx().fragmentGeneration; + } + + public static int getColorGeneration() { + return ctx().colorGeneration; + } + + public static int getClipPlaneGeneration() { + return ctx().clipPlaneGeneration; + } + + public static float getOverlayR() { + return ctx().overlayR; + } + + public static float getOverlayG() { + return ctx().overlayG; + } + + public static float getOverlayB() { + return ctx().overlayB; + } + + public static float getOverlayA() { + return ctx().overlayA; + } + + public static float getShaderColorR() { + return ctx().shaderColorR; + } + + public static float getShaderColorG() { + return ctx().shaderColorG; + } + + public static float getShaderColorB() { + return ctx().shaderColorB; + } + + public static float getShaderColorA() { + return ctx().shaderColorA; + } + + public static int getAttribDepth() { + return ctx().attribDepth; + } + + public static IntegerStateStack getActiveTextureUnitStack() { + return ctx().activeTextureUnit; + } + + public static IntegerStateStack getShadeModelState() { + return ctx().shadeModelState; + } + + public static TextureUnitArray getTextures() { + return ctx().textures; + } + + public static BlendStateStack getBlendState() { + return ctx().blendState; + } + + public static BooleanStateStack getBlendMode() { + return ctx().blendMode; + } + + public static BooleanStateStack getScissorTest() { + return ctx().scissorTest; + } + + public static DepthStateStack getDepthState() { + return ctx().depthState; + } + + public static BooleanStateStack getDepthTest() { + return ctx().depthTest; + } + + public static FogStateStack getFogState() { + return ctx().fogState; + } + + public static BooleanStateStack getFogMode() { + return ctx().fogMode; + } + + public static Color4Stack getColor() { + return ctx().color; + } + + public static Color4Stack getClearColor() { + return ctx().clearColor; + } + + public static ColorMaskStack getColorMask() { + return ctx().colorMask; + } + + public static IntegerStateStack getDrawBuffer() { + return ctx().drawBuffer; + } + + public static IntegerStateStack getLogicOpMode() { + return ctx().logicOpMode; + } + + public static BooleanStateStack getCullState() { + return ctx().cullState; + } + + public static AlphaStateStack getAlphaState() { + return ctx().alphaState; + } + + public static BooleanStateStack getAlphaTest() { + return ctx().alphaTest; + } + + public static BooleanStateStack getLightingState() { + return ctx().lightingState; + } + + public static BooleanStateStack getRescaleNormalState() { + return ctx().rescaleNormalState; + } + + public static BooleanStateStack getNormalizeState() { + return ctx().normalizeState; + } + + public static BooleanStateStack getDitherState() { + return ctx().ditherState; + } + + public static BooleanStateStack getStencilTest() { + return ctx().stencilTest; + } + + public static BooleanStateStack getLineSmoothState() { + return ctx().lineSmoothState; + } + + public static BooleanStateStack getLineStippleState() { + return ctx().lineStippleState; + } + + public static BooleanStateStack getPointSmoothState() { + return ctx().pointSmoothState; + } + + public static BooleanStateStack getPolygonSmoothState() { + return ctx().polygonSmoothState; + } + + public static BooleanStateStack getPolygonStippleState() { + return ctx().polygonStippleState; + } + + public static BooleanStateStack getMultisampleState() { + return ctx().multisampleState; + } + + public static BooleanStateStack getSampleAlphaToCoverageState() { + return ctx().sampleAlphaToCoverageState; + } + + public static BooleanStateStack getSampleAlphaToOneState() { + return ctx().sampleAlphaToOneState; + } + + public static BooleanStateStack getSampleCoverageState() { + return ctx().sampleCoverageState; + } + + public static BooleanStateStack getColorLogicOpState() { + return ctx().colorLogicOpState; + } + + public static BooleanStateStack getIndexLogicOpState() { + return ctx().indexLogicOpState; + } + + public static BooleanStateStack getPolygonOffsetPointState() { + return ctx().polygonOffsetPointState; + } + + public static BooleanStateStack getPolygonOffsetLineState() { + return ctx().polygonOffsetLineState; + } + + public static BooleanStateStack getPolygonOffsetFillState() { + return ctx().polygonOffsetFillState; + } + + public static LineStateStack getLineState() { + return ctx().lineState; + } + + public static PointStateStack getPointState() { + return ctx().pointState; + } + + public static PolygonStateStack getPolygonState() { + return ctx().polygonState; + } + + public static StencilStateStack getStencilState() { + return ctx().stencilState; + } + + public static BooleanStateStack getAutoNormalState() { + return ctx().autoNormalState; + } + + public static BooleanStateStack getMap1Color4State() { + return ctx().map1Color4State; + } + + public static BooleanStateStack getMap1IndexState() { + return ctx().map1IndexState; + } + + public static BooleanStateStack getMap1NormalState() { + return ctx().map1NormalState; + } + + public static BooleanStateStack getMap1TextureCoord1State() { + return ctx().map1TextureCoord1State; + } + + public static BooleanStateStack getMap1TextureCoord2State() { + return ctx().map1TextureCoord2State; + } + + public static BooleanStateStack getMap1TextureCoord3State() { + return ctx().map1TextureCoord3State; + } + + public static BooleanStateStack getMap1TextureCoord4State() { + return ctx().map1TextureCoord4State; + } + + public static BooleanStateStack getMap1Vertex3State() { + return ctx().map1Vertex3State; + } + + public static BooleanStateStack getMap1Vertex4State() { + return ctx().map1Vertex4State; + } + + public static BooleanStateStack getMap2Color4State() { + return ctx().map2Color4State; + } + + public static BooleanStateStack getMap2IndexState() { + return ctx().map2IndexState; + } + + public static BooleanStateStack getMap2NormalState() { + return ctx().map2NormalState; + } + + public static BooleanStateStack getMap2TextureCoord1State() { + return ctx().map2TextureCoord1State; + } + + public static BooleanStateStack getMap2TextureCoord2State() { + return ctx().map2TextureCoord2State; + } + + public static BooleanStateStack getMap2TextureCoord3State() { + return ctx().map2TextureCoord3State; + } + + public static BooleanStateStack getMap2TextureCoord4State() { + return ctx().map2TextureCoord4State; + } + + public static BooleanStateStack getMap2Vertex3State() { + return ctx().map2Vertex3State; + } + + public static BooleanStateStack getMap2Vertex4State() { + return ctx().map2Vertex4State; + } + + public static BooleanStateStack[] getClipPlaneStates() { + return ctx().clipPlaneStates; + } + + public static ClipPlaneState getClipPlaneState() { + return ctx().clipPlaneState; + } + + public static MatrixModeStack getMatrixMode() { + return ctx().matrixMode; + } + + public static Matrix4fStack getModelViewMatrix() { + return ctx().modelViewMatrix; + } + + public static Matrix4fStack getProjectionMatrix() { + return ctx().projectionMatrix; + } + + public static BooleanStateStack[] getLightStates() { + return ctx().lightStates; + } + + public static LightStateStack[] getLightDataStates() { + return ctx().lightDataStates; + } + + public static BooleanStateStack getColorMaterial() { + return ctx().colorMaterial; + } + + public static IntegerStateStack getColorMaterialFace() { + return ctx().colorMaterialFace; + } + + public static IntegerStateStack getColorMaterialParameter() { + return ctx().colorMaterialParameter; + } + + public static LightModelStateStack getLightModel() { + return ctx().lightModel; + } + + public static MaterialStateStack getFrontMaterial() { + return ctx().frontMaterial; + } + + public static MaterialStateStack getBackMaterial() { + return ctx().backMaterial; + } + + public static ViewPortStateStack getViewportState() { + return ctx().viewportState; + } + + public static int getActiveProgram() { + return ctx().activeProgram; + } + + public static int getListBase() { + return ctx().listBase; + } + + public static int getBoundVBO() { + return ctx().boundVBO; + } + + public static int getBoundVAO() { + return ctx().boundVAO; + } + + public static int getDrawFramebuffer() { + return ctx().drawFramebuffer; + } + + public static int getReadFramebuffer() { + return ctx().readFramebuffer; + } + + public static int getTexGenGeneration() { + return ctx().texGenGeneration; + } + + public static void incrementFragmentGeneration() { + ctx().fragmentGeneration++; + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLTypes.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLTypes.java new file mode 100644 index 000000000..c90c55261 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLTypes.java @@ -0,0 +1,57 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL30; + +public final class GLTypes { + + private GLTypes() {} + + public static int sizeBytes(int glType) { + return switch (glType) { + case GL11.GL_BYTE, GL11.GL_UNSIGNED_BYTE -> 1; + case GL11.GL_SHORT, GL11.GL_UNSIGNED_SHORT, GL30.GL_HALF_FLOAT -> 2; + case GL11.GL_INT, GL11.GL_UNSIGNED_INT, GL11.GL_FLOAT -> 4; + case GL11.GL_DOUBLE -> 8; + default -> throw new IllegalArgumentException("Unknown GL type: 0x" + Integer.toHexString(glType)); + }; + } + + public static int packedTexelBytes(int glType) { + return switch (glType) { + case GL12.GL_UNSIGNED_BYTE_3_3_2, GL12.GL_UNSIGNED_BYTE_2_3_3_REV -> 1; + case GL12.GL_UNSIGNED_SHORT_5_6_5, GL12.GL_UNSIGNED_SHORT_5_6_5_REV, + GL12.GL_UNSIGNED_SHORT_4_4_4_4, GL12.GL_UNSIGNED_SHORT_4_4_4_4_REV, + GL12.GL_UNSIGNED_SHORT_5_5_5_1, GL12.GL_UNSIGNED_SHORT_1_5_5_5_REV -> 2; + case GL12.GL_UNSIGNED_INT_8_8_8_8, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, + GL12.GL_UNSIGNED_INT_10_10_10_2, GL12.GL_UNSIGNED_INT_2_10_10_10_REV, + GL30.GL_UNSIGNED_INT_24_8, GL30.GL_UNSIGNED_INT_10F_11F_11F_REV, + GL30.GL_UNSIGNED_INT_5_9_9_9_REV -> 4; + case GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV -> 8; + default -> 0; + }; + } + + public static String name(int glType) { + return switch (glType) { + case GL11.GL_BYTE -> "BYTE"; + case GL11.GL_UNSIGNED_BYTE -> "UNSIGNED_BYTE"; + case GL11.GL_SHORT -> "SHORT"; + case GL11.GL_UNSIGNED_SHORT -> "UNSIGNED_SHORT"; + case GL11.GL_INT -> "INT"; + case GL11.GL_UNSIGNED_INT -> "UNSIGNED_INT"; + case GL11.GL_FLOAT -> "FLOAT"; + case GL11.GL_DOUBLE -> "DOUBLE"; + case GL30.GL_HALF_FLOAT -> "HALF_FLOAT"; + case GL12.GL_UNSIGNED_BYTE_3_3_2 -> "UNSIGNED_BYTE_3_3_2"; + case GL12.GL_UNSIGNED_SHORT_4_4_4_4 -> "UNSIGNED_SHORT_4_4_4_4"; + case GL12.GL_UNSIGNED_SHORT_5_5_5_1 -> "UNSIGNED_SHORT_5_5_5_1"; + case GL12.GL_UNSIGNED_INT_8_8_8_8 -> "UNSIGNED_INT_8_8_8_8"; + case GL12.GL_UNSIGNED_INT_8_8_8_8_REV -> "UNSIGNED_INT_8_8_8_8_REV"; + case GL12.GL_UNSIGNED_INT_10_10_10_2 -> "UNSIGNED_INT_10_10_10_2"; + case GL12.GL_UNSIGNED_INT_2_10_10_10_REV -> "UNSIGNED_INT_2_10_10_10_REV"; + default -> String.format("0x%X", glType); + }; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java index 72334ac1a..461f29bfa 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java @@ -1,10 +1,19 @@ package com.gtnewhorizons.angelica.glsm; +import org.antlr.v4.runtime.BufferedTokenStream; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLPreParser; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -79,6 +88,77 @@ public class GlslTransformUtils { return source; } + public record QuietParse(GLSLParser.Translation_unitContext full, GLSLPreParser.Translation_unitContext pre) {} + + public static GLSLParser.Translation_unitContext parseFullQuiet(String source) { + final GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(source)); + lexer.removeErrorListeners(); + final GLSLParser parser = new GLSLParser(new CommonTokenStream(lexer)); + parser.removeErrorListeners(); + parser.setBuildParseTree(true); + return parser.translation_unit(); + } + + public static GLSLPreParser.Translation_unitContext parsePreQuiet(String source) { + final GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(source)); + lexer.removeErrorListeners(); + final GLSLPreParser preParser = new GLSLPreParser(new CommonTokenStream(lexer, GLSLLexer.DIRECTIVES)); + preParser.removeErrorListeners(); + preParser.setBuildParseTree(true); + return preParser.translation_unit(); + } + + public static QuietParse parseBothQuiet(String source) { + final GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(source)); + lexer.removeErrorListeners(); + final GLSLPreParser preParser = new GLSLPreParser(new BufferedTokenStream(lexer)); + preParser.removeErrorListeners(); + preParser.setBuildParseTree(true); + final GLSLPreParser.Translation_unitContext pre = preParser.translation_unit(); + lexer.reset(); + final GLSLParser parser = new GLSLParser(new CommonTokenStream(lexer)); + parser.removeErrorListeners(); + parser.setBuildParseTree(true); + return new QuietParse(parser.translation_unit(), pre); + } + + public static Set identifiersInDirectiveText(String source) { + final GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(source)); + lexer.removeErrorListeners(); + final BufferedTokenStream tokens = new BufferedTokenStream(lexer); + tokens.fill(); + + final Set names = new HashSet<>(); + for (Token token : tokens.getTokens()) { + switch (token.getType()) { + case GLSLLexer.PROGRAM_TEXT, GLSLLexer.MACRO_TEXT, GLSLLexer.CONSTANT_EXPRESSION -> collectIdentifiers(token.getText(), names); + default -> { } + } + } + return names; + } + + private static void collectIdentifiers(String text, Set out) { + if (text == null) return; + final int len = text.length(); + int i = 0; + while (i < len) { + final char c = text.charAt(i); + if (c != '_' && !Character.isLetter(c)) { + i++; + continue; + } + int end = i + 1; + while (end < len) { + final char n = text.charAt(end); + if (n != '_' && !Character.isLetterOrDigit(n)) break; + end++; + } + out.add(text.substring(i, end)); + i = end; + } + } + public static String getFormattedShader(ParseTree tree, String header) { final StringBuilder sb = new StringBuilder(header + "\n"); final String[] tabHolder = {""}; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java index 79fc36b8b..b018f9959 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java @@ -90,13 +90,33 @@ public final class QuadConverter { drawSharedQuadEbo(first, vertexCount, primcount, true); } + private static int misalignedDraws; + private static void drawSharedQuadEbo(int first, int vertexCount, int primcount, boolean instanced) { + final int quadCount = vertexCount / 4; + if ((first & 3) != 0) { + misalignedDraws++; + if ((misalignedDraws & (misalignedDraws - 1)) == 0) { + GLStateManager.LOGGER.warn("QuadConverter: quad draw with unaligned first={} count={} (#{}) -- using scratch indices", first, vertexCount, misalignedDraws); + } + final ByteBuffer dst = memAlloc(quadCount * 6 * 4); + long ptr = memAddress0(dst); + for (int i = 0; i < quadCount; i++) { + final int base = first + i * 4; + memPutInt(ptr, base); + memPutInt(ptr + 4, base + 1); + memPutInt(ptr + 8, base + 3); + memPutInt(ptr + 12, base + 1); + memPutInt(ptr + 16, base + 2); + memPutInt(ptr + 20, base + 3); + ptr += 24; + } + uploadAndDraw(dst, quadCount * 6, GL11.GL_UNSIGNED_INT, 4, primcount, instanced); + return; + } final boolean locked = GLStateManager.acquireDrawLock(); try { GLStateManager.preDraw(); - assert first % 4 == 0 : "QuadConverter: first (" + first + ") must be a multiple of 4"; - assert vertexCount % 4 == 0 : "QuadConverter: vertexCount (" + vertexCount + ") must be a multiple of 4"; - final int quadCount = vertexCount / 4; final int prevEbo = GLStateManager.getBoundEBO(); ensureCapacity(first / 4 + quadCount); RENDER_BACKEND.bindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId); @@ -184,7 +204,7 @@ public final class QuadConverter { final int quadCount = indexCount / 4; final int triIndexCount = quadCount * 6; - final int bytesPerIndex = VAOManager.Attrib.glTypeSizeBytes(type); + final int bytesPerIndex = GLTypes.sizeBytes(type); final ByteBuffer src = memAlloc(indexCount * bytesPerIndex); RENDER_BACKEND.getBufferSubData(GL15.GL_ELEMENT_ARRAY_BUFFER, offset, src); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java index 7dc3e4e1a..c66ab5457 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java @@ -18,6 +18,7 @@ import org.lwjgl.opengl.ARBShaderStorageBufferObject; import org.lwjgl.opengl.EXTShaderImageLoadStore; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GL42; import org.lwjgl.opengl.GL43; @@ -40,6 +41,7 @@ public class RenderSystem { private static boolean supportsCompute; private static boolean supportsImageLoadStore; private static boolean supportsSSBO; + private static boolean supportsMultiDrawIndirect; private static boolean supportsBufferStorage; private static boolean supportsClearTexture; private static boolean supportsTesselation; @@ -52,6 +54,11 @@ public class RenderSystem { @Getter private static int glMinor; @Getter private static boolean coreProfile; + private static volatile boolean isGLES; + private static volatile int glesVersion; + private static volatile boolean glesDetected; + private static volatile boolean hasClipCullDistance; + // Sampler object state tracking (null if unsupported) private static int[] samplers; @@ -64,30 +71,38 @@ public class RenderSystem { public static void initRenderer() { if (rendererInitialized) return; rendererInitialized = true; - try { - if (GLStateManager.vendorIsIntel() && GLStateManager.isWindows()) { - dsaState = new DSAUnsupported(); - GLStateManager.LOGGER.info("Detected Intel drivers on Windows, disabling DSA."); - } else if (!GLStateManager.getInitConfig().isDSAEnabled()) { - dsaState = new DSAUnsupported(); - GLStateManager.LOGGER.info("enableDSA is set to false, disabling DSA."); - } else if (GLStateManager.capabilities.OpenGL45) { - dsaState = (Runtime.version().feature() > 8 && GLStateManager.capabilities.GL_EXT_direct_state_access) ? new DSAEXT() : new DSACore(); - GLStateManager.LOGGER.info("OpenGL 4.5 detected, enabling DSA."); - } - } catch (NoSuchFieldError ignored) { + final boolean wasDetected = glesDetected; + if (isGLES() && !wasDetected) { + GLStateManager.LOGGER.info("OpenGL ES {}.{} detected", glesVersion / 100, (glesVersion / 10) % 10); } - try { - if (dsaState == null && GLStateManager.capabilities.GL_ARB_direct_state_access) { - dsaState = new DSAARB(); - GLStateManager.LOGGER.info("ARB_direct_state_access detected, enabling DSA."); + + if (!isGLES) { + try { + if (GLStateManager.vendorIsIntel() && GLStateManager.isWindows()) { + dsaState = new DSAUnsupported(); + GLStateManager.LOGGER.info("Detected Intel drivers on Windows, disabling DSA."); + } else if (!GLStateManager.getInitConfig().isDSAEnabled()) { + dsaState = new DSAUnsupported(); + GLStateManager.LOGGER.info("enableDSA is set to false, disabling DSA."); + } else if (GLStateManager.capabilities.OpenGL45) { + dsaState = (Runtime.version().feature() > 8 && GLStateManager.capabilities.GL_EXT_direct_state_access) ? new DSAEXT() : new DSACore(); + GLStateManager.LOGGER.info("OpenGL 4.5 detected, enabling DSA."); + } + + } catch (NoSuchFieldError ignored) { + } + try { + if (dsaState == null && GLStateManager.capabilities.GL_ARB_direct_state_access) { + dsaState = new DSAARB(); + GLStateManager.LOGGER.info("ARB_direct_state_access detected, enabling DSA."); + } + } catch (NoSuchFieldError ignored) { } - } catch (NoSuchFieldError ignored) { } if (dsaState == null) { dsaState = new DSAUnsupported(); - GLStateManager.LOGGER.info("No DSA support detected, falling back to legacy OpenGL."); + GLStateManager.LOGGER.info("{}", isGLES ? "GLES context, using DSAUnsupported (bind-based) fallback." : "No DSA support detected, falling back to legacy OpenGL."); } BackendManager.init(); @@ -99,8 +114,10 @@ public class RenderSystem { || GLStateManager.capabilities.GL_ARB_shader_image_load_store || GLStateManager.capabilities.GL_EXT_shader_image_load_store; supportsSSBO = GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_shader_storage_buffer_object; - supportsBufferStorage = GLStateManager.capabilities.OpenGL44 || GLStateManager.capabilities.GL_ARB_buffer_storage; + supportsMultiDrawIndirect = GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_multi_draw_indirect; + supportsBufferStorage = !isGLES && (GLStateManager.capabilities.OpenGL44 || GLStateManager.capabilities.GL_ARB_buffer_storage); supportsClearTexture = GLStateManager.capabilities.OpenGL44 || GLStateManager.capabilities.GL_ARB_clear_texture; + hasClipCullDistance = !isGLES || hasExtension("GL_EXT_clip_cull_distance"); // Cache maximum image units if (supportsImageLoadStore) { @@ -140,7 +157,10 @@ public class RenderSystem { GLStateManager.LOGGER.info("SSBO: {}, Max SSBO Bindings: {}", supportsSSBO, maxSSBOBindings); GLStateManager.LOGGER.info("Buffer Storage: {}, Clear Texture: {}, Sampler Objects: {}", supportsBufferStorage, supportsClearTexture, supportsSamplerObjects); - if (GLStateManager.capabilities.OpenGL32) { + if (isGLES) { + GLStateManager.LOGGER.info("GL ES context detected, enabling shader transformer."); + ShaderManager.getInstance().enable(); + } else if (GLStateManager.capabilities.OpenGL32) { final int profileMask = RENDER_BACKEND.getInteger(GL32.GL_CONTEXT_PROFILE_MASK); if ((profileMask & GL32.GL_CONTEXT_CORE_PROFILE_BIT) != 0) { coreProfile = true; @@ -168,6 +188,10 @@ public class RenderSystem { } public static void texImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) { + final GLStateManager.GLESTexImageRemap remap = GLStateManager.remapTexImageForGLES(internalformat, format, type); + internalformat = remap.internalFormat(); + format = remap.format(); + type = remap.type(); GLStateManager.glBindTexture(target, texture); GLStateManager.suspendPixelUnpackBuffer(); RENDER_BACKEND.texImage2D(target, level, internalformat, width, height, border, format, type, pixels); @@ -327,12 +351,16 @@ public class RenderSystem { return dsaState.getTexParameteri(texture, target, pname); } + public static float getTexParameterf(int texture, int target, int pname) { + return dsaState.getTexParameterf(texture, target, pname); + } + public static int getTexLevelParameteri(int texture, int level, int pname) { return dsaState.getTexLevelParameteri(texture, level, pname); } public static void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { - RENDER_BACKEND.bindImageTexture(unit, texture, level, layered, layer, access, format); + GLStateManager.glBindImageTexture(unit, texture, level, layered, layer, access, format); } public static int getMaxImageUnits() { @@ -340,13 +368,49 @@ public class RenderSystem { } public static boolean supportsImageLoadStore() { + if (RENDER_BACKEND.isSDLGPU()) return true; return supportsImageLoadStore; } + public static boolean hasClipCullDistance() { + return hasClipCullDistance; + } + + private static boolean hasExtension(String name) { + final int count = GLStateManager.glGetInteger(GL30.GL_NUM_EXTENSIONS); + for (int i = 0; i < count; i++) { + if (name.equals(GLStateManager.glGetStringi(GL11.GL_EXTENSIONS, i))) return true; + } + return false; + } + + public static boolean isGLES() { + if (!glesDetected) detectGLES(); + return isGLES; + } + + private static synchronized void detectGLES() { + if (glesDetected) return; + try { + final String v = RENDER_BACKEND.getString(GL11.GL_VERSION); + if (v != null && v.startsWith("OpenGL ES ")) { + isGLES = true; + glesVersion = Integer.parseInt(parseGlVersionString(v)); + } + glesDetected = true; + } catch (Throwable ignored) { + // No GL context on this thread yet (splash); retry on next call. + } + } + public static boolean supportsSSBO() { return supportsSSBO; } + public static boolean supportsMultiDrawIndirect() { + return supportsMultiDrawIndirect; + } + public static boolean supportsBufferStorage() { return supportsBufferStorage; } @@ -427,9 +491,14 @@ public class RenderSystem { GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); } - public static void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, - int height2, int bufferChoice, int filter) { - dsaState.blitFramebuffer(source, dest, offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter); + public static void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) { + final boolean scissor = GLStateManager.glIsEnabled(GL11.GL_SCISSOR_TEST); + if (scissor) GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + try { + dsaState.blitFramebuffer(source, dest, offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter); + } finally { + if (scissor) GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + } } public static int createFramebuffer() { @@ -443,7 +512,7 @@ public class RenderSystem { // TODO: Proper notification of compute support public static boolean supportsCompute() { try { - return GLStateManager.capabilities.GL_ARB_compute_shader; + return GLStateManager.capabilities.GL_ARB_compute_shader || GLStateManager.capabilities.OpenGL43; } catch (Exception ignored) { return false; } @@ -453,6 +522,10 @@ public class RenderSystem { return GLStateManager.glGenBuffers(); } + public static int getIndexedBufferBinding(int target, int index) { + return RENDER_BACKEND.getIndexedBufferBinding(target, index); + } + public static void bindBufferBase(int target, int index, int buffer) { RENDER_BACKEND.bindBufferBase(target, index, buffer); } @@ -505,6 +578,7 @@ public class RenderSystem { } public static boolean supportsSnormFormats() { + if (isGLES()) return false; return GLStateManager.capabilities.OpenGL31; } @@ -552,9 +626,17 @@ public class RenderSystem { } } - /** Parse a GL version string (e.g. "4.6.0 NVIDIA ...") into concatenated digits "460" */ - static String parseGlVersionString(String info) { - final Matcher matcher = SEMVER_PATTERN.matcher(Objects.requireNonNull(info)); + /** Parse a GL version string (e.g. "4.6.0 NVIDIA ...") into concatenated digits "460". Strips + * "OpenGL ES " / "OpenGL ES GLSL ES " prefixes so ES contexts parse too. */ + public static String parseGlVersionString(String info) { + Objects.requireNonNull(info); + String stripped = info; + if (stripped.startsWith("OpenGL ES GLSL ES ")) { + stripped = stripped.substring("OpenGL ES GLSL ES ".length()); + } else if (stripped.startsWith("OpenGL ES ")) { + stripped = stripped.substring("OpenGL ES ".length()); + } + final Matcher matcher = SEMVER_PATTERN.matcher(stripped); if (!matcher.matches()) { throw new IllegalStateException("Could not parse GL version from \"" + info + "\""); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/GLDebugMessageListener.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/GLDebugMessageListener.java new file mode 100644 index 000000000..0a46db301 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/GLDebugMessageListener.java @@ -0,0 +1,5 @@ +package com.gtnewhorizons.angelica.glsm.backend; + +public interface GLDebugMessageListener { + void onMessage(int source, int type, int id, int severity, int length, long message, long userParam); +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/Lwjgl2GLRenderBackend.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/Lwjgl2GLRenderBackend.java index 94b40d20d..094c3cb90 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/Lwjgl2GLRenderBackend.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/Lwjgl2GLRenderBackend.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm.backend; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.AMDDebugOutput; import org.lwjgl.opengl.AMDDebugOutputCallback; @@ -7,8 +8,10 @@ import org.lwjgl.opengl.ARBClearTexture; import org.lwjgl.opengl.ARBDebugOutput; import org.lwjgl.opengl.ARBDebugOutputCallback; import org.lwjgl.opengl.ARBDirectStateAccess; +import org.lwjgl.opengl.ARBTimerQuery; import org.lwjgl.opengl.ContextCapabilities; import org.lwjgl.opengl.EXTDirectStateAccess; +import org.lwjgl.opengl.EXTShaderImageLoadStore; import org.lwjgl.opengl.GLContext; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -27,6 +30,8 @@ import org.lwjgl.opengl.GL44; import org.lwjgl.opengl.GL45; import org.lwjgl.opengl.KHRDebug; import org.lwjgl.opengl.KHRDebugCallback; +import org.lwjgl.opengl.Display; + import java.nio.ByteBuffer; import java.nio.DoubleBuffer; @@ -96,9 +101,26 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { } } + @Override + public boolean isCurrent() { + try { + return Display.isCurrent(); + } catch (Exception e) { + return false; + } + } + @Override public int getMinGLSLVersion() {return 330;} + @Override + public void setVSyncEnabled(boolean enabled) {Display.setVSyncEnabled(enabled);} + + @Override + public boolean isAnisotropicSupported() { + return caps != null && caps.GL_EXT_texture_filter_anisotropic; + } + @Override public void flush() {GL11.glFlush();} @@ -322,7 +344,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { @Override public void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { - org.lwjgl.opengl.GL43.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride); + GL43.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride); } @Override @@ -332,8 +354,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { @Override public void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) { - // On GL path, LWJGL3 service dispatches directly. This is only called via VulkanRenderBackend. - throw new UnsupportedOperationException("GLRenderBackend.drawElementsBaseVertex should not be called — LWJGL service handles this"); + GL32.glDrawElementsBaseVertex(mode, count, type, indices, baseVertex); } @Override @@ -927,6 +948,32 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { GL30.glBindBufferBase(target, index, buffer); } + @Override + public void bindBufferRange(int target, int index, int buffer, long offset, long size) { + GL30.glBindBufferRange(target, index, buffer, offset, size); + } + + @Override + public int getUniformBlockIndex(int program, CharSequence name) { + return GL31.glGetUniformBlockIndex(program, name); + } + + @Override + public void uniformBlockBinding(int program, int blockIndex, int binding) { + GL31.glUniformBlockBinding(program, blockIndex, binding); + } + + @Override + public int getIndexedBufferBinding(int target, int index) { + final int pname = (target == GL43.GL_SHADER_STORAGE_BUFFER) ? GL43.GL_SHADER_STORAGE_BUFFER_BINDING : GL31.GL_UNIFORM_BUFFER_BINDING; + return GL30.glGetInteger(pname, index); + } + + @Override + public int getIntegerIndexed(int pname, int index) { + return GL30.glGetInteger(pname, index); + } + @Override public void bufferData(int target, long size, int usage) { GL15.glBufferData(target, size, usage); @@ -1058,6 +1105,16 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { return GL15.glIsBuffer(buffer); } + @Override + public boolean isTexture(int texture) { + return GL11.glIsTexture(texture); + } + + @Override public boolean isFramebuffer(int framebuffer) { return GL30.glIsFramebuffer(framebuffer); } + @Override public boolean isRenderbuffer(int renderbuffer) { return GL30.glIsRenderbuffer(renderbuffer); } + @Override public boolean isSampler(int sampler) { return GL33.glIsSampler(sampler); } + @Override public boolean isQuery(int query) { return GL15.glIsQuery(query); } + @Override public ByteBuffer mapBufferRange(int target, long offset, long length, int access) { return GL30.glMapBufferRange(target, offset, length, access, null); @@ -1284,6 +1341,11 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { return ARBDirectStateAccess.glGetTextureParameteri(texture, pname); } + @Override + public float getTextureParameterf(int texture, int target, int pname) { + return ARBDirectStateAccess.glGetTextureParameterf(texture, pname); + } + @Override public int getTextureLevelParameteri(int texture, int level, int pname) { return ARBDirectStateAccess.glGetTextureLevelParameteri(texture, level, pname); @@ -1350,6 +1412,66 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { LWJGL.glDeleteSync(sync); } + @Override + public boolean supportsGpuProfiling() { + if (!caps.OpenGL33 && !caps.GL_ARB_timer_query) return false; + return GL15.glGetQuery(GL33.GL_TIMESTAMP, GL15.GL_QUERY_COUNTER_BITS) > 0; + } + + @Override + public int genQuery() { + return GL15.glGenQueries(); + } + + @Override + public void deleteQuery(int query) { + GL15.glDeleteQueries(query); + } + + @Override + public void queryCounter(int query) { + if (caps.OpenGL33) { + GL33.glQueryCounter(query, GL33.GL_TIMESTAMP); + } else { + ARBTimerQuery.glQueryCounter(query, GL33.GL_TIMESTAMP); + } + } + + @Override + public boolean isQueryResultAvailable(int query) { + return GL15.glGetQueryObjecti(query, GL15.GL_QUERY_RESULT_AVAILABLE) != 0; + } + + @Override + public long getQueryResult64(int query) { + return caps.OpenGL33 ? GL33.glGetQueryObjectui64(query, GL15.GL_QUERY_RESULT) : ARBTimerQuery.glGetQueryObjectui64(query, GL15.GL_QUERY_RESULT); + } + + @Override + public long getGpuTimestamp() { + return GL32.glGetInteger64(GL33.GL_TIMESTAMP); + } + + @Override public void genQueries(IntBuffer ids) { GL15.glGenQueries(ids); } + @Override public int genQueries() { return GL15.glGenQueries(); } + @Override public void deleteQueries(int id) { GL15.glDeleteQueries(id); } + @Override public void beginQuery(int target, int id) { GL15.glBeginQuery(target, id); } + @Override public void endQuery(int target) { GL15.glEndQuery(target); } + @Override public void getQueryObjectui(int id, int pname, IntBuffer params) { GL15.glGetQueryObjectu(id, pname, params); } + @Override public int getQueryObjecti(int id, int pname) { return GL15.glGetQueryObjecti(id, pname); } + + @Override public void waitSync(long sync, int flags, long timeout) { LWJGL.glWaitSync(sync, flags, timeout); } + @Override public int getSynci(long sync, int pname, IntBuffer length) { return LWJGL.glGetSynci(sync, pname, length); } + @Override public void queryCounter(int id, int target) { + if (caps.OpenGL33) GL33.glQueryCounter(id, target); else ARBTimerQuery.glQueryCounter(id, target); + } + @Override public long getQueryObjectui64(int id, int pname) { + return caps.OpenGL33 ? GL33.glGetQueryObjectui64(id, pname) : ARBTimerQuery.glGetQueryObjectui64(id, pname); + } + @Override public void uniform3fv(int location, float[] values) { GL20.glUniform3f(location, values[0], values[1], values[2]); } + @Override public void uniform4fv(int location, float[] values) { GL20.glUniform4f(location, values[0], values[1], values[2], values[3]); } + @Override public void bindFragDataLocation(int program, int colorNumber, CharSequence name) { GL30.glBindFragDataLocation(program, colorNumber, name); } + @Override public void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, ByteBuffer data) { GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, data); @@ -1366,7 +1488,13 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { @Override public void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { - GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format); + if (GLStateManager.capabilities.OpenGL42 || GLStateManager.capabilities.GL_ARB_shader_image_load_store) { + GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format); + } else if (GLStateManager.capabilities.GL_EXT_shader_image_load_store) { + EXTShaderImageLoadStore.glBindImageTextureEXT(unit, texture, level, layered, layer, access, format); + } else { + GLStateManager.warnOnce("bindImageTexture", "glBindImageTexture ignored: no image load/store support"); + } } @Override @@ -1391,7 +1519,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { @Override public int setupDebugOutput(DebugMessageHandler handler) { if (caps.OpenGL43 || caps.GL_KHR_debug) { - khrCallback = new KHRDebugCallback((source, type, id, severity, message) -> handler.handleMessage(source, type, id, severity, message)); + khrCallback = new KHRDebugCallback(handler::handleMessage); GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true); GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false); GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_LOW, null, false); @@ -1406,7 +1534,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { } return 1; } else if (caps.GL_ARB_debug_output) { - arbCallback = new ARBDebugOutputCallback((source, type, id, severity, message) -> handler.handleMessage(source, type, id, severity, message)); + arbCallback = new ARBDebugOutputCallback(handler::handleMessage); ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true); ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false); ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_LOW, null, false); @@ -1520,4 +1648,76 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend { } } + @Override + public void debugMessageControl(int source, int type, int severity, IntBuffer ids, boolean enabled) { + if (activeDebugExtension == 1) { + GL43.glDebugMessageControl(source, type, severity, ids, enabled); + } + } + + @Override + public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { + GL14.glMultiDrawArrays(mode, firsts, counts); + } + + @Override + public void primitiveRestartIndex(int index) { + GL31.glPrimitiveRestartIndex(index); + } + + @Override + public void pointParameterf(int pname, float param) { + GL14.glPointParameterf(pname, param); + } + + @Override + public void pointParameteri(int pname, int param) { + GL14.glPointParameteri(pname, param); + } + + @Override + public void getActiveAttrib(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) { + GL20.glGetActiveAttrib(program, index, length, size, type, name); + } + + @Override + public String getActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) { + return GL20.glGetActiveAttrib(program, index, maxLength, sizeType); + } + + @Override + public int genRenderbuffers() { + return GL30.glGenRenderbuffers(); + } + + @Override + public void deleteRenderbuffers(int renderbuffer) { + GL30.glDeleteRenderbuffers(renderbuffer); + } + + @Override + public void bindRenderbuffer(int target, int renderbuffer) { + GL30.glBindRenderbuffer(target, renderbuffer); + } + + @Override + public void renderbufferStorage(int target, int internalformat, int width, int height) { + GL30.glRenderbufferStorage(target, internalformat, width, height); + } + + @Override + public void renderbufferStorageMultisample(int target, int samples, int internalformat, int width, int height) { + GL30.glRenderbufferStorageMultisample(target, samples, internalformat, width, height); + } + + @Override + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer) { + GL30.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + } + + @Override + public void clearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) { + GL43.glClearBufferData(target, internalformat, format, type, data); + } + } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/RenderBackend.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/RenderBackend.java index 5b0ff45f2..80f217aa9 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/RenderBackend.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/backend/RenderBackend.java @@ -1,8 +1,12 @@ package com.gtnewhorizons.angelica.glsm.backend; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import org.lwjgl.opengl.GL20; +import me.eigenraven.lwjgl3ify.api.SwapchainInvalidatingChange; + import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; @@ -16,14 +20,19 @@ import java.util.List; */ public abstract class RenderBackend { + public void onPostWindowCreate(long window, boolean debug) {} + public abstract void init(); public abstract void shutdown(); public abstract boolean isAvailable(); public abstract String getName(); - /** Returns true if the current thread has a valid render context. Safe to call from any thread. */ + /** Returns true if the current thread has a valid render context. */ public abstract boolean hasContext(); + /** Returns true if the calling thread owns the "GL Context" */ + public abstract boolean isCurrent(); + /** Higher priority backends are preferred. */ public int getPriority() { return 0; } @@ -35,14 +44,46 @@ public abstract class RenderBackend { public List pollDroppedFiles() { return Collections.emptyList(); } + public boolean isIndirectRequired() { return false; } + public boolean supportsGeometryShaders() { return true; } + public boolean isSDLGPU() { return false; } + + public boolean framebufferCompletenessIsMeaningful() { return true; } + public void onPersistentBufferWrite(int glId, long offset, long size) {} + + public boolean isAnisotropicSupported() { return true; } + + public boolean supportsGpuDrivenCulling() { return RenderSystem.supportsCompute(); } + + public void beginComputeDispatchBatch() {} + + public void endComputeDispatchBatch() {} + public abstract int getMinGLSLVersion(); public abstract void flush(); public abstract void finish(); - public void onFrameBegin() {} + public abstract void setVSyncEnabled(boolean enabled); + + public void onFrameBegin() { + if (GLStateManager.takeStateSeedPending()) { + GLStateManager.replayStateToBackend(); + } + } + public void onFrameEnd() {} + /** Fired by lwjgl3ify Display before a mutation that recreates the swapchain. */ + public void onPreSwapchainInvalidatingChange(SwapchainInvalidatingChange change) {} + + public boolean handleMakeCurrent(Object drawable) { return false; } + public boolean handleReleaseContext(Object drawable) { return false; } + public boolean handleSwapBuffers() { return false; } + public void onRenderThreadReleased(Thread thread) {} + + public String getTransferDebugInfo() { return null; } + public abstract void enable(int cap); public abstract void enablei(int cap, int index); public abstract void disable(int cap); @@ -60,6 +101,7 @@ public abstract class RenderBackend { public abstract void frontFace(int mode); public abstract void polygonMode(int face, int mode); public abstract void polygonOffset(float factor, float units); + public void polygonOffsetClamp(float factor, float units, float clamp) { throw new UnsupportedOperationException(getName() + ": polygon offset clamp unsupported"); } public abstract void stencilFunc(int func, int ref, int mask); public abstract void stencilOp(int sfail, int dpfail, int dppass); public abstract void stencilMask(int mask); @@ -85,12 +127,24 @@ public abstract class RenderBackend { public void drawElements(int mode, ShortBuffer indices) {} public void drawElements(int mode, int count, int type, ByteBuffer indices) {} public abstract void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride); + public void multiDrawArraysIndirectCount(int mode, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); } + public void multiDrawElementsIndirectCount(int mode, int type, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); } public abstract void copyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size); public abstract void drawElementsInstanced(int mode, int count, int type, long indices, int primcount); public abstract void drawArraysInstanced(int mode, int first, int count, int primcount); public void provokingVertex(int provokeMode) {} public abstract void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex); public abstract void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex); + public void drawRangeElements(int mode, int start, int end, int count, int type, long indices) { + drawElements(mode, count, type, indices); + } + public void drawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) { + drawElementsBaseVertex(mode, count, type, indices, baseVertex); + } + public abstract void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts); + public abstract void primitiveRestartIndex(int index); + public abstract void pointParameterf(int pname, float param); + public abstract void pointParameteri(int pname, int param); public abstract void drawBuffer(int mode); public abstract void dispatchCompute(int numGroupsX, int numGroupsY, int numGroupsZ); public abstract void dispatchComputeIndirect(long offset); @@ -141,6 +195,12 @@ public abstract class RenderBackend { public abstract void bindFramebuffer(int target, int framebuffer); public abstract void framebufferTexture2D(int target, int attachment, int textarget, int texture, int level); public abstract void framebufferTexture(int target, int attachment, int texture, int level); + public abstract int genRenderbuffers(); + public abstract void deleteRenderbuffers(int renderbuffer); + public abstract void bindRenderbuffer(int target, int renderbuffer); + public abstract void renderbufferStorage(int target, int internalformat, int width, int height); + public abstract void renderbufferStorageMultisample(int target, int samples, int internalformat, int width, int height); + public abstract void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer); public abstract int checkFramebufferStatus(int target); public abstract void blitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); public abstract void drawBuffers(int buffer); @@ -158,6 +218,7 @@ public abstract class RenderBackend { public abstract void deleteShader(int shader); public abstract void shaderSource(int shader, CharSequence source); public abstract void compileShader(int shader); + public void specializeShader(int shader, CharSequence entryPoint, IntBuffer constantIndex, IntBuffer constantValue) { throw new UnsupportedOperationException(getName() + ": externally supplied SPIR-V binaries unsupported"); } public abstract int createProgram(); public abstract void deleteProgram(int program); public abstract void attachShader(int program, int shader); @@ -179,7 +240,10 @@ public abstract class RenderBackend { public abstract void getProgramiv(int program, int pname, IntBuffer params); public abstract String getActiveUniform(int program, int index, int maxLength, IntBuffer sizeType); public abstract void getActiveUniform(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name); + public abstract void getActiveAttrib(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name); + public abstract String getActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType); public abstract void bindAttribLocation(int program, int index, CharSequence name); + public void bindFragDataLocation(int program, int colorNumber, CharSequence name) {} public abstract int getAttribLocation(int program, CharSequence name); public abstract int getAttribLocation(int program, ByteBuffer name); public abstract int getUniformLocation(int program, CharSequence name); @@ -196,6 +260,8 @@ public abstract class RenderBackend { public abstract void uniform1i(int location, int v0); public abstract void uniform1f(int location, float v0); public void uniform1fv(int location, FloatBuffer values) {} + public void uniform3fv(int location, float[] values) {} + public void uniform4fv(int location, float[] values) {} public abstract void uniform2f(int location, float v0, float v1); public abstract void uniform2i(int location, int v0, int v1); public abstract void uniform3f(int location, float v0, float v1, float v2); @@ -224,6 +290,11 @@ public abstract class RenderBackend { public abstract void deleteBuffers(IntBuffer buffers); public abstract void bindBuffer(int target, int buffer); public abstract void bindBufferBase(int target, int index, int buffer); + public abstract void bindBufferRange(int target, int index, int buffer, long offset, long size); + public abstract int getUniformBlockIndex(int program, CharSequence name); + public abstract void uniformBlockBinding(int program, int blockIndex, int binding); + public abstract int getIndexedBufferBinding(int target, int index); + public abstract int getIntegerIndexed(int pname, int index); public abstract void bufferData(int target, long size, int usage); public abstract void bufferData(int target, ByteBuffer data, int usage); public abstract void bufferData(int target, FloatBuffer data, int usage); @@ -251,6 +322,16 @@ public abstract class RenderBackend { public abstract boolean isBuffer(int buffer); public abstract ByteBuffer mapBufferRange(int target, long offset, long length, int access); public abstract void flushMappedBufferRange(int target, long offset, long length); + public long mapBufferRangeAddress(int target, long offset, long length, int access) { + final ByteBuffer buf = mapBufferRange(target, offset, length, access); + return buf == null ? 0L : MemoryUtilities.memAddress0(buf); + } + + public abstract boolean isTexture(int texture); + public abstract boolean isFramebuffer(int framebuffer); + public abstract boolean isRenderbuffer(int renderbuffer); + public abstract boolean isSampler(int sampler); + public abstract boolean isQuery(int query); public abstract int genVertexArrays(); public abstract void deleteVertexArrays(int array); @@ -300,10 +381,12 @@ public abstract class RenderBackend { public abstract void namedBufferSubData(int buffer, long offset, ByteBuffer data); public abstract void copyTextureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int x, int y, int width, int height); public abstract int getTextureParameteri(int texture, int target, int pname); + public abstract float getTextureParameterf(int texture, int target, int pname); public abstract int getTextureLevelParameteri(int texture, int level, int pname); public abstract int getInteger(int pname); public abstract void getInteger(int pname, IntBuffer params); + public void getInteger(int pname, int[] params) { if (params.length > 0) params[0] = getInteger(pname); } public abstract float getFloat(int pname); public abstract void getFloat(int pname, FloatBuffer params); public abstract boolean getBoolean(int pname); @@ -315,8 +398,30 @@ public abstract class RenderBackend { public abstract long fenceSync(int condition, int flags); public abstract int clientWaitSync(long sync, int flags, long timeout); public abstract void deleteSync(long sync); + public void waitSync(long sync, int flags, long timeout) { throw new UnsupportedOperationException("sync objects unsupported"); } + public int getSynci(long sync, int pname, IntBuffer length) { throw new UnsupportedOperationException("sync objects unsupported"); } + + public void genQueries(IntBuffer ids) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public int genQueries() { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public void deleteQueries(int id) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public void beginQuery(int target, int id) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public void endQuery(int target) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public void getQueryObjectui(int id, int pname, IntBuffer params) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + public int getQueryObjecti(int id, int pname) { throw new UnsupportedOperationException("occlusion queries unsupported"); } + + public void queryCounter(int id, int target) { throw new UnsupportedOperationException("timer queries unsupported"); } + public long getQueryObjectui64(int id, int pname) { throw new UnsupportedOperationException("timer queries unsupported"); } + + public boolean supportsGpuProfiling() { return false; } + public int genQuery() { throw new UnsupportedOperationException("timer queries unsupported"); } + public void deleteQuery(int query) { throw new UnsupportedOperationException("timer queries unsupported"); } + public void queryCounter(int query) { throw new UnsupportedOperationException("timer queries unsupported"); } + public boolean isQueryResultAvailable(int query) { throw new UnsupportedOperationException("timer queries unsupported"); } + public long getQueryResult64(int query) { throw new UnsupportedOperationException("timer queries unsupported"); } + public long getGpuTimestamp() { throw new UnsupportedOperationException("timer queries unsupported"); } public abstract void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, ByteBuffer data); + public abstract void clearBufferData(int target, int internalformat, int format, int type, ByteBuffer data); public abstract void clearTexImage(int texture, int level, int format, int type); public abstract void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format); @@ -342,4 +447,10 @@ public abstract class RenderBackend { // Debug message insertion public void debugMessageInsert(int source, int type, int id, int severity, CharSequence message) {} + public void debugMessageControl(int source, int type, int severity, IntBuffer ids, boolean enabled) {} + + public void debugMessageCallback(GLDebugMessageListener listener, long userParam) {} + + public int getDebugMessageLog(int count, IntBuffer sources, IntBuffer types, IntBuffer ids, IntBuffer severities, IntBuffer lengths, ByteBuffer messageLog) { return 0; } + } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java index 88df6f59e..b35f49e16 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.glsm.dsa; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; import java.nio.FloatBuffer; @@ -75,6 +76,11 @@ public class DSAARB extends DSAUnsupported { return GLStateManager.getTexParameterOrDefault(texture, pname, () -> RENDER_BACKEND.getTextureParameteri(texture, target, pname)); } + @Override + public float getTexParameterf(int texture, int target, int pname) { + return RENDER_BACKEND.getTextureParameterf(texture, target, pname); + } + @Override public int getTexLevelParameteri(int texture, int level, int pname) { return RENDER_BACKEND.getTextureLevelParameteri(texture, level, pname); @@ -87,19 +93,20 @@ public class DSAARB extends DSAUnsupported { @Override public void bindTextureToUnit(int unit, int texture) { - if(GLStateManager.getBoundTextureForServerState(unit) == texture) return; - - if (texture == 0) { - super.bindTextureToUnit(unit, texture); - } else { - RENDER_BACKEND.bindTextureUnit(unit, texture); - GLStateManager.getTextures().getTextureUnitBindings(unit).setBinding(texture); - } + bindTextureToUnit(0, unit, texture); } @Override public void bindTextureToUnit(int target, int unit, int texture) { - bindTextureToUnit(unit, texture); + if(GLStateManager.getBoundTextureForServerState(unit) == texture) return; + + if (texture == 0) { + super.bindTextureToUnit(target != 0 ? target : GL11.GL_TEXTURE_2D, unit, texture); + } else { + RENDER_BACKEND.bindTextureUnit(unit, texture); + GLStateManager.getTextures().getTextureUnitBindings(unit).setBinding(texture, target); + GLStateManager.trackMaxBoundTextureUnit(unit); + } } @Override diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAAccess.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAAccess.java index c7633675c..f1cafa2f8 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAAccess.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAAccess.java @@ -23,6 +23,8 @@ public interface DSAAccess { int getTexParameteri(int texture, int target, int pname); + float getTexParameterf(int texture, int target, int pname); + int getTexLevelParameteri(int texture, int level, int pname); void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java index 76bc872b2..a8d7b55f6 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAUnsupported.java @@ -90,6 +90,12 @@ public class DSAUnsupported implements DSAAccess { return GLStateManager.glGetTexParameteri(target, pname); } + @Override + public float getTexParameterf(int texture, int target, int pname) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + return GLStateManager.glGetTexParameterf(target, pname); + } + @Override public int getTexLevelParameteri(int texture, int level, int pname) { final int previous = GLStateManager.getBoundTextureForServerState(); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java new file mode 100644 index 000000000..a9247700d --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlock.java @@ -0,0 +1,119 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntMap; + +public final class FFPUniformBlock { + + public static final String BLOCK_NAME = "FFPUniformBlock"; + public static final int BINDING_POINT = 0; + + private static final StringBuilder DECL = new StringBuilder(2048); + private static int cursor = 0; + static final Object2IntMap MEMBER_OFFSETS = new Object2IntLinkedOpenHashMap<>(); + + private static int align(int alignment) { + cursor = (cursor + alignment - 1) & -alignment; + return cursor; + } + + private static int member(String type, String name, int alignment, int size) { + DECL.append(" ").append(type).append(' ').append(name).append(";\n"); + final int offset = align(alignment); + cursor += size; + MEMBER_OFFSETS.put(name, offset); + return offset; + } + + private static int mat4(String name) { return member("mat4", name, 16, 64); } + private static int mat3(String name) { return member("mat3", name, 16, 48); } + private static int vec4(String name) { return member("vec4", name, 16, 16); } + private static int vec3(String name) { return member("vec3", name, 16, 12); } + private static int vec2(String name) { return member("vec2", name, 8, 8); } + private static int flt(String name) { return member("float", name, 4, 4); } + private static int integer(String name) { return member("int", name, 4, 4); } + private static int vec4Array(String name, int count) { + DECL.append(" vec4 ").append(name).append('[').append(count).append("];\n"); + final int offset = align(16); + cursor += 16 * count; + MEMBER_OFFSETS.put(name + "[0]", offset); + return offset; + } + + static { DECL.append("layout(std140) uniform ").append(BLOCK_NAME).append(" {\n"); } + + public static final int MODEL_VIEW_MATRIX = mat4("u_ModelViewMatrix"); + public static final int PROJECTION_MATRIX = mat4("u_ProjectionMatrix"); + public static final int MVP_MATRIX = mat4("u_MVPMatrix"); + public static final int NORMAL_MATRIX = mat3("u_NormalMatrix"); + public static final int TEXTURE_MATRIX_0 = mat4("u_TextureMatrix0"); + public static final int TEXTURE_MATRIX_2 = mat4("u_TextureMatrix2"); + public static final int TEXTURE_MATRIX_3 = mat4("u_TextureMatrix3"); + public static final int LIGHTMAP_TEXTURE_MATRIX = mat4("u_LightmapTextureMatrix"); + + public static final int CURRENT_COLOR = vec4("u_CurrentColor"); + public static final int CURRENT_TEX_COORD_0 = vec4("u_CurrentTexCoord0"); + public static final int CURRENT_TEX_COORD_2 = vec4("u_CurrentTexCoord2"); + public static final int CURRENT_TEX_COORD_3 = vec4("u_CurrentTexCoord3"); + public static final int VIEWPORT = vec4("u_Viewport"); + public static final int CURRENT_NORMAL = vec3("u_CurrentNormal"); + public static final int CURRENT_LIGHTMAP_COORD = vec2("u_CurrentLightmapCoord"); + public static final int VIEWPORT_SIZE = vec2("u_ViewportSize"); + public static final int NORMAL_SCALE = flt("u_NormalScale"); + public static final int MATERIAL_SHININESS = flt("u_MaterialShininess"); + public static final int ALPHA_REF = flt("u_AlphaRef"); + public static final int LINE_WIDTH = flt("u_LineWidth"); + public static final int LINE_STIPPLE = integer("u_LineStipple"); + + public static final int TEX_GEN_OBJ_PLANE_S = vec4("u_TexGenObjPlaneS"); + public static final int TEX_GEN_OBJ_PLANE_T = vec4("u_TexGenObjPlaneT"); + public static final int TEX_GEN_OBJ_PLANE_R = vec4("u_TexGenObjPlaneR"); + public static final int TEX_GEN_OBJ_PLANE_Q = vec4("u_TexGenObjPlaneQ"); + public static final int TEX_GEN_EYE_PLANE_S = vec4("u_TexGenEyePlaneS"); + public static final int TEX_GEN_EYE_PLANE_T = vec4("u_TexGenEyePlaneT"); + public static final int TEX_GEN_EYE_PLANE_R = vec4("u_TexGenEyePlaneR"); + public static final int TEX_GEN_EYE_PLANE_Q = vec4("u_TexGenEyePlaneQ"); + + public static final int CLIP_PLANES = vec4Array("u_ClipPlane", 8); + + public static final int LIGHT_MODEL_AMBIENT = vec4("u_LightModelAmbient"); + public static final int MATERIAL_EMISSION = vec4("u_MaterialEmission"); + public static final int MATERIAL_AMBIENT = vec4("u_MaterialAmbient"); + public static final int MATERIAL_DIFFUSE = vec4("u_MaterialDiffuse"); + public static final int MATERIAL_SPECULAR = vec4("u_MaterialSpecular"); + public static final int LIGHT0_AMBIENT = vec4("u_Light0Ambient"); + public static final int LIGHT0_DIFFUSE = vec4("u_Light0Diffuse"); + public static final int LIGHT0_SPECULAR = vec4("u_Light0Specular"); + public static final int LIGHT0_POSITION = vec4("u_Light0Position"); + public static final int LIGHT1_AMBIENT = vec4("u_Light1Ambient"); + public static final int LIGHT1_DIFFUSE = vec4("u_Light1Diffuse"); + public static final int LIGHT1_SPECULAR = vec4("u_Light1Specular"); + public static final int LIGHT1_POSITION = vec4("u_Light1Position"); + + public static final int SCENE_COLOR = vec4("u_SceneColor"); + public static final int LIGHT_PROD0_AMBIENT = vec3("u_LightProd0Ambient"); + public static final int LIGHT_PROD0_DIFFUSE = vec3("u_LightProd0Diffuse"); + public static final int LIGHT_PROD0_SPECULAR = vec3("u_LightProd0Specular"); + public static final int LIGHT_PROD1_AMBIENT = vec3("u_LightProd1Ambient"); + public static final int LIGHT_PROD1_DIFFUSE = vec3("u_LightProd1Diffuse"); + public static final int LIGHT_PROD1_SPECULAR = vec3("u_LightProd1Specular"); + + public static final int TEX_ENV_COLOR_0 = vec4("u_TexEnvColor0"); + public static final int TEX_ENV_COLOR_1 = vec4("u_TexEnvColor1"); + public static final int TEX_ENV_COLOR_2 = vec4("u_TexEnvColor2"); + public static final int TEX_ENV_COLOR_3 = vec4("u_TexEnvColor3"); + public static final int OVERLAY_COLOR = vec4("u_OverlayColor"); + public static final int FOG_PARAMS = vec4("u_FogParams"); + public static final int FOG_COLOR = vec4("u_FogColor"); + + public static final int SIZE; + public static final String GLSL_DECL; + + static { + SIZE = (cursor + 15) & -16; + DECL.append("};\n"); + GLSL_DECL = DECL.toString(); + } + + private FFPUniformBlock() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java index 2b15d8158..63eac958f 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java @@ -61,31 +61,12 @@ public final class FragmentShaderGenerator { } private static void emitUniforms(StringBuilder sb, FragmentKey key) { - // Samplers for each enabled unit for (int i = 0; i < key.nrEnabledUnits(); i++) { if (key.unitEnabled(i)) { sb.append("uniform sampler2D u_Sampler").append(i).append(";\n"); } } - if (key.alphaTestEnabled()) { - sb.append("uniform float u_AlphaRef;\n"); - } - if (key.lineStipple()) { - sb.append("uniform int u_LineStipple;\n"); - } - // Per-unit texEnvColor uniforms - for (int i = 0; i < key.nrEnabledUnits(); i++) { - if (key.unitEnabled(i) && key.unitNeedsEnvColor(i)) { - sb.append("uniform vec4 u_TexEnvColor").append(i).append(";\n"); - } - } - if (key.overlayEnabled()) { - sb.append("uniform vec4 u_OverlayColor;\n"); - } - if (key.fogMode() != FragmentKey.FOG_NONE) { - sb.append("uniform vec4 u_FogParams;\n"); - sb.append("uniform vec4 u_FogColor;\n"); - } + sb.append(FFPUniformBlock.GLSL_DECL); sb.append('\n'); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java index d2b30bee8..a64d3e5de 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java @@ -14,8 +14,8 @@ public final class GeometryShaderGenerator { sb.append("layout(lines) in;\n"); sb.append("layout(triangle_strip, max_vertices = 4) out;\n\n"); - sb.append("uniform vec2 u_ViewportSize;\n"); - sb.append("uniform float u_LineWidth;\n\n"); + sb.append(FFPUniformBlock.GLSL_DECL); + sb.append('\n'); sb.append("// Pass-through varyings\n"); sb.append("in vec4 v_Color_gs[];\n"); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java new file mode 100644 index 000000000..24e3ed24e --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +public final class InstancedAttribs { + + public static final int LOC_MATRIX_COL0 = 7; + public static final int LOC_MATRIX_COL1 = 8; + public static final int LOC_MATRIX_COL2 = 9; + public static final int LOC_MATRIX_COL3 = 10; + public static final int LOC_COLOR = 11; + public static final int LOC_LIGHTMAP = 12; + + public static final int OFFSET_MATRIX = 0; + public static final int OFFSET_COLOR = 64; + public static final int OFFSET_LIGHTMAP = 68; + public static final int STRIDE = 80; + + private InstancedAttribs() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java index 5a21545cc..e383ccb60 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java @@ -1,16 +1,23 @@ package com.gtnewhorizons.angelica.glsm.ffp; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; import lombok.Getter; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL31; import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GL40; import org.lwjgl.opengl.GL43; import org.lwjgl.opengl.KHRDebug; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.atomic.AtomicInteger; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; @@ -26,180 +33,15 @@ public class Program { @Getter private final VertexKey vertexKey; @Getter private final FragmentKey fragmentKey; - // Per-program uniform dirty-tracking - static final class UploadState { - int mvGen = -1, mvLinearGen = -1, projGen = -1, texMatGen = -1; - int lightingGen = -1, fragmentGen = -1, colorGen = -1, normalGen = -1, texCoordGen = -1; - int texGenGen = -1, clipPlaneGen = -1; - float lightmapX = Float.NaN, lightmapY = Float.NaN, lineWidth = Float.NaN; - int viewportWidth = -1, viewportHeight = -1; - int stippleViewportX = Integer.MIN_VALUE, stippleViewportY = Integer.MIN_VALUE; - int stippleViewportW = -1, stippleViewportH = -1; - int lineStipple = -1; - } - final UploadState uploadState = new UploadState(); - - // Uniform locations (-1 = not present in this variant) - // Matrices - public int locModelViewMatrix = -1; - public int locProjectionMatrix = -1; - public int locMVPMatrix = -1; - public int locNormalMatrix = -1; - public final int[] locTextureMatrix = { -1, -1, -1, -1 }; - - // Current state defaults - public int locCurrentNormal = -1; - public int locCurrentColor = -1; - public final int[] locCurrentTexCoord = { -1, -1, -1, -1 }; - public int locCurrentLightmapCoord = -1; - public int locLightmapTextureMatrix = -1; - - // Lighting - color material path (raw values) - public int locLightModelAmbient = -1; - public int locMaterialEmission = -1; - public int locMaterialAmbient = -1; - public int locMaterialDiffuse = -1; - public int locMaterialSpecular = -1; - public int locMaterialShininess = -1; - public int locLight0Ambient = -1; - public int locLight0Diffuse = -1; - public int locLight0Specular = -1; - public int locLight1Ambient = -1; - public int locLight1Diffuse = -1; - public int locLight1Specular = -1; - - // Lighting - pre-computed path - public int locSceneColor = -1; - public int locLightProd0Ambient = -1; - public int locLightProd0Diffuse = -1; - public int locLightProd0Specular = -1; - public int locLightProd1Ambient = -1; - public int locLightProd1Diffuse = -1; - public int locLightProd1Specular = -1; - - // Light positions - public int locLight0Position = -1; - public int locLight1Position = -1; - - // Normal scale (for rescale normals) - public int locNormalScale = -1; - - // TexGen plane uniforms - public int locTexGenObjPlaneS = -1; - public int locTexGenObjPlaneT = -1; - public int locTexGenObjPlaneR = -1; - public int locTexGenObjPlaneQ = -1; - public int locTexGenEyePlaneS = -1; - public int locTexGenEyePlaneT = -1; - public int locTexGenEyePlaneR = -1; - public int locTexGenEyePlaneQ = -1; - - // Clip planes - public int locClipPlanes = -1; - - // Wide line emulation (geometry shader) - public int locViewportSize = -1; - public int locLineWidth = -1; - - // Line stipple emulation - public int locViewport = -1; - public int locLineStipple = -1; - - // Fragment uniforms public final int[] locSampler = { -1, -1, -1, -1 }; - public int locAlphaRef = -1; - public final int[] locTexEnvColor = { -1, -1, -1, -1 }; - public int locOverlayColor = -1; - public int locFogParams = -1; - public int locFogColor = -1; Program(int programId, VertexKey vertexKey, FragmentKey fragmentKey) { this.programId = programId; this.vertexKey = vertexKey; this.fragmentKey = fragmentKey; - resolveLocations(); - } - - private void resolveLocations() { - locModelViewMatrix = loc("u_ModelViewMatrix"); - locProjectionMatrix = loc("u_ProjectionMatrix"); - locMVPMatrix = loc("u_MVPMatrix"); - locNormalMatrix = loc("u_NormalMatrix"); for (int i = 0; i < 4; i++) { - locTextureMatrix[i] = loc("u_TextureMatrix" + i); - locCurrentTexCoord[i] = loc("u_CurrentTexCoord" + i); + locSampler[i] = RENDER_BACKEND.getUniformLocation(programId, "u_Sampler" + i); } - - locCurrentNormal = loc("u_CurrentNormal"); - locCurrentColor = loc("u_CurrentColor"); - locCurrentLightmapCoord = loc("u_CurrentLightmapCoord"); - locLightmapTextureMatrix = loc("u_LightmapTextureMatrix"); - - // Color material path - locLightModelAmbient = loc("u_LightModelAmbient"); - locMaterialEmission = loc("u_MaterialEmission"); - locMaterialAmbient = loc("u_MaterialAmbient"); - locMaterialDiffuse = loc("u_MaterialDiffuse"); - locMaterialSpecular = loc("u_MaterialSpecular"); - locMaterialShininess = loc("u_MaterialShininess"); - locLight0Ambient = loc("u_Light0Ambient"); - locLight0Diffuse = loc("u_Light0Diffuse"); - locLight0Specular = loc("u_Light0Specular"); - locLight1Ambient = loc("u_Light1Ambient"); - locLight1Diffuse = loc("u_Light1Diffuse"); - locLight1Specular = loc("u_Light1Specular"); - - // Pre-computed path - locSceneColor = loc("u_SceneColor"); - locLightProd0Ambient = loc("u_LightProd0Ambient"); - locLightProd0Diffuse = loc("u_LightProd0Diffuse"); - locLightProd0Specular = loc("u_LightProd0Specular"); - locLightProd1Ambient = loc("u_LightProd1Ambient"); - locLightProd1Diffuse = loc("u_LightProd1Diffuse"); - locLightProd1Specular = loc("u_LightProd1Specular"); - - // Light positions - locLight0Position = loc("u_Light0Position"); - locLight1Position = loc("u_Light1Position"); - - locNormalScale = loc("u_NormalScale"); - - // TexGen - locTexGenObjPlaneS = loc("u_TexGenObjPlaneS"); - locTexGenObjPlaneT = loc("u_TexGenObjPlaneT"); - locTexGenObjPlaneR = loc("u_TexGenObjPlaneR"); - locTexGenObjPlaneQ = loc("u_TexGenObjPlaneQ"); - locTexGenEyePlaneS = loc("u_TexGenEyePlaneS"); - locTexGenEyePlaneT = loc("u_TexGenEyePlaneT"); - locTexGenEyePlaneR = loc("u_TexGenEyePlaneR"); - locTexGenEyePlaneQ = loc("u_TexGenEyePlaneQ"); - - // Clip planes - locClipPlanes = loc("u_ClipPlane[0]"); - - // Wide line emulation - locViewportSize = loc("u_ViewportSize"); - locLineWidth = loc("u_LineWidth"); - - // Line stipple emulation - locViewport = loc("u_Viewport"); - locLineStipple = loc("u_LineStipple"); - - // Fragment - for (int i = 0; i < 4; i++) { - locSampler[i] = loc("u_Sampler" + i); - } - locAlphaRef = loc("u_AlphaRef"); - for (int i = 0; i < 4; i++) { - locTexEnvColor[i] = loc("u_TexEnvColor" + i); - } - locOverlayColor = loc("u_OverlayColor"); - locFogParams = loc("u_FogParams"); - locFogColor = loc("u_FogColor"); - } - - private int loc(String name) { - return RENDER_BACKEND.getUniformLocation(programId, name); } public void destroy() { @@ -241,7 +83,7 @@ public class Program { final String debugName = "FFP(v=0x" + vkHex + ",f=" + id + (hasGeom ? ",g" : "") + ")"; GLDebug.nameObject(KHRDebug.GL_PROGRAM, program, debugName); - // Detach and delete individual shaders — they're linked into the program + // Detach and delete individual shaders - they're linked into the program for (int i = 0; i < shaderCount; i++) { backend.detachShader(program, shaders[i]); backend.deleteShader(shaders[i]); @@ -250,6 +92,11 @@ public class Program { final Program ffpProgram = new Program(program, vk, fk); + final int blockIndex = backend.getUniformBlockIndex(program, FFPUniformBlock.BLOCK_NAME); + if (blockIndex != GL31.GL_INVALID_INDEX) { + backend.uniformBlockBinding(program, blockIndex, FFPUniformBlock.BINDING_POINT); + } + final int previousProgram = GLStateManager.getActiveProgram(); backend.useProgram(program); for (int i = 0; i < 4; i++) { @@ -268,6 +115,10 @@ public class Program { private static int compileShader(int type, String src, String name) { final RenderBackend backend = RENDER_BACKEND; final int shader = backend.createShader(type); + if (RenderSystem.isGLES()) { + src = CompatShaderTransformer.toGLES(src, type, type == GL20.GL_FRAGMENT_SHADER); + dumpTranslatedFFPShader(type, src, name); + } backend.shaderSource(shader, src); backend.compileShader(shader); @@ -296,4 +147,22 @@ public class Program { return shader; } + + // Post-translation GLSL ES dump, paired with ShaderCache's pre-translation 330 core dump. + private static void dumpTranslatedFFPShader(int type, String translatedSrc, String name) { + final Path dir = SystemProperties.shaderDumpDir("ffp"); + if (dir == null) return; + final String suffix = switch (type) { + case GL20.GL_VERTEX_SHADER -> ".vert.glsl"; + case GL20.GL_FRAGMENT_SHADER -> ".frag.glsl"; + case GL32.GL_GEOMETRY_SHADER -> ".geom.glsl"; + default -> ".glsl"; + }; + try { + Files.createDirectories(dir); + Files.writeString(dir.resolve(name + ".gles" + suffix), translatedSrc); + } catch (IOException e) { + GLStateManager.LOGGER.warn("Failed to dump translated FFP shader: {}", e.getMessage()); + } + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java index 7f1edd1d4..c2da00ab4 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.glsm.ffp; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import lombok.Setter; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -25,6 +26,8 @@ import java.util.IdentityHashMap; * */ public class ShaderCache { + private static final Tracy.ZoneId Z_FFP_SHADER_GEN = Tracy.zoneId("ffpShaderGen", Tracy.COLOR_FFP); + private static final int SLOT_STRIDE = 6; private static final int INITIAL_CAPACITY = 64; // power of 2 private static final long EMPTY_MARKER = 0L; // slot [1] == 0 means empty (fkLen >= 1 guarantees nonzero) @@ -98,18 +101,25 @@ public class ShaderCache { } final VertexKey vk = VertexKey.fromPacked(vkPacked); - final String vertSrc = getOrGenerateVertex(vk); - final FragmentKey fk = FragmentKey.fromPacked(fkPacked, fkLen); - String fragSrc = findFragSource(fkPacked, fkLen); - if (fragSrc == null) { - fragSrc = FragmentShaderGenerator.generate(fk); - uniqueFragCount++; + final String vertSrc; + String fragSrc; + final String geomSrc; + final Program program; + if (Tracy.ENABLED) Tracy.beginZone(Z_FFP_SHADER_GEN); + try { + vertSrc = getOrGenerateVertex(vk); + fragSrc = findFragSource(fkPacked, fkLen); + if (fragSrc == null) { + fragSrc = FragmentShaderGenerator.generate(fk); + uniqueFragCount++; + } + geomSrc = vk.wideLineEmulation() ? getOrGenerateGeometry(vk) : null; + program = Program.create(vk, fk, vertSrc, fragSrc, geomSrc); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); } - final String geomSrc = vk.wideLineEmulation() ? getOrGenerateGeometry(vk) : null; - final Program program = Program.create(vk, fk, vertSrc, fragSrc, geomSrc); - final int insertIdx = findEmptySlot(hash); final int base = insertIdx * SLOT_STRIDE; keys[base] = vkPacked; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java index 1c609edb7..c4bdb0a00 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java @@ -1,12 +1,15 @@ package com.gtnewhorizons.angelica.glsm.ffp; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.CompatUniformManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.GLSMInitConfig; import com.gtnewhorizons.angelica.glsm.QuadConverter; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.stacks.Vec3fStack; import com.gtnewhorizons.angelica.glsm.stacks.Vec4fStack; import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; @@ -14,7 +17,6 @@ import lombok.Getter; import org.joml.Vector3f; import org.joml.Vector4f; -import java.nio.file.Paths; import java.util.Arrays; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; @@ -53,14 +55,21 @@ public final class ShaderManager { @Getter private static int normalGeneration; @Getter private static int texCoordGeneration; + private int preDrawCalls; + private int lastFramePreDrawCalls; + + public static long variantSwitches; + public static Vector4f getCurrentTexCoord() { return currentTexCoords[0]; } public static Vector4f getCurrentTexCoord(int unit) { return currentTexCoords[unit]; } @Getter private boolean enabled = false; private ShaderManager() { - if (Boolean.parseBoolean(System.getProperty("angelica.dumpShaders", "false"))) { - cache.setDumpDir(Paths.get("ffp_shaders")); - } + cache.setDumpDir(SystemProperties.shaderDumpDir("ffp")); + VertexFormat.registerSetupBufferStateOverride((format, offset) -> { + VAOManager.setCurrentVertexFlags(format.getVertexFlags()); + return false; + }); } public static ShaderManager getInstance() { @@ -110,6 +119,7 @@ public final class ShaderManager { lastBoundProgramId = -1; currentVertexKeyPacked = Long.MIN_VALUE; currentFKLen = 0; + GLStateManager.forceAttribDefaultsDirty(); } public void preDraw() { @@ -133,7 +143,7 @@ public final class ShaderManager { if (!active) return; - + preDrawCalls++; final int fkLen = FragmentKey.packFromState(currentFKScratch); final int fragMask = FragmentKey.unitMaskFromPacked(currentFKScratch, fkLen); final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap, fragMask); @@ -152,6 +162,7 @@ public final class ShaderManager { currentProgram = cache.getOrCreate(vkPacked, currentFKPacked, currentFKLen); final int programId = currentProgram.getProgramId(); if (programId != lastBoundProgramId) { + if (Tracy.ENABLED) variantSwitches++; RENDER_BACKEND.useProgram(programId); lastBoundProgramId = programId; } @@ -159,10 +170,17 @@ public final class ShaderManager { private void uploadUniforms() { if (currentProgram != null) { - uniforms.upload(currentProgram); + uniforms.upload(); } } + public static void endFrame() { + final ShaderManager sm = Holder.INSTANCE; + sm.lastFramePreDrawCalls = sm.preDrawCalls; + sm.preDrawCalls = 0; + sm.uniforms.endFrame(); + } + public static void setCurrentNormal(float x, float y, float z) { currentNormal.set(x, y, z); normalGeneration++; @@ -186,13 +204,31 @@ public final class ShaderManager { uniforms.destroy(); final GLSMInitConfig config = GLStateManager.getInitConfig(); if (config != null && config.getStreamingDrawerDestroy() != null) config.getStreamingDrawerDestroy().run(); - com.gtnewhorizons.angelica.glsm.QuadConverter.destroy(); + QuadConverter.destroy(); active = false; currentProgram = null; } public String getDebugInfo() { - return String.format("FFP: %d programs (%d vert, %d frag variants)", - cache.getProgramCount(), cache.getVertexVariantCount(), cache.getFragmentVariantCount()); + return String.format("FFP: %d programs (%d vert, %d frag variants) | UBO: %d/%d draws wrote (mat %d, light %d, frag %d, misc %d)", + cache.getProgramCount(), cache.getVertexVariantCount(), cache.getFragmentVariantCount(), + uniforms.lastFrameBlockWrites, lastFramePreDrawCalls, + uniforms.lastFrameStagedMatrices, uniforms.lastFrameStagedLighting, + uniforms.lastFrameStagedFragment, uniforms.lastFrameStagedMisc); } + + public int statLastFramePreDrawCalls() { return lastFramePreDrawCalls; } + public int statLastFrameBlockWrites() { return uniforms.lastFrameBlockWrites; } + public int statLastFrameBlockSkips() { return uniforms.lastFrameBlockSkips; } + public int statLastFrameStagedMatrices() { return uniforms.lastFrameStagedMatrices; } + public int statLastFrameStagedLighting() { return uniforms.lastFrameStagedLighting; } + public int statLastFrameStagedFragment() { return uniforms.lastFrameStagedFragment; } + public int statLastFrameStagedColor() { return uniforms.lastFrameStagedColor; } + public int statLastFrameStagedNormal() { return uniforms.lastFrameStagedNormal; } + public int statLastFrameStagedTexCoord() { return uniforms.lastFrameStagedTexCoord; } + public int statLastFrameStagedLightmap() { return uniforms.lastFrameStagedLightmap; } + public int statLastFrameStagedTexGen() { return uniforms.lastFrameStagedTexGen; } + public int statLastFrameStagedClipPlanes() { return uniforms.lastFrameStagedClipPlanes; } + public int statLastFrameStagedMisc() { return uniforms.lastFrameStagedMisc; } + public int statProgramCount() { return cache.getProgramCount(); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java index 5427099ee..5bca87279 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java @@ -8,503 +8,434 @@ import com.gtnewhorizons.angelica.glsm.states.LineState; import com.gtnewhorizons.angelica.glsm.states.MaterialState; import com.gtnewhorizons.angelica.glsm.states.TexGenState; import com.gtnewhorizons.angelica.glsm.states.ViewportState; +import com.gtnewhorizons.angelica.glsm.streaming.UniformRingBuffer; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import org.joml.Math; import org.joml.Matrix3f; import org.joml.Matrix4f; +import org.joml.Vector3f; import org.joml.Vector4f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL31; +import java.nio.ByteBuffer; import java.nio.FloatBuffer; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCalloc; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; /** - * Uploads GLSM cached state to the active FFP program's uniforms. - * - * Follows Mesa's prog_statevars.c patterns: - * - Pre-computed derived state (light products, scene color) when material is static - * - Raw light/material values when color material is active - * - Optimized fog params (pre-divided for single MAD in shader) + * Maintains the shared {@link FFPUniformBlock} image from GLSM cached state and streams it to the UBO ring. */ public class Uniforms { - // Reusable temp buffers for uniform upload - private final FloatBuffer mat4Buf = memAllocFloat(16); - private final FloatBuffer mat3Buf = memAllocFloat(9); - private final FloatBuffer vec4Buf = memAllocFloat(4); - private final FloatBuffer vec3Buf = memAllocFloat(3); - private final FloatBuffer clipPlaneBuf = memAllocFloat(32); // 8 planes * vec4 - // Derived matrices (computed on CPU) + private static final int RING_CAPACITY = 16 * 1024 * 1024; + + private final ByteBuffer staging = memCalloc(FFPUniformBlock.SIZE); + private final long stagingAddress = memAddress0(staging); + private UniformRingBuffer ring; + private boolean bound; + private boolean contentChanged; + + private int mvGen = -1, mvLinearGen = -1, projGen = -1, texMatGen = -1; + private int lightingGen = -1, fragmentGen = -1, colorGen = -1, normalGen = -1, texCoordGen = -1; + private int texGenGen = -1, clipPlaneGen = -1; + private float lightmapX = Float.NaN, lightmapY = Float.NaN, lineWidth = Float.NaN; + private int viewportX = Integer.MIN_VALUE, viewportY = Integer.MIN_VALUE, viewportWidth = -1, viewportHeight = -1; + private int lineStipple = -1; + + int blockWrites; + int blockSkips; + int stagedMatrices; + int stagedLighting; + int stagedFragment; + int stagedColor; + int stagedNormal; + int stagedTexCoord; + int stagedLightmap; + int stagedTexGen; + int stagedClipPlanes; + int stagedMisc; + int lastFrameBlockWrites; + int lastFrameBlockSkips; + int lastFrameStagedMatrices; + int lastFrameStagedLighting; + int lastFrameStagedFragment; + int lastFrameStagedColor; + int lastFrameStagedNormal; + int lastFrameStagedTexCoord; + int lastFrameStagedLightmap; + int lastFrameStagedTexGen; + int lastFrameStagedClipPlanes; + int lastFrameStagedMisc; + private final Matrix4f mvpMatrix = new Matrix4f(); private final Matrix3f normalMatrix = new Matrix3f(); + private final Vector3f tempVec3 = new Vector3f(); + private final FloatBuffer clipPlaneBuf = memAllocFloat(32); // 8 planes * vec4 - // Temp vectors for light product and normal scale computation - private final Vector4f tempVec4 = new Vector4f(); - private final org.joml.Vector3f tempVec3 = new org.joml.Vector3f(); - - // Pre-computed constants for fog params (Mesa STATE_FOG_PARAMS_OPTIMIZED) private static final double LN2 = java.lang.Math.log(2.0); private static final double SQRT_LN2 = java.lang.Math.sqrt(LN2); - /** - * Upload all relevant uniforms to the given FFP program based on current GLSM state. - * Uses generation counters to skip categories that haven't changed since last upload. - */ - public void upload(Program program) { - final Program.UploadState st = program.uploadState; + public void upload() { + boolean dirty = false; + contentChanged = false; - final int mvGen = GLStateManager.mvGeneration; - final int mvLinearGen = GLStateManager.mvLinearGeneration; - final int projGen = GLStateManager.projGeneration; - final int texMatGen = GLStateManager.texMatrixGeneration; - final boolean mvChanged = mvGen != st.mvGen; - final boolean mvLinearChanged = mvLinearGen != st.mvLinearGen; - final boolean projChanged = projGen != st.projGen; - final boolean texMatChanged = texMatGen != st.texMatGen; - if (mvChanged || projChanged || texMatChanged) { - uploadMatrices(program, mvChanged, mvLinearChanged, projChanged, texMatChanged); - st.mvGen = mvGen; - st.mvLinearGen = mvLinearGen; - st.projGen = projGen; - st.texMatGen = texMatGen; + final int mvG = GLStateManager.getMvGeneration(); + final int projG = GLStateManager.getProjGeneration(); + final boolean mvChanged = mvG != mvGen; + final boolean projChanged = projG != projGen; + if (mvChanged || projChanged) { + stageMatrices(mvChanged, projChanged); + mvGen = mvG; + projGen = projG; + stagedMatrices++; + dirty = true; } - - if (program.getVertexKey().lightingEnabled()) { - final int litGen = GLStateManager.lightingGeneration; - if (litGen != st.lightingGen) { - uploadLighting(program); - st.lightingGen = litGen; - } + final int mvLinG = GLStateManager.getMvLinearGeneration(); + if (mvLinG != mvLinearGen) { + stageNormalMatrix(); + mvLinearGen = mvLinG; + dirty = true; } - - // Current color/normal/texcoord — skip if generation unchanged - if (!program.getVertexKey().hasVertexColor()) { - final int colorGen = GLStateManager.colorGeneration; - if (colorGen != st.colorGen) { - uploadCurrentColor(program); - st.colorGen = colorGen; - } + final int texMatG = GLStateManager.getTexMatrixGeneration(); + if (texMatG != texMatGen) { + stageTextureMatrices(); + texMatGen = texMatG; + dirty = true; } - - if (!program.getVertexKey().hasVertexNormal() && program.getVertexKey().lightingEnabled()) { - final int normalGen = ShaderManager.getNormalGeneration(); - if (normalGen != st.normalGen) { - uploadCurrentNormal(program); - st.normalGen = normalGen; - } + final int litG = GLStateManager.getLightingGeneration(); + if (litG != lightingGen) { + stageLighting(); + lightingGen = litG; + stagedLighting++; + dirty = true; } - - if (program.getVertexKey().anyUnitTexCoordEnabled()) { - final int texGen = ShaderManager.getTexCoordGeneration(); - if (texGen != st.texCoordGen) { - uploadCurrentTexCoords(program); - st.texCoordGen = texGen; - } + final int colG = GLStateManager.getColorGeneration(); + if (colG != colorGen) { + stageCurrentColor(); + colorGen = colG; + stagedColor++; + dirty = true; } - - if (program.getVertexKey().lightmapEnabled() && !program.getVertexKey().hasVertexLightmap()) { - if (GLSMConfig.lastBrightnessX != st.lightmapX || GLSMConfig.lastBrightnessY != st.lightmapY) { - uploadCurrentLightmapCoord(program); - st.lightmapX = GLSMConfig.lastBrightnessX; - st.lightmapY = GLSMConfig.lastBrightnessY; - } + final int normG = ShaderManager.getNormalGeneration(); + if (normG != normalGen) { + final Vector3f normal = ShaderManager.getCurrentNormal(); + putVec3(FFPUniformBlock.CURRENT_NORMAL, normal.x, normal.y, normal.z); + normalGen = normG; + stagedNormal++; + dirty = true; } - - if (program.getVertexKey().texGenEnabled()) { - final int tgGen = GLStateManager.texGenGeneration; - if (tgGen != st.texGenGen) { - uploadTexGen(program); - st.texGenGen = tgGen; - } + final int tcG = ShaderManager.getTexCoordGeneration(); + if (tcG != texCoordGen) { + putVec4(FFPUniformBlock.CURRENT_TEX_COORD_0, ShaderManager.getCurrentTexCoord(0)); + putVec4(FFPUniformBlock.CURRENT_TEX_COORD_2, ShaderManager.getCurrentTexCoord(2)); + putVec4(FFPUniformBlock.CURRENT_TEX_COORD_3, ShaderManager.getCurrentTexCoord(3)); + texCoordGen = tcG; + stagedTexCoord++; + dirty = true; } - - if (program.getVertexKey().clipPlanesEnabled()) { - final int cpGen = GLStateManager.clipPlaneGeneration; - if (cpGen != st.clipPlaneGen) { - uploadClipPlanes(program); - st.clipPlaneGen = cpGen; - } + final float brightX = GLSMConfig.lastBrightnessX; + final float brightY = GLSMConfig.lastBrightnessY; + if (brightX != lightmapX || brightY != lightmapY) { + putFloat(FFPUniformBlock.CURRENT_LIGHTMAP_COORD, brightX); + putFloat(FFPUniformBlock.CURRENT_LIGHTMAP_COORD + 4, brightY); + lightmapX = brightX; + lightmapY = brightY; + stagedLightmap++; + dirty = true; } - - final int fragGen = GLStateManager.fragmentGeneration; - if (fragGen != st.fragmentGen) { - uploadFragmentUniforms(program); - st.fragmentGen = fragGen; + final int tgG = GLStateManager.getTexGenGeneration(); + if (tgG != texGenGen) { + stageTexGen(); + texGenGen = tgG; + stagedTexGen++; + dirty = true; } - - // Wide line emulation uniforms - if (program.locLineWidth != -1 && program.locViewportSize != -1) { - uploadWideLineUniforms(program); + final int cpG = GLStateManager.getClipPlaneGeneration(); + if (cpG != clipPlaneGen) { + stageClipPlanes(); + clipPlaneGen = cpG; + stagedClipPlanes++; + dirty = true; } - - if (program.locLineStipple != -1) { - uploadLineStippleUniforms(program); + final int fragG = GLStateManager.getFragmentGeneration(); + if (fragG != fragmentGen) { + stageFragment(); + fragmentGen = fragG; + stagedFragment++; + dirty = true; } - } - - private void uploadLineStippleUniforms(Program program) { - final Program.UploadState st = program.uploadState; - final LineState line = GLStateManager.getLineState(); - - final int factor = line.getStippleFactor() < 1 ? 1 : line.getStippleFactor(); - final int packed = (line.getStipplePattern() & 0xFFFF) | (factor << 16); - if (packed != st.lineStipple) { - RENDER_BACKEND.uniform1i(program.locLineStipple, packed); - st.lineStipple = packed; + final float lw = GLStateManager.getLineState().getWidth(); + if (lw != lineWidth) { + putFloat(FFPUniformBlock.LINE_WIDTH, lw); + lineWidth = lw; + stagedMisc++; + dirty = true; } - final ViewportState vp = GLStateManager.getViewportState(); - if (vp.x != st.stippleViewportX || vp.y != st.stippleViewportY || vp.width != st.stippleViewportW || vp.height != st.stippleViewportH) { - RENDER_BACKEND.uniform4f(program.locViewport, vp.x, vp.y, vp.width, vp.height); - st.stippleViewportX = vp.x; - st.stippleViewportY = vp.y; - st.stippleViewportW = vp.width; - st.stippleViewportH = vp.height; + if (vp.x != viewportX || vp.y != viewportY || vp.width != viewportWidth || vp.height != viewportHeight) { + putFloat(FFPUniformBlock.VIEWPORT_SIZE, vp.width); + putFloat(FFPUniformBlock.VIEWPORT_SIZE + 4, vp.height); + putVec4(FFPUniformBlock.VIEWPORT, vp.x, vp.y, vp.width, vp.height); + viewportX = vp.x; + viewportY = vp.y; + viewportWidth = vp.width; + viewportHeight = vp.height; + stagedMisc++; + dirty = true; + } + final LineState line = GLStateManager.getLineState(); + final int stippleFactor = line.getStippleFactor() < 1 ? 1 : line.getStippleFactor(); + final int stipplePacked = (line.getStipplePattern() & 0xFFFF) | (stippleFactor << 16); + if (stipplePacked != lineStipple) { + putInt(FFPUniformBlock.LINE_STIPPLE, stipplePacked); + lineStipple = stipplePacked; + stagedMisc++; + dirty = true; + } + + if (dirty || !bound) { + if (!contentChanged && bound) { + blockSkips++; + return; + } + if (ring == null) { + ring = new UniformRingBuffer(RING_CAPACITY, FFPUniformBlock.SIZE); + } + final int offset = ring.writeBlock(staging); + RENDER_BACKEND.bindBufferRange(GL31.GL_UNIFORM_BUFFER, FFPUniformBlock.BINDING_POINT, + ring.getBufferId(), offset, FFPUniformBlock.SIZE); + bound = true; + blockWrites++; } } - private void uploadMatrices(Program program, boolean mvChanged, boolean mvLinearChanged, boolean projChanged, boolean texMatChanged) { + private void stageMatrices(boolean mvChanged, boolean projChanged) { final Matrix4f mv = GLStateManager.getModelViewMatrix(); final Matrix4f proj = GLStateManager.getProjectionMatrix(); - - // ModelView + derived (normal matrix, normal scale) if (mvChanged) { - if (program.locModelViewMatrix != -1) { - mv.get(mat4Buf); - RENDER_BACKEND.uniformMatrix4(program.locModelViewMatrix, false, mat4Buf); - } + putMat4(FFPUniformBlock.MODEL_VIEW_MATRIX, mv); } - - if (mvLinearChanged) { - // Normal matrix = inverse transpose of upper-left 3x3 of ModelView - if (program.locNormalMatrix != -1 || program.locNormalScale != -1) { - mv.normal(normalMatrix); - } - if (program.locNormalMatrix != -1) { - normalMatrix.get(mat3Buf); - RENDER_BACKEND.uniformMatrix3(program.locNormalMatrix, false, mat3Buf); - } - - // Normal scale (for GL_RESCALE_NORMAL without GL_NORMALIZE) - if (program.locNormalScale != -1) { - // Scale factor = 1/length of first column of normal matrix - final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length(); - RENDER_BACKEND.uniform1f(program.locNormalScale, scale); - } - } - - // Projection if (projChanged) { - if (program.locProjectionMatrix != -1) { - proj.get(mat4Buf); - RENDER_BACKEND.uniformMatrix4(program.locProjectionMatrix, false, mat4Buf); - } - } - - // MVP = Projection * ModelView — needs recompute if either input changed - if ((mvChanged || projChanged) && program.locMVPMatrix != -1) { - proj.mul(mv, mvpMatrix); - mvpMatrix.get(mat4Buf); - RENDER_BACKEND.uniformMatrix4(program.locMVPMatrix, false, mat4Buf); - } - - // Texture matrices (per-unit). - if (texMatChanged) { - for (int i = 0; i < 4; i++) { - if (program.locTextureMatrix[i] != -1) { - final Matrix4f texMat = GLStateManager.getTextures().getTextureUnitMatrix(i); - texMat.get(mat4Buf); - RENDER_BACKEND.uniformMatrix4(program.locTextureMatrix[i], false, mat4Buf); - } - } - if (program.locLightmapTextureMatrix != -1) { - final Matrix4f lmTexMat = GLStateManager.getTextures().getTextureUnitMatrix(1); - lmTexMat.get(mat4Buf); - RENDER_BACKEND.uniformMatrix4(program.locLightmapTextureMatrix, false, mat4Buf); - } + putMat4(FFPUniformBlock.PROJECTION_MATRIX, proj); } + proj.mul(mv, mvpMatrix); + putMat4(FFPUniformBlock.MVP_MATRIX, mvpMatrix); } - private void uploadLighting(Program program) { - final VertexKey vk = program.getVertexKey(); - - if (vk.colorMaterialEnabled()) { - uploadLightingColorMaterial(program, vk); - } else { - uploadLightingPreComputed(program, vk); - } + private void stageNormalMatrix() { + GLStateManager.getModelViewMatrix().normal(normalMatrix); + putMat3(FFPUniformBlock.NORMAL_MATRIX, normalMatrix); + final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length(); + putFloat(FFPUniformBlock.NORMAL_SCALE, scale); } - /** - * Color material active: upload raw light and material values. - * The shader multiplies them with vertex color at runtime. - */ - private void uploadLightingColorMaterial(Program program, VertexKey vk) { + private void stageTextureMatrices() { + putMat4(FFPUniformBlock.TEXTURE_MATRIX_0, GLStateManager.getTextures().getTextureUnitMatrix(0)); + putMat4(FFPUniformBlock.TEXTURE_MATRIX_2, GLStateManager.getTextures().getTextureUnitMatrix(2)); + putMat4(FFPUniformBlock.TEXTURE_MATRIX_3, GLStateManager.getTextures().getTextureUnitMatrix(3)); + putMat4(FFPUniformBlock.LIGHTMAP_TEXTURE_MATRIX, GLStateManager.getTextures().getTextureUnitMatrix(1)); + } + + private void stageLighting() { final MaterialState mat = GLStateManager.getFrontMaterial(); + final Vector4f lmAmbient = GLStateManager.getLightModel().ambient; + final LightState light0 = GLStateManager.getLightDataStates()[0]; + final LightState light1 = GLStateManager.getLightDataStates()[1]; - uploadVec4(program.locLightModelAmbient, GLStateManager.getLightModel().ambient); - uploadVec4(program.locMaterialEmission, mat.emission); - uploadVec4(program.locMaterialAmbient, mat.ambient); - uploadVec4(program.locMaterialDiffuse, mat.diffuse); - uploadVec4(program.locMaterialSpecular, mat.specular); - if (program.locMaterialShininess != -1) { - RENDER_BACKEND.uniform1f(program.locMaterialShininess, mat.shininess); - } + putVec4(FFPUniformBlock.LIGHT_MODEL_AMBIENT, lmAmbient); + putVec4(FFPUniformBlock.MATERIAL_EMISSION, mat.emission); + putVec4(FFPUniformBlock.MATERIAL_AMBIENT, mat.ambient); + putVec4(FFPUniformBlock.MATERIAL_DIFFUSE, mat.diffuse); + putVec4(FFPUniformBlock.MATERIAL_SPECULAR, mat.specular); + putFloat(FFPUniformBlock.MATERIAL_SHININESS, mat.shininess); + putVec4(FFPUniformBlock.LIGHT0_AMBIENT, light0.ambient); + putVec4(FFPUniformBlock.LIGHT0_DIFFUSE, light0.diffuse); + putVec4(FFPUniformBlock.LIGHT0_SPECULAR, light0.specular); + putVec4(FFPUniformBlock.LIGHT0_POSITION, light0.position); + putVec4(FFPUniformBlock.LIGHT1_AMBIENT, light1.ambient); + putVec4(FFPUniformBlock.LIGHT1_DIFFUSE, light1.diffuse); + putVec4(FFPUniformBlock.LIGHT1_SPECULAR, light1.specular); + putVec4(FFPUniformBlock.LIGHT1_POSITION, light1.position); - if (vk.light0Enabled()) { - final LightState light0 = GLStateManager.getLightDataStates()[0]; - uploadVec4(program.locLight0Ambient, light0.ambient); - uploadVec4(program.locLight0Diffuse, light0.diffuse); - uploadVec4(program.locLight0Specular, light0.specular); - uploadVec4(program.locLight0Position, light0.position); - } - if (vk.light1Enabled()) { - final LightState light1 = GLStateManager.getLightDataStates()[1]; - uploadVec4(program.locLight1Ambient, light1.ambient); - uploadVec4(program.locLight1Diffuse, light1.diffuse); - uploadVec4(program.locLight1Specular, light1.specular); - uploadVec4(program.locLight1Position, light1.position); - } + putVec4(FFPUniformBlock.SCENE_COLOR, + mat.emission.x + mat.ambient.x * lmAmbient.x, + mat.emission.y + mat.ambient.y * lmAmbient.y, + mat.emission.z + mat.ambient.z * lmAmbient.z, + mat.diffuse.w); + putLightProduct(FFPUniformBlock.LIGHT_PROD0_AMBIENT, light0.ambient, mat.ambient); + putLightProduct(FFPUniformBlock.LIGHT_PROD0_DIFFUSE, light0.diffuse, mat.diffuse); + putLightProduct(FFPUniformBlock.LIGHT_PROD0_SPECULAR, light0.specular, mat.specular); + putLightProduct(FFPUniformBlock.LIGHT_PROD1_AMBIENT, light1.ambient, mat.ambient); + putLightProduct(FFPUniformBlock.LIGHT_PROD1_DIFFUSE, light1.diffuse, mat.diffuse); + putLightProduct(FFPUniformBlock.LIGHT_PROD1_SPECULAR, light1.specular, mat.specular); } - /** - * No color material: upload pre-computed light products and scene color. - * Fewer shader multiplies since material is static. - */ - private void uploadLightingPreComputed(Program program, VertexKey vk) { - final MaterialState mat = GLStateManager.getFrontMaterial(); - - // Scene color = emission + ambient * lightModel.ambient - // Alpha = material.diffuse.a - if (program.locSceneColor != -1) { - tempVec4.set( - mat.emission.x + mat.ambient.x * GLStateManager.getLightModel().ambient.x, - mat.emission.y + mat.ambient.y * GLStateManager.getLightModel().ambient.y, - mat.emission.z + mat.ambient.z * GLStateManager.getLightModel().ambient.z, - mat.diffuse.w // alpha from diffuse - ); - uploadVec4(program.locSceneColor, tempVec4); - } - - if (program.locMaterialShininess != -1) { - RENDER_BACKEND.uniform1f(program.locMaterialShininess, mat.shininess); - } - - // Per-light products - if (vk.light0Enabled()) { - final LightState light0 = GLStateManager.getLightDataStates()[0]; - uploadVec4(program.locLight0Position, light0.position); - uploadLightProduct(program.locLightProd0Ambient, light0.ambient, mat.ambient); - uploadLightProduct(program.locLightProd0Diffuse, light0.diffuse, mat.diffuse); - uploadLightProduct(program.locLightProd0Specular, light0.specular, mat.specular); - } - if (vk.light1Enabled()) { - final LightState light1 = GLStateManager.getLightDataStates()[1]; - uploadVec4(program.locLight1Position, light1.position); - uploadLightProduct(program.locLightProd1Ambient, light1.ambient, mat.ambient); - uploadLightProduct(program.locLightProd1Diffuse, light1.diffuse, mat.diffuse); - uploadLightProduct(program.locLightProd1Specular, light1.specular, mat.specular); - } + private void putLightProduct(int offset, Vector4f lightVal, Vector4f materialVal) { + putVec3(offset, lightVal.x * materialVal.x, lightVal.y * materialVal.y, lightVal.z * materialVal.z); } - /** - * Upload pre-multiplied light product: light.X * material.X (RGB only). - */ - private void uploadLightProduct(int loc, Vector4f lightVal, Vector4f materialVal) { - if (loc == -1) return; - vec3Buf.clear(); - vec3Buf.put(lightVal.x * materialVal.x); - vec3Buf.put(lightVal.y * materialVal.y); - vec3Buf.put(lightVal.z * materialVal.z); - vec3Buf.flip(); - RENDER_BACKEND.uniform3(loc, vec3Buf); - } - - private void uploadCurrentColor(Program program) { - if (program.locCurrentColor == -1) return; - // Upload the current color from GLSM + private void stageCurrentColor() { final var color = GLStateManager.getColor(); - tempVec4.set( + putVec4(FFPUniformBlock.CURRENT_COLOR, Math.clamp(0f, 1f, color.getRed()), Math.clamp(0f, 1f, color.getGreen()), Math.clamp(0f, 1f, color.getBlue()), Math.clamp(0f, 1f, color.getAlpha())); - vec4Buf.clear(); - tempVec4.get(vec4Buf); - RENDER_BACKEND.uniform4(program.locCurrentColor, vec4Buf); } - private void uploadCurrentTexCoords(Program program) { - for (int i = 0; i < 4; i++) { - if (program.locCurrentTexCoord[i] != -1) { - uploadVec4(program.locCurrentTexCoord[i], ShaderManager.getCurrentTexCoord(i)); - } - } - } - - private void uploadCurrentLightmapCoord(Program program) { - if (program.locCurrentLightmapCoord == -1) return; - RENDER_BACKEND.uniform2f(program.locCurrentLightmapCoord, - GLSMConfig.lastBrightnessX, GLSMConfig.lastBrightnessY); - } - - private void uploadCurrentNormal(Program program) { - if (program.locCurrentNormal == -1) return; - // Upload current normal from FFPShaderManager's tracked normal - final var normal = ShaderManager.getCurrentNormal(); - vec3Buf.clear(); - normal.get(vec3Buf); - RENDER_BACKEND.uniform3(program.locCurrentNormal, vec3Buf); - } - - private void uploadTexGen(Program program) { - final VertexKey vk = program.getVertexKey(); + private void stageTexGen() { final TexGenState tg = GLStateManager.getTextures().getTexGenState(0); - - if (vk.texGenModeS() == VertexKey.TG_OBJ_LINEAR) { - uploadPlane(program.locTexGenObjPlaneS, tg.getObjectPlane(org.lwjgl.opengl.GL11.GL_S)); - } else if (vk.texGenModeS() == VertexKey.TG_EYE_LINEAR) { - uploadPlane(program.locTexGenEyePlaneS, tg.getEyePlane(org.lwjgl.opengl.GL11.GL_S)); - } - - if (vk.texGenModeT() == VertexKey.TG_OBJ_LINEAR) { - uploadPlane(program.locTexGenObjPlaneT, tg.getObjectPlane(org.lwjgl.opengl.GL11.GL_T)); - } else if (vk.texGenModeT() == VertexKey.TG_EYE_LINEAR) { - uploadPlane(program.locTexGenEyePlaneT, tg.getEyePlane(org.lwjgl.opengl.GL11.GL_T)); - } - - if (vk.texGenModeR() == VertexKey.TG_OBJ_LINEAR) { - uploadPlane(program.locTexGenObjPlaneR, tg.getObjectPlane(org.lwjgl.opengl.GL11.GL_R)); - } else if (vk.texGenModeR() == VertexKey.TG_EYE_LINEAR) { - uploadPlane(program.locTexGenEyePlaneR, tg.getEyePlane(org.lwjgl.opengl.GL11.GL_R)); - } - - if (vk.texGenModeQ() == VertexKey.TG_OBJ_LINEAR) { - uploadPlane(program.locTexGenObjPlaneQ, tg.getObjectPlane(org.lwjgl.opengl.GL11.GL_Q)); - } else if (vk.texGenModeQ() == VertexKey.TG_EYE_LINEAR) { - uploadPlane(program.locTexGenEyePlaneQ, tg.getEyePlane(org.lwjgl.opengl.GL11.GL_Q)); - } + putPlane(FFPUniformBlock.TEX_GEN_OBJ_PLANE_S, tg.getObjectPlane(GL11.GL_S)); + putPlane(FFPUniformBlock.TEX_GEN_OBJ_PLANE_T, tg.getObjectPlane(GL11.GL_T)); + putPlane(FFPUniformBlock.TEX_GEN_OBJ_PLANE_R, tg.getObjectPlane(GL11.GL_R)); + putPlane(FFPUniformBlock.TEX_GEN_OBJ_PLANE_Q, tg.getObjectPlane(GL11.GL_Q)); + putPlane(FFPUniformBlock.TEX_GEN_EYE_PLANE_S, tg.getEyePlane(GL11.GL_S)); + putPlane(FFPUniformBlock.TEX_GEN_EYE_PLANE_T, tg.getEyePlane(GL11.GL_T)); + putPlane(FFPUniformBlock.TEX_GEN_EYE_PLANE_R, tg.getEyePlane(GL11.GL_R)); + putPlane(FFPUniformBlock.TEX_GEN_EYE_PLANE_Q, tg.getEyePlane(GL11.GL_Q)); } - private void uploadPlane(int loc, float[] plane) { - if (loc == -1) return; - vec4Buf.clear(); - vec4Buf.put(plane, 0, 4); - vec4Buf.flip(); - RENDER_BACKEND.uniform4(loc, vec4Buf); - } - - private void uploadClipPlanes(Program program) { - if (program.locClipPlanes == -1) return; + private void stageClipPlanes() { final ClipPlaneState cps = GLStateManager.getClipPlaneState(); clipPlaneBuf.clear(); for (int i = 0; i < GLStateManager.MAX_CLIP_PLANES; i++) { cps.putEyePlane(i, clipPlaneBuf); } - clipPlaneBuf.flip(); - RENDER_BACKEND.uniform4(program.locClipPlanes, clipPlaneBuf); + final long src = memAddress0(clipPlaneBuf); + for (int i = 0; i < 32 * 4; i += 4) { + putInt(FFPUniformBlock.CLIP_PLANES + i, memGetInt(src + i)); + } } - private void uploadFragmentUniforms(Program program) { - final FragmentKey fk = program.getFragmentKey(); + private void stageFragment() { + putFloat(FFPUniformBlock.ALPHA_REF, GLStateManager.getAlphaState().getReference()); - // Alpha test reference - if (fk.alphaTestEnabled() && program.locAlphaRef != -1) { - RENDER_BACKEND.uniform1f(program.locAlphaRef, GLStateManager.getAlphaState().getReference()); - } - - // Per-unit tex env color for (int i = 0; i < 4; i++) { - if (program.locTexEnvColor[i] != -1) { - final var envState = GLStateManager.getTextures().getTexEnvState(i); - vec4Buf.clear(); - vec4Buf.put(envState.envColorR); - vec4Buf.put(envState.envColorG); - vec4Buf.put(envState.envColorB); - vec4Buf.put(envState.envColorA); - vec4Buf.flip(); - RENDER_BACKEND.uniform4(program.locTexEnvColor[i], vec4Buf); - } + final var envState = GLStateManager.getTextures().getTexEnvState(i); + putVec4(FFPUniformBlock.TEX_ENV_COLOR_0 + i * 16, + envState.envColorR, envState.envColorG, envState.envColorB, envState.envColorA); } - if (fk.overlayEnabled() && program.locOverlayColor != -1) { - vec4Buf.clear(); - vec4Buf.put(GLStateManager.getOverlayR()); - vec4Buf.put(GLStateManager.getOverlayG()); - vec4Buf.put(GLStateManager.getOverlayB()); - vec4Buf.put(GLStateManager.getOverlayA()); - vec4Buf.flip(); - RENDER_BACKEND.uniform4(program.locOverlayColor, vec4Buf); - } + putVec4(FFPUniformBlock.OVERLAY_COLOR, + GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), + GLStateManager.getOverlayB(), GLStateManager.getOverlayA()); - // Fog - if (fk.fogMode() != FragmentKey.FOG_NONE) { - uploadFog(program); - } - } - - /** - * Upload optimized fog params (following Mesa's STATE_FOG_PARAMS_OPTIMIZED): - */ - private void uploadFog(Program program) { + // Mesa STATE_FOG_PARAMS_OPTIMIZED final FogState fog = GLStateManager.getFogState(); - - if (program.locFogParams != -1) { - final float start = fog.getStart(); - final float end = fog.getEnd(); - final float density = fog.getDensity(); - final float range = end - start; - - vec4Buf.clear(); - vec4Buf.put(range != 0.0f ? -1.0f / range : 0.0f); // [0]: -1/(end-start) - vec4Buf.put(range != 0.0f ? end / range : 1.0f); // [1]: end/(end-start) - vec4Buf.put((float)(density / LN2)); // [2]: density/ln(2) - vec4Buf.put((float)(density / SQRT_LN2)); // [3]: density/sqrt(ln(2)) - vec4Buf.flip(); - RENDER_BACKEND.uniform4(program.locFogParams, vec4Buf); - } - - if (program.locFogColor != -1) { - vec4Buf.clear(); - vec4Buf.put((float) fog.getFogColor().x); - vec4Buf.put((float) fog.getFogColor().y); - vec4Buf.put((float) fog.getFogColor().z); - vec4Buf.put(fog.getFogAlpha()); - vec4Buf.flip(); - RENDER_BACKEND.uniform4(program.locFogColor, vec4Buf); - } + final float start = fog.getStart(); + final float end = fog.getEnd(); + final float density = fog.getDensity(); + final float range = end - start; + putVec4(FFPUniformBlock.FOG_PARAMS, + range != 0.0f ? -1.0f / range : 0.0f, + range != 0.0f ? end / range : 1.0f, + (float) (density / LN2), + (float) (density / SQRT_LN2)); + putVec4(FFPUniformBlock.FOG_COLOR, + (float) fog.getFogColor().x, (float) fog.getFogColor().y, (float) fog.getFogColor().z, + fog.getFogAlpha()); } - private void uploadWideLineUniforms(Program program) { - final Program.UploadState st = program.uploadState; - final float lineWidth = GLStateManager.getLineState().getWidth(); - if (lineWidth != st.lineWidth) { - RENDER_BACKEND.uniform1f(program.locLineWidth, lineWidth); - st.lineWidth = lineWidth; - } - final int vw = GLStateManager.getViewportState().width; - final int vh = GLStateManager.getViewportState().height; - if (vw != st.viewportWidth || vh != st.viewportHeight) { - RENDER_BACKEND.uniform2f(program.locViewportSize, vw, vh); - st.viewportWidth = vw; - st.viewportHeight = vh; - } + private void putFloat(int offset, float v) { + final long a = stagingAddress + offset; + final int bits = Float.floatToRawIntBits(v); + if (memGetInt(a) != bits) contentChanged = true; + memPutInt(a, bits); } - private void uploadVec4(int loc, Vector4f v) { - if (loc == -1) return; - vec4Buf.clear(); - v.get(vec4Buf); - RENDER_BACKEND.uniform4(loc, vec4Buf); + private void putInt(int offset, int v) { + final long a = stagingAddress + offset; + if (memGetInt(a) != v) contentChanged = true; + memPutInt(a, v); + } + + private void putMat4(int offset, Matrix4f m) { + putVec4(offset, m.m00(), m.m01(), m.m02(), m.m03()); + putVec4(offset + 16, m.m10(), m.m11(), m.m12(), m.m13()); + putVec4(offset + 32, m.m20(), m.m21(), m.m22(), m.m23()); + putVec4(offset + 48, m.m30(), m.m31(), m.m32(), m.m33()); + } + + /** std140 mat3: three vec4-aligned columns. */ + private void putMat3(int offset, Matrix3f m) { + putVec3(offset, m.m00(), m.m01(), m.m02()); + putVec3(offset + 16, m.m10(), m.m11(), m.m12()); + putVec3(offset + 32, m.m20(), m.m21(), m.m22()); + } + + private void putVec4(int offset, Vector4f v) { + putVec4(offset, v.x, v.y, v.z, v.w); + } + + private void putVec4(int offset, float x, float y, float z, float w) { + putFloat(offset, x); + putFloat(offset + 4, y); + putFloat(offset + 8, z); + putFloat(offset + 12, w); + } + + private void putVec3(int offset, float x, float y, float z) { + putFloat(offset, x); + putFloat(offset + 4, y); + putFloat(offset + 8, z); + } + + private void putPlane(int offset, float[] plane) { + putVec4(offset, plane[0], plane[1], plane[2], plane[3]); + } + + public void endFrame() { + if (ring != null) { + ring.endFrame(); + } + lastFrameBlockWrites = blockWrites; + lastFrameBlockSkips = blockSkips; + lastFrameStagedMatrices = stagedMatrices; + lastFrameStagedLighting = stagedLighting; + lastFrameStagedFragment = stagedFragment; + lastFrameStagedColor = stagedColor; + lastFrameStagedNormal = stagedNormal; + lastFrameStagedTexCoord = stagedTexCoord; + lastFrameStagedLightmap = stagedLightmap; + lastFrameStagedTexGen = stagedTexGen; + lastFrameStagedClipPlanes = stagedClipPlanes; + lastFrameStagedMisc = stagedMisc; + blockWrites = 0; + blockSkips = 0; + stagedMatrices = 0; + stagedLighting = 0; + stagedFragment = 0; + stagedColor = 0; + stagedNormal = 0; + stagedTexCoord = 0; + stagedLightmap = 0; + stagedTexGen = 0; + stagedClipPlanes = 0; + stagedMisc = 0; + } + + UniformRingBuffer getRing() { + return ring; + } + + ByteBuffer getStaging() { + return staging; } public void destroy() { - memFree(mat4Buf); - memFree(mat3Buf); - memFree(vec4Buf); - memFree(vec3Buf); + memFree(staging); memFree(clipPlaneBuf); + if (ring != null) { + ring.destroy(); + ring = null; + } + bound = false; } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VAOManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VAOManager.java index 64e240d26..ffca7b369 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VAOManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VAOManager.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.glsm.ffp; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; @@ -315,17 +316,7 @@ public final class VAOManager { } public int typeSizeBytes() { - return glTypeSizeBytes(type); - } - - public static int glTypeSizeBytes(int glType) { - return switch (glType) { - case GL11.GL_FLOAT, GL11.GL_INT, GL11.GL_UNSIGNED_INT -> 4; - case GL11.GL_DOUBLE -> 8; - case GL11.GL_SHORT, GL11.GL_UNSIGNED_SHORT -> 2; - case GL11.GL_BYTE, GL11.GL_UNSIGNED_BYTE -> 1; - default -> 4; - }; + return GLTypes.sizeBytes(type); } public float readComponent(ByteBuffer buf, int base, int component) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java index 1b9157042..b7de1f334 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -51,6 +51,7 @@ public final class VertexKey { private static final int BIT_UNIT_TEXMAT_BASE = 37; private static final int BIT_UNIT23_UV_FROM_UNIT0 = 41; private static final int BIT_LINE_STIPPLE = 42; + private static final int BIT_INSTANCED = 44; public static final int TG_NONE = 0; public static final int TG_OBJ_LINEAR = 1; @@ -100,6 +101,7 @@ public final class VertexKey { public boolean clipPlanesEnabled() { return bit(BIT_CLIP_PLANES); } public boolean wideLineEmulation() { return bit(BIT_WIDE_LINE); } public boolean lineStipple() { return bit(BIT_LINE_STIPPLE); } + public boolean instancedDraw() { return bit(BIT_INSTANCED); } public boolean cmReplacesAmbient() { final int m = colorMaterialMode(); return m == CM_AMBIENT || m == CM_AMBIENT_AND_DIFFUSE; } public boolean cmReplacesDiffuse() { final int m = colorMaterialMode(); return m == CM_DIFFUSE || m == CM_AMBIENT_AND_DIFFUSE; } @@ -233,6 +235,10 @@ public final class VertexKey { bits |= (1L << BIT_LINE_STIPPLE); } + if (GLStateManager.instancedFfpDrawActive) { + bits |= (1L << BIT_INSTANCED); + } + return bits; } @@ -258,12 +264,12 @@ public final class VertexKey { @Override public String toString() { - return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b]", + return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%b]", packed, lightingEnabled(), light0Enabled(), light1Enabled(), colorMaterialEnabled(), fogEnabled(), unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0, unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0, hasVertexColor(), hasVertexNormal(), hasVertexTexCoord(), hasVertexLightmap(), - texGenModeS(), texGenModeT(), texGenModeR(), texGenModeQ(), clipPlanesEnabled(), wideLineEmulation()); + texGenModeS(), texGenModeT(), texGenModeR(), texGenModeQ(), clipPlanesEnabled(), wideLineEmulation(), instancedDraw()); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java index 5f520f77c..7219547f5 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java @@ -69,6 +69,14 @@ public final class VertexShaderGenerator { if (key.hasVertexNormal()) { sb.append("layout(location = ").append(VertexFormatElement.Usage.NORMAL.getAttributeLocation()).append(") in vec3 a_Normal;\n"); } + if (key.instancedDraw()) { + sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL0).append(") in vec4 a_InstCol0;\n"); + sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL1).append(") in vec4 a_InstCol1;\n"); + sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL2).append(") in vec4 a_InstCol2;\n"); + sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL3).append(") in vec4 a_InstCol3;\n"); + sb.append("layout(location = ").append(InstancedAttribs.LOC_COLOR).append(") in vec4 a_InstColor;\n"); + sb.append("layout(location = ").append(InstancedAttribs.LOC_LIGHTMAP).append(") in vec2 a_InstLightmap;\n"); + } sb.append('\n'); } @@ -78,119 +86,10 @@ public final class VertexShaderGenerator { } private static void emitUniforms(StringBuilder sb, VertexKey key) { - sb.append("// Matrices\n"); - sb.append("uniform mat4 u_ModelViewMatrix;\n"); - sb.append("uniform mat4 u_ProjectionMatrix;\n"); - sb.append("uniform mat4 u_MVPMatrix;\n"); - - if (key.lightingEnabled()) { - sb.append("uniform mat3 u_NormalMatrix;\n"); - } - if (key.lineStipple()) { - sb.append("uniform vec4 u_Viewport;\n"); - } - - for (int i = 0; i < VertexKey.MAX_UNITS; i++) { - if (i == 1) continue; - if (key.unitTexMatEnabled(i)) { - sb.append("uniform mat4 u_TextureMatrix").append(i).append(";\n"); - } - } - - // TexGen plane uniforms (unit 0 only - TODO: per-unit) - if (key.texGenModeS() == VertexKey.TG_OBJ_LINEAR) sb.append("uniform vec4 u_TexGenObjPlaneS;\n"); - if (key.texGenModeS() == VertexKey.TG_EYE_LINEAR) sb.append("uniform vec4 u_TexGenEyePlaneS;\n"); - if (key.texGenModeT() == VertexKey.TG_OBJ_LINEAR) sb.append("uniform vec4 u_TexGenObjPlaneT;\n"); - if (key.texGenModeT() == VertexKey.TG_EYE_LINEAR) sb.append("uniform vec4 u_TexGenEyePlaneT;\n"); - if (key.texGenModeR() == VertexKey.TG_OBJ_LINEAR) sb.append("uniform vec4 u_TexGenObjPlaneR;\n"); - if (key.texGenModeR() == VertexKey.TG_EYE_LINEAR) sb.append("uniform vec4 u_TexGenEyePlaneR;\n"); - if (key.texGenModeQ() == VertexKey.TG_OBJ_LINEAR) sb.append("uniform vec4 u_TexGenObjPlaneQ;\n"); - if (key.texGenModeQ() == VertexKey.TG_EYE_LINEAR) sb.append("uniform vec4 u_TexGenEyePlaneQ;\n"); - - if (!key.hasVertexNormal() && key.lightingEnabled()) { - sb.append("uniform vec3 u_CurrentNormal;\n"); - } - - if (!key.hasVertexColor()) { - sb.append("uniform vec4 u_CurrentColor;\n"); - } - - if (key.unitTexCoordEnabled(0) && !key.hasVertexTexCoord()) { - sb.append("uniform vec4 u_CurrentTexCoord0;\n"); - } - if (key.unitTexCoordEnabled(2) && !key.unit23UvFromUnit0()) sb.append("uniform vec4 u_CurrentTexCoord2;\n"); - if (key.unitTexCoordEnabled(3) && !key.unit23UvFromUnit0()) sb.append("uniform vec4 u_CurrentTexCoord3;\n"); - - if (key.lightmapEnabled() && !key.hasVertexLightmap()) { - sb.append("uniform vec2 u_CurrentLightmapCoord;\n"); - } - - if (key.lightmapEnabled()) { - sb.append("uniform mat4 u_LightmapTextureMatrix;\n"); - } - - if (key.lightingEnabled()) { - emitLightingUniforms(sb, key); - } - - if (key.lightingEnabled() && (key.normalizeEnabled() || key.rescaleNormalsEnabled())) { - // normalize is done in shader; rescale uses normalScale - if (key.rescaleNormalsEnabled() && !key.normalizeEnabled()) { - sb.append("uniform float u_NormalScale;\n"); - } - } - - if (key.clipPlanesEnabled()) { - sb.append("uniform vec4 u_ClipPlane[8];\n"); - } - + sb.append(FFPUniformBlock.GLSL_DECL); sb.append('\n'); } - private static void emitLightingUniforms(StringBuilder sb, VertexKey key) { - sb.append("\n// Lighting\n"); - - if (key.colorMaterialEnabled()) { - // When color material is active, we can't pre-compute light products so we upload raw light and material values - sb.append("uniform vec4 u_LightModelAmbient;\n"); - sb.append("uniform vec4 u_MaterialEmission;\n"); - sb.append("uniform vec4 u_MaterialAmbient;\n"); - sb.append("uniform vec4 u_MaterialDiffuse;\n"); - sb.append("uniform vec4 u_MaterialSpecular;\n"); - sb.append("uniform float u_MaterialShininess;\n"); - - if (key.light0Enabled()) { - sb.append("uniform vec4 u_Light0Ambient;\n"); - sb.append("uniform vec4 u_Light0Diffuse;\n"); - sb.append("uniform vec4 u_Light0Specular;\n"); - sb.append("uniform vec4 u_Light0Position;\n"); - } - if (key.light1Enabled()) { - sb.append("uniform vec4 u_Light1Ambient;\n"); - sb.append("uniform vec4 u_Light1Diffuse;\n"); - sb.append("uniform vec4 u_Light1Specular;\n"); - sb.append("uniform vec4 u_Light1Position;\n"); - } - } else { - // Pre-computed: sceneColor + lightProducts - sb.append("uniform vec4 u_SceneColor;\n"); - - if (key.light0Enabled()) { - sb.append("uniform vec4 u_Light0Position;\n"); - sb.append("uniform vec3 u_LightProd0Ambient;\n"); - sb.append("uniform vec3 u_LightProd0Diffuse;\n"); - sb.append("uniform vec3 u_LightProd0Specular;\n"); - } - if (key.light1Enabled()) { - sb.append("uniform vec4 u_Light1Position;\n"); - sb.append("uniform vec3 u_LightProd1Ambient;\n"); - sb.append("uniform vec3 u_LightProd1Diffuse;\n"); - sb.append("uniform vec3 u_LightProd1Specular;\n"); - } - sb.append("uniform float u_MaterialShininess;\n"); - } - } - private static void emitOutputs(StringBuilder sb, VertexKey key) { sb.append("// Outputs\n"); sb.append("out vec4 v_Color;\n"); @@ -218,22 +117,30 @@ public final class VertexShaderGenerator { private static void emitPositionTransform(StringBuilder sb, VertexKey key) { sb.append(" // Position transform\n"); sb.append(" vec4 pos4 = vec4(a_Position, 1.0);\n"); - sb.append(" gl_Position = u_MVPMatrix * pos4;\n"); + if (key.instancedDraw()) { + sb.append(" mat4 instMV = mat4(a_InstCol0, a_InstCol1, a_InstCol2, a_InstCol3);\n"); + sb.append(" vec4 eyePos = instMV * pos4;\n"); + sb.append(" gl_Position = u_ProjectionMatrix * eyePos;\n"); + } else { + sb.append(" gl_Position = u_MVPMatrix * pos4;\n"); - // Eye position needed for lighting, fog, EYE_LINEAR texgen, and clip planes - if (key.lightingEnabled() || key.fogEnabled() || texGenNeedsEyePos(key) || key.clipPlanesEnabled()) { - sb.append(" vec4 eyePos = u_ModelViewMatrix * pos4;\n"); + // Eye position needed for lighting, fog, EYE_LINEAR texgen, and clip planes + if (key.lightingEnabled() || key.fogEnabled() || texGenNeedsEyePos(key) || key.clipPlanesEnabled()) { + sb.append(" vec4 eyePos = u_ModelViewMatrix * pos4;\n"); + } } sb.append('\n'); } private static void emitNormalTransform(StringBuilder sb, VertexKey key) { sb.append(" // Normal transform\n"); - if (key.hasVertexNormal()) { - sb.append(" vec3 normal = u_NormalMatrix * a_Normal;\n"); - } else { - sb.append(" vec3 normal = u_NormalMatrix * u_CurrentNormal;\n"); + final String srcNormal = key.hasVertexNormal() ? "a_Normal" : "u_CurrentNormal"; + if (key.instancedDraw()) { + sb.append(" vec3 normal = normalize(mat3(instMV) * ").append(srcNormal).append(");\n"); + sb.append('\n'); + return; } + sb.append(" vec3 normal = u_NormalMatrix * ").append(srcNormal).append(";\n"); if (key.normalizeEnabled()) { sb.append(" normal = normalize(normal);\n"); @@ -250,6 +157,9 @@ public final class VertexShaderGenerator { // Color material: vertex color replaces specific material properties per glColorMaterial mode (Mesa ffvertex_prog.c get_material() bitmask approach) sb.append(" vec4 matColor = "); sb.append(key.hasVertexColor() ? "a_Color" : "u_CurrentColor"); + if (key.instancedDraw()) { + sb.append(" * a_InstColor"); + } sb.append(";\n"); // Emission source: vertex color for CM_EMISSION, else material uniform @@ -345,10 +255,11 @@ public final class VertexShaderGenerator { private static void emitColorPassthrough(StringBuilder sb, VertexKey key) { sb.append(" // Color passthrough (no lighting)\n"); - if (key.hasVertexColor()) { - sb.append(" v_Color = a_Color;\n"); + final String src = key.hasVertexColor() ? "a_Color" : "u_CurrentColor"; + if (key.instancedDraw()) { + sb.append(" v_Color = ").append(src).append(" * a_InstColor;\n"); } else { - sb.append(" v_Color = u_CurrentColor;\n"); + sb.append(" v_Color = ").append(src).append(";\n"); } sb.append('\n'); } @@ -369,7 +280,9 @@ public final class VertexShaderGenerator { } if (key.lightmapEnabled()) { - if (key.hasVertexLightmap()) { + if (key.instancedDraw()) { + sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(a_InstLightmap, 0.0, 1.0);\n"); + } else if (key.hasVertexLightmap()) { sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(a_TexCoord1, 0.0, 1.0);\n"); } else { sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(u_CurrentLightmapCoord, 0.0, 1.0);\n"); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMConfig.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMConfig.java index 60fc9879b..a6dd9e5c6 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMConfig.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMConfig.java @@ -8,5 +8,7 @@ public final class GLSMConfig { public static boolean hudCacheOverride; + public static volatile boolean expandVertexFormats; + private GLSMConfig() {} } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java index ff9a603aa..fb2ad5891 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java @@ -9,28 +9,36 @@ public final class GLSMHooks { public static DeferredAlphaHandler alphaHandler; public static DeferredDepthColorHandler depthColorHandler; public static GlintColorHandler glintColorHandler; + public static ShaderWorkSubmitter shaderWorkSubmitter; + public static ShaderTransformPostProcessor postTransformProcessor; + public static PerFrameUniformBlock perFrameUniformBlock; + public static PerFrameUniformBlock perPassUniformBlock; // EventBus instances public static final EventBus TEXTURE_BIND = EventBus.create(TextureBindEvent.class); public static final EventBus TEXTURE_DELETE = EventBus.create(TextureDeleteEvent.class); public static final EventBus TEXTURE_UNIT_STATE = EventBus.create(TextureUnitStateEvent.class); public static final EventBus PROGRAM_CHANGE = EventBus.create(ProgramChangeEvent.class); + public static final EventBus PROGRAM_DELETE = EventBus.create(ProgramDeleteEvent.class); public static final EventBus BLEND_FUNC_CHANGE = EventBus.create(BlendFuncChangeEvent.class); public static final EventBus FOG_STATE_CHANGE = EventBus.create(FogStateChangeEvent.class); public static final EventBus LIGHTMAP_COORDS = EventBus.create(LightmapCoordsEvent.class); public static final EventBus ALPHA_STATE_CHANGE = EventBus.create(AlphaStateChangeEvent.class); public static final EventBus SHADER_COLOR_CHANGE = EventBus.create(ShaderColorChangeEvent.class); + public static final EventBus LOADING_CHECKPOINT = EventBus.create(LoadingCheckpointEvent.class); // Reusable event instances public static final TextureBindEvent textureBindEvent = new TextureBindEvent(); public static final TextureDeleteEvent textureDeleteEvent = new TextureDeleteEvent(); public static final TextureUnitStateEvent textureUnitStateEvent = new TextureUnitStateEvent(); public static final ProgramChangeEvent programChangeEvent = new ProgramChangeEvent(); + public static final ProgramDeleteEvent programDeleteEvent = new ProgramDeleteEvent(); public static final BlendFuncChangeEvent blendFuncChangeEvent = new BlendFuncChangeEvent(); public static final FogStateChangeEvent fogStateChangeEvent = new FogStateChangeEvent(); public static final LightmapCoordsEvent lightmapCoordsEvent = new LightmapCoordsEvent(); public static final AlphaStateChangeEvent alphaStateChangeEvent = new AlphaStateChangeEvent(); public static final ShaderColorChangeEvent shaderColorChangeEvent = new ShaderColorChangeEvent(); + public static final LoadingCheckpointEvent loadingCheckpointEvent = new LoadingCheckpointEvent(); private GLSMHooks() {} } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMInitConfig.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMInitConfig.java index 601681cc2..e820e922d 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMInitConfig.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMInitConfig.java @@ -2,19 +2,20 @@ package com.gtnewhorizons.angelica.glsm.hooks; import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; +import lombok.Getter; import java.util.function.Consumer; public final class GLSMInitConfig { - private final boolean lwjglDebug; - private final StreamingUploader.UploadStrategy streamingUploadStrategy; - private final Consumer directDrawer; - private final Runnable streamingDrawerDestroy; - private final int displayWidth; - private final int displayHeight; - private final Runnable postInitCallback; - private final boolean enableDSA; - private final boolean noErrorChecks; + @Getter private final boolean lwjglDebug; + @Getter private final StreamingUploader.UploadStrategy streamingUploadStrategy; + @Getter private final Consumer directDrawer; + @Getter private final Runnable streamingDrawerDestroy; + @Getter private final int displayWidth; + @Getter private final int displayHeight; + @Getter private final Runnable postInitCallback; + @Getter private final boolean DSAEnabled; + @Getter private final boolean noErrorChecks; private GLSMInitConfig(Builder builder) { this.lwjglDebug = builder.lwjglDebug; @@ -25,23 +26,13 @@ public final class GLSMInitConfig { this.displayWidth = builder.displayWidth; this.displayHeight = builder.displayHeight; this.postInitCallback = builder.postInitCallback; - this.enableDSA = builder.enableDSA; + this.DSAEnabled = builder.enableDSA; } public static Builder builder() { return new Builder(); } - public boolean isLwjglDebug() { return lwjglDebug; } - public StreamingUploader.UploadStrategy getStreamingUploadStrategy() { return streamingUploadStrategy; } - public Consumer getDirectDrawer() { return directDrawer; } - public Runnable getStreamingDrawerDestroy() { return streamingDrawerDestroy; } - public int getDisplayWidth() { return displayWidth; } - public int getDisplayHeight() { return displayHeight; } - public Runnable getPostInitCallback() { return postInitCallback; } - public boolean isDSAEnabled() { return enableDSA; } - public boolean noErrorChecks() { return noErrorChecks; } - public static final class Builder { private boolean lwjglDebug = false; private StreamingUploader.UploadStrategy streamingUploadStrategy = StreamingUploader.UploadStrategy.BUFFER_DATA; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PerFrameUniformBlock.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PerFrameUniformBlock.java new file mode 100644 index 000000000..b68cc6faa --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PerFrameUniformBlock.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.glsm.hooks; + +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + +import java.util.List; + +/** + * Shared per-frame uniform block for SDL GPU. Produced by Iris once per shader pack load. Every shader declares the + * whole block regardless of which members it reads. + */ +public record PerFrameUniformBlock(List members) { + + public record Member(String name, UniformType type) {} + + public boolean isEmpty() { + return members.isEmpty(); + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderTransformPostProcessor.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderTransformPostProcessor.java new file mode 100644 index 000000000..00ed67df3 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderTransformPostProcessor.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.glsm.hooks; + +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; + +@FunctionalInterface +public interface ShaderTransformPostProcessor { + void onTransformed(String transformedSource, ShaderType shaderType); +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderWorkSubmitter.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderWorkSubmitter.java new file mode 100644 index 000000000..1a7b3a916 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/ShaderWorkSubmitter.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.glsm.hooks; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public interface ShaderWorkSubmitter { + CompletableFuture submit(Supplier work); +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/LoadingCheckpointEvent.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/LoadingCheckpointEvent.java new file mode 100644 index 000000000..2bc03bb03 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/LoadingCheckpointEvent.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.glsm.hooks.events; + +import net.minecraftforge.eventbus.api.event.MutableEvent; + +/** Fired at loading-phase boundaries */ +public final class LoadingCheckpointEvent extends MutableEvent { + public boolean requiresSync; +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ProgramDeleteEvent.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ProgramDeleteEvent.java new file mode 100644 index 000000000..1b10e206a --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ProgramDeleteEvent.java @@ -0,0 +1,7 @@ +package com.gtnewhorizons.angelica.glsm.hooks.events; + +import net.minecraftforge.eventbus.api.event.MutableEvent; + +public final class ProgramDeleteEvent extends MutableEvent { + public int program; +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/Tracy.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/Tracy.java new file mode 100644 index 000000000..c5d9df4a5 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/Tracy.java @@ -0,0 +1,422 @@ +package com.gtnewhorizons.angelica.glsm.profiling; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.CaptureGate; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.sun.management.ThreadMXBean; +import lombok.Setter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +@SuppressWarnings("ForLoopReplaceableByForEach") +public final class Tracy { + private static final Logger LOGGER = LogManager.getLogger("Tracy"); + + public static final boolean ENABLED; + public static final boolean FINE_ZONES; + private static final TracyBackend BACKEND; + private static volatile boolean SHUTTING_DOWN; + + private static final ConcurrentHashMap CLIENT_SRC_LOCS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap SERVER_SRC_LOCS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap PLAIN_SRC_LOCS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap PLOT_NAMES = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap FRAME_NAMES = new ConcurrentHashMap<>(); + private static final Set WARNED_LEAKS = ConcurrentHashMap.newKeySet(); + + public static final int COLOR_CLIENT = 0x3A6EA5; // blue + public static final int COLOR_SERVER = 0xB5651D; // brown + public static final int COLOR_WORKER = 0x3F7F3F; // green + public static final int COLOR_SWAP = 0xAA3333; // red + public static final int COLOR_TERRAIN = 0x2E8B8B; // teal + public static final int COLOR_IRIS = 0x9E862E; // gold + public static final int COLOR_FFP = 0x7A4E9E; // purple + + private static final ThreadLocal STACK = new ThreadLocal<>() { + @Override + protected ZoneStack initialValue() { + BACKEND.setCurrentThreadName(Thread.currentThread().getName()); + return new ZoneStack(); + } + }; + + static { + TracyBackend backend = null; + if (SystemProperties.TRACY) { + backend = loadAndInit(); + } + BACKEND = backend; + ENABLED = backend != null; + FINE_ZONES = ENABLED && SystemProperties.TRACY_FINE_ZONES; + if (ENABLED) { + Runtime.getRuntime().addShutdownHook(new Thread(Tracy::shutdown, "Tracy-Shutdown")); + LOGGER.info("Tracy profiling enabled"); + } + } + + private Tracy() {} + + private static void shutdown() { + SHUTTING_DOWN = true; + final Thread worker = new Thread(BACKEND::shutdown, "Tracy-Shutdown-Worker"); + worker.setDaemon(true); + worker.start(); + try { + worker.join(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private static TracyBackend loadAndInit() { + TracyBackend found = null; + try { + final Iterator it = ServiceLoader.load(TracyBackend.class, TracyBackend.class.getClassLoader()).iterator(); + while (found == null && it.hasNext()) { + found = it.next(); + } + } catch (ServiceConfigurationError | LinkageError e) { + LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but backend unavailable: {}", e.getMessage()); + return null; + } + if (found == null) { + LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but no TracyBackend service present"); + return null; + } + final TracyBackend backend = found; + final CountDownLatch done = new CountDownLatch(1); + final AtomicReference result = new AtomicReference<>(); + final Thread init = new Thread(new InitRunner(backend, done, result), "Tracy-Init"); + init.setDaemon(true); + init.start(); + try { + if (!done.await(15, TimeUnit.SECONDS) && result.compareAndSet(null, Boolean.FALSE)) { + LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but init timed out; profiling disabled"); + return null; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + if (!result.compareAndSet(null, Boolean.FALSE) && Boolean.TRUE.equals(result.get())) { + backend.shutdown(); + } + return null; + } + if (!Boolean.TRUE.equals(result.get())) { + LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but native init failed; profiling disabled"); + return null; + } + return backend; + } + + private record InitRunner(TracyBackend backend, CountDownLatch done, AtomicReference result) implements Runnable { + @Override + public void run() { + final boolean ok = backend.init(); + if (!result.compareAndSet(null, ok) && ok) { + backend.shutdown(); + } + done.countDown(); + } + } + + public static void beginSection(String name) { + if (!ENABLED) return; + if ("root".equals(name)) { + unwindToRoot(STACK.get()); + } + if (!CaptureGate.markersThisFrame) { + skip(name); + return; + } + final boolean client = Thread.currentThread() == GLStateManager.getMainThread(); + final ConcurrentHashMap map = client ? CLIENT_SRC_LOCS : SERVER_SRC_LOCS; + Long srcLoc = map.get(name); + if (srcLoc == null) { + srcLoc = map.computeIfAbsent(name, n -> BACKEND.internSrcLoc((client ? "cl:" : "sv:") + n, client ? classifySection(n) : COLOR_SERVER)); + } + begin(srcLoc, name); + } + + private static int classifySection(String name) { + if (name.startsWith("iris_")) return COLOR_IRIS; + if (name.startsWith("draw_chunk_layer")) return COLOR_TERRAIN; + return COLOR_CLIENT; + } + + private static void unwindToRoot(ZoneStack stack) { + while (stack.depth() > 0 || stack.hasSkipped()) { + final long ctx = stack.pop(); + if (ctx == ZoneStack.EMPTY) continue; + if (stack.poppedGpu()) { + BACKEND.gpuEndZone(); + } + if (ctx != 0L) { + BACKEND.endZone(ctx); + } + final String name = stack.poppedName(); + if (name != null && WARNED_LEAKS.add(name)) { + LOGGER.warn("Tracy: unbalanced profiler section '{}' left open (leaked by its caller); closed at next root", name); + BACKEND.message("unbalanced profiler section '" + name + "' closed at root"); + } + } + } + + public static void beginZone(String name) { + beginZone(name, COLOR_WORKER); + } + + public static void beginZone(String name, int color) { + if (!ENABLED || SHUTTING_DOWN) return; + if (!CaptureGate.markersThisFrame) { + skip(name); + return; + } + Long srcLoc = PLAIN_SRC_LOCS.get(name); + if (srcLoc == null) { + srcLoc = PLAIN_SRC_LOCS.computeIfAbsent(name, n -> BACKEND.internSrcLoc(n, color)); + } + begin(srcLoc, name); + } + + public static final class ZoneId { + private final long srcLoc; + private final String name; + + private ZoneId(long srcLoc, String name) { + this.srcLoc = srcLoc; + this.name = name; + } + } + + public static ZoneId zoneId(String name) { + return zoneId(name, COLOR_WORKER); + } + + public static ZoneId zoneId(String name, int color) { + if (!ENABLED) return new ZoneId(0L, name); + Long srcLoc = PLAIN_SRC_LOCS.get(name); + if (srcLoc == null) { + srcLoc = PLAIN_SRC_LOCS.computeIfAbsent(name, n -> BACKEND.internSrcLoc(n, color)); + } + return new ZoneId(srcLoc, name); + } + + public static void beginZone(ZoneId zone) { + if (!ENABLED || SHUTTING_DOWN) return; + begin(zone.srcLoc, zone.name); + } + + private static void skip(String name) { + STACK.get().push(0L, false, name); + } + + private static void begin(long srcLoc, String name) { + if (SHUTTING_DOWN) return; + final ZoneStack stack = STACK.get(); + if (srcLoc == 0 || !CaptureGate.markersThisFrame || stack.atCap()) { + stack.push(0L, false, name); + return; + } + final long ctx = BACKEND.beginZone(srcLoc); + final boolean gpu = gpuReady && gpuZonesEnabled && Thread.currentThread() == GLStateManager.getMainThread() && BACKEND.gpuBeginZone(srcLoc); + stack.push(ctx, gpu, name); + if (srcLoc == BACKEND.dynamicSrcLoc()) { + BACKEND.zoneText(ctx, name); + } + } + + public static void endZone() { + if (!ENABLED || SHUTTING_DOWN) return; + final ZoneStack stack = STACK.get(); + final long ctx = stack.pop(); + if (ctx == ZoneStack.EMPTY) return; + if (stack.poppedGpu()) { + BACKEND.gpuEndZone(); + } + if (ctx != 0L) { + BACKEND.endZone(ctx); + } + } + + public static void zoneText(String text) { + if (!ENABLED || SHUTTING_DOWN) return; + final long ctx = STACK.get().peek(); + if (ctx != ZoneStack.EMPTY && ctx != 0L) { + BACKEND.zoneText(ctx, text); + } + } + + public static void zoneValue(long value) { + if (!ENABLED || SHUTTING_DOWN) return; + final long ctx = STACK.get().peek(); + if (ctx != ZoneStack.EMPTY && ctx != 0L) { + BACKEND.zoneValue(ctx, value); + } + } + + private static boolean threadNameRefreshed; + + public static void frameMark() { + if (!ENABLED || SHUTTING_DOWN) return; + if (!threadNameRefreshed) { + threadNameRefreshed = true; + BACKEND.setCurrentThreadName(Thread.currentThread().getName()); + } + BACKEND.frameMark(); + } + + public static void frameMark(String name) { + if (!ENABLED || SHUTTING_DOWN) return; + Long ptr = FRAME_NAMES.get(name); + if (ptr == null) { + ptr = FRAME_NAMES.computeIfAbsent(name, BACKEND::internFrameName); + } + if (ptr != 0) BACKEND.frameMark(ptr); + } + + public static void plotInt(String name, long value) { + plotInt(name, value, TracyBackend.PLOT_FORMAT_NUMBER); + } + + public static void plotInt(String name, long value, int format) { + if (!ENABLED || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return; + final long ptr = plotName(name, format); + if (ptr != 0) BACKEND.plotInt(ptr, value); + } + + public static void plot(String name, double value) { + if (!ENABLED || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return; + final long ptr = plotName(name, TracyBackend.PLOT_FORMAT_NUMBER); + if (ptr != 0) BACKEND.plot(ptr, value); + } + + private static long plotName(String name, int format) { + Long ptr = PLOT_NAMES.get(name); + if (ptr == null) { + ptr = PLOT_NAMES.computeIfAbsent(name, n -> BACKEND.internPlotName(n, format)); + } + return ptr; + } + + public static long plotHandle(String name, int format) { + if (!ENABLED || SHUTTING_DOWN) return 0; + return plotName(name, format); + } + + public static long plotHandle(String name) { + return plotHandle(name, TracyBackend.PLOT_FORMAT_NUMBER); + } + + public static void plotInt(long handle, long value) { + if (handle == 0 || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return; + BACKEND.plotInt(handle, value); + } + + public static void plot(long handle, double value) { + if (handle == 0 || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return; + BACKEND.plot(handle, value); + } + + public static void message(String text) { + if (!ENABLED || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return; + BACKEND.message(text); + } + + public static boolean isConnected() { + return ENABLED && BACKEND.isConnected(); + } + + private static boolean gpuInitAttempted; + private static boolean gpuReady; + @Setter private static boolean gpuZonesEnabled = true; + + public static void gpuCollect() { + if (!ENABLED) return; + if (!gpuInitAttempted) { + gpuInitAttempted = true; + gpuReady = BACKEND.gpuInit(); + } + if (gpuReady) BACKEND.gpuCollect(); + } + + private static final class AllocBean { + static final ThreadMXBean BEAN; + static { + ThreadMXBean bean = null; + try { + if (ManagementFactory.getThreadMXBean() instanceof ThreadMXBean sun && sun.isThreadAllocatedMemorySupported()) { + bean = sun; + } + } catch (Throwable ignored) {} + BEAN = bean; + } + } + + private static final ThreadLocal PREV_ALLOC = ThreadLocal.withInitial(() -> new long[1]); + + public static void plotAllocRate(long plotHandle) { + if (!ENABLED || SHUTTING_DOWN || AllocBean.BEAN == null) return; + if (!CaptureGate.markersThisFrame) { + PREV_ALLOC.get()[0] = 0; + return; + } + final long now = AllocBean.BEAN.getThreadAllocatedBytes(Thread.currentThread().threadId()); + if (now < 0) return; + final long[] prev = PREV_ALLOC.get(); + if (prev[0] != 0) { + plotInt(plotHandle, now - prev[0]); + } + prev[0] = now; + } + + private static List gcBeans; + private static boolean gcBaselineValid; + private static long prevGcCount; + private static long prevGcTimeMs; + private static long gcCountHandle; + private static long gcTimeHandle; + + public static void plotGcStats() { + if (!ENABLED || SHUTTING_DOWN) return; + if (!CaptureGate.markersThisFrame) { + gcBaselineValid = false; + return; + } + if (gcBeans == null) { + gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); + gcCountHandle = plotHandle("gcCount"); + gcTimeHandle = plotHandle("gcTimeMs"); + } + long count = 0; + long timeMs = 0; + for (int i = 0; i < gcBeans.size(); i++) { + final GarbageCollectorMXBean bean = gcBeans.get(i); + final long c = bean.getCollectionCount(); + final long t = bean.getCollectionTime(); + if (c > 0) count += c; + if (t > 0) timeMs += t; + } + if (gcBaselineValid) { + plotInt(gcCountHandle, count - prevGcCount); + plotInt(gcTimeHandle, timeMs - prevGcTimeMs); + if (count > prevGcCount) { + message("GC: +" + (count - prevGcCount) + " collections, +" + (timeMs - prevGcTimeMs) + " ms"); + } + } + gcBaselineValid = true; + prevGcCount = count; + prevGcTimeMs = timeMs; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/TracyBackend.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/TracyBackend.java new file mode 100644 index 000000000..513c01eda --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/TracyBackend.java @@ -0,0 +1,36 @@ +package com.gtnewhorizons.angelica.glsm.profiling; + +public interface TracyBackend { + int PLOT_FORMAT_NUMBER = 0; + int PLOT_FORMAT_MEMORY = 1; + int PLOT_FORMAT_PERCENTAGE = 2; + + boolean init(); + + long internSrcLoc(String name, int color); + long dynamicSrcLoc(); + + long beginZone(long srcLoc); + void endZone(long ctx); + + void zoneText(long ctx, String text); + void zoneValue(long ctx, long value); + + void frameMark(); + void frameMark(long namePtr); + + long internFrameName(String name); + long internPlotName(String name, int format); + + void plotInt(long namePtr, long value); + void plot(long namePtr, double value); + void message(String text); + void setCurrentThreadName(String name); + boolean isConnected(); + void shutdown(); + + boolean gpuInit(); + boolean gpuBeginZone(long srcLoc); + void gpuEndZone(); + void gpuCollect(); +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/ZoneStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/ZoneStack.java new file mode 100644 index 000000000..1398dbd6b --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/profiling/ZoneStack.java @@ -0,0 +1,87 @@ +package com.gtnewhorizons.angelica.glsm.profiling; + +public final class ZoneStack { + public static final long EMPTY = -1L; + static final int MAX_DEPTH = 512; + + private long[] stack = new long[64]; + private boolean[] gpu = new boolean[64]; + private String[] names = new String[64]; + private int depth; + private int skipped; + private boolean lastPoppedGpu; + private String lastPoppedName; + + public boolean atCap() { + return depth == MAX_DEPTH; + } + + public boolean push(long ctx) { + return push(ctx, false, null); + } + + public boolean push(long ctx, boolean gpuBracketed) { + return push(ctx, gpuBracketed, null); + } + + public boolean push(long ctx, boolean gpuBracketed, String name) { + if (depth == MAX_DEPTH) { + skipped++; + return false; + } + if (depth == stack.length) { + final long[] grownStack = new long[stack.length * 2]; + System.arraycopy(stack, 0, grownStack, 0, stack.length); + stack = grownStack; + final boolean[] grownGpu = new boolean[gpu.length * 2]; + System.arraycopy(gpu, 0, grownGpu, 0, gpu.length); + gpu = grownGpu; + final String[] grownNames = new String[names.length * 2]; + System.arraycopy(names, 0, grownNames, 0, names.length); + names = grownNames; + } + gpu[depth] = gpuBracketed; + names[depth] = name; + stack[depth++] = ctx; + return true; + } + + public long pop() { + if (skipped > 0) { + skipped--; + lastPoppedGpu = false; + lastPoppedName = null; + return EMPTY; + } + if (depth == 0) { + lastPoppedGpu = false; + lastPoppedName = null; + return EMPTY; + } + lastPoppedGpu = gpu[--depth]; + lastPoppedName = names[depth]; + names[depth] = null; + return stack[depth]; + } + + public boolean poppedGpu() { + return lastPoppedGpu; + } + + public String poppedName() { + return lastPoppedName; + } + + public boolean hasSkipped() { + return skipped > 0; + } + + public long peek() { + if (skipped > 0 || depth == 0) return EMPTY; + return stack[depth - 1]; + } + + public int depth() { + return depth; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AttribSnapshot.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AttribSnapshot.java index 672ea543d..5846096a2 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AttribSnapshot.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AttribSnapshot.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; @@ -10,16 +11,24 @@ import org.lwjgl.opengl.GL15; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; public final class AttribSnapshot { + private static final Set WARN_ONCE = ConcurrentHashMap.newKeySet(); + + private static void warnOnce(String key, String fmt, Object... args) { + if (WARN_ONCE.add(key)) GLStateManager.LOGGER.warn(fmt, args); + } + public record AttribDesc(int location, int size, int type, boolean normalized, int stride, long offset, int sourceVboId, ByteBuffer readBuffer, long readBufferBaseOffset) { public int effectiveStride() { - return stride != 0 ? stride : size * VAOManager.Attrib.glTypeSizeBytes(type); + return stride != 0 ? stride : size * GLTypes.sizeBytes(type); } public int typeSizeBytes() { - return VAOManager.Attrib.glTypeSizeBytes(type); + return GLTypes.sizeBytes(type); } } @@ -59,6 +68,7 @@ public final class AttribSnapshot { final AttribDesc[] out = new AttribDesc[VAOManager.MAX_ATTRIBS]; final List allocated = new ArrayList<>(); final int prevVBO = GLStateManager.getBoundVBO(); + boolean success = false; // Pass 1 — unioned [start,end] per vboId. Hot path: one source VBO, zero allocations. int rangeSoleVboId = 0; @@ -71,7 +81,7 @@ public final class AttribSnapshot { final VAOManager.Attrib a = VAOManager.get(i); if (a == null || !a.enabled || a.vboId == 0) continue; final int stride = a.effectiveStride(); - final long typeBytes = (long) a.size * VAOManager.Attrib.glTypeSizeBytes(a.type); + final long typeBytes = (long) a.size * GLTypes.sizeBytes(a.type); final long start = a.offset + (long) firstVertex * stride; final long end = a.offset + lastVtx * stride + typeBytes; @@ -125,8 +135,8 @@ public final class AttribSnapshot { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, a.vboId); final int bufferSize = GLStateManager.glGetBufferParameteri(GL15.GL_ARRAY_BUFFER, GL15.GL_BUFFER_SIZE); if (bufferSize <= 0) { - GLStateManager.LOGGER.warn("[VBO Readback] GL_BUFFER_SIZE={} for VBO {}", bufferSize, a.vboId); - continue; + warnOnce("vbo-orphaned", "[AttribSnapshot] GL_BUFFER_SIZE={} for VBO {} -- skipping capture", bufferSize, a.vboId); + return null; } final long rStart; @@ -139,9 +149,16 @@ public final class AttribSnapshot { rStart = rangeSoleStart; rEnd = rangeSoleEnd; } + if (rEnd > bufferSize) { + warnOnce("vbo-overrun", "[AttribSnapshot] attrib range {}..{} exceeds VBO {} size {} -- skipping capture", rStart, rEnd, a.vboId, bufferSize); + return null; + } final long ro = Math.max(0, rStart); - final int rs = (int) (Math.min(bufferSize, rEnd) - ro); - if (rs <= 0) continue; + final int rs = (int) (rEnd - ro); + if (rs <= 0) { + warnOnce("vbo-empty-range", "[AttribSnapshot] empty attrib range {}..{} for VBO {} -- skipping capture", rStart, rEnd, a.vboId); + return null; + } buf = MemoryUtilities.memAlloc(rs); GLStateManager.glGetBufferSubData(GL15.GL_ARRAY_BUFFER, ro, buf); @@ -169,10 +186,13 @@ public final class AttribSnapshot { out[i] = new AttribDesc(i, a.size, a.type, a.normalized, a.stride, a.clientPointer.position(), 0, a.clientPointer, 0L); } } + success = true; + return new AttribSnapshot(out, allocated); } finally { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, prevVBO); + if (!success) { + for (ByteBuffer b : allocated) MemoryUtilities.memFree(b); + } } - - return new AttribSnapshot(out, allocated); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java index 791c3e217..2b965c0b9 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; /** * A class that stores multiple vertex formats & their corresponding buffers. @@ -37,12 +38,14 @@ public final class DisplayListVBO { private final int drawMode; private final int start; private final int count; + private final int vertexFlags; - public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count) { + public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count, int vertexFlags) { this.vao = vao; this.drawMode = drawMode; this.start = start; this.count = count; + this.vertexFlags = vertexFlags; } public int getStart() { @@ -62,11 +65,12 @@ public final class DisplayListVBO { } public void render() { - if (vao == null) return; - vao.bind(); - if (count <= 0) { vao.unbind(); return; } - vao.draw(drawMode, start, count); - vao.unbind(); + if (vao == null) return; + vao.bind(); + if (count <= 0) { vao.unbind(); return; } + VAOManager.setCurrentVertexFlags(vertexFlags); + vao.draw(drawMode, start, count); + vao.unbind(); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java index 1255b87c4..f04a7af58 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java @@ -72,17 +72,18 @@ public final class DisplayListVBOBuilder { } vertexCount = format.getVertexCount(size); } + final int flags = format.getVertexFlags(); if (data.drawMode == GL11.GL_QUADS) { final IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount)); - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6, flags); } else if (data.drawMode == GL11.GL_QUAD_STRIP) { // GL_QUAD_STRIP is removed in core profile; an even-length GL_TRIANGLE_STRIP produces the same quads - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, GL11.GL_TRIANGLE_STRIP, start, vertexCount & ~1); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, GL11.GL_TRIANGLE_STRIP, start, vertexCount & ~1, flags); } else if (data.drawMode == GL11.GL_POLYGON) { // GL_POLYGON is removed in core profile; convert to GL_TRIANGLE_FAN which is equivalent for convex polygons - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, GL11.GL_TRIANGLE_FAN, start, vertexCount); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, GL11.GL_TRIANGLE_FAN, start, vertexCount, flags); } else { - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount, flags); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java index 270ed2cf2..703b570c0 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java @@ -203,6 +203,7 @@ public final class ImmediateModeRecorder { */ public static DirectTessellator processDrawArraysFromAttribs(int mode, int first, int count) { final AttribSnapshot snap = AttribSnapshot.snapshot(first, count); + if (snap == null) return null; try { prepareReaders(snap); if (positionReaderIndex < 0) return null; @@ -307,36 +308,4 @@ public final class ImmediateModeRecorder { return VAOManager.Attrib.readComponent(r.type, r.normalized, r.data, base, component); } - public static float readComponent(int type, boolean normalized, ByteBuffer buf, int base, int component) { - return switch (type) { - case GL11.GL_FLOAT -> buf.getFloat(base + component * 4); - case GL11.GL_DOUBLE -> (float) buf.getDouble(base + component * 8); - case GL11.GL_INT -> { - final int v = buf.getInt(base + component * 4); - yield normalized ? v / (float) Integer.MAX_VALUE : (float) v; - } - case GL11.GL_UNSIGNED_INT -> { - final int v = buf.getInt(base + component * 4); - yield normalized ? (v & 0xFFFFFFFFL) / (float) 0xFFFFFFFFL : (float) (v & 0xFFFFFFFFL); - } - case GL11.GL_SHORT -> { - final short v = buf.getShort(base + component * 2); - yield normalized ? v / (float) Short.MAX_VALUE : (float) v; - } - case GL11.GL_UNSIGNED_SHORT -> { - final int v = buf.getShort(base + component * 2) & 0xFFFF; - yield normalized ? v / (float) 0xFFFF : (float) v; - } - case GL11.GL_BYTE -> { - final byte v = buf.get(base + component); - yield normalized ? v / 127.0f : (float) v; - } - case GL11.GL_UNSIGNED_BYTE -> { - final int v = buf.get(base + component) & 0xFF; - yield normalized ? v / 255.0f : (float) v; - } - default -> 0.0f; - }; - } - } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AttribLayoutKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AttribLayoutKey.java index 8d8affa6d..6bfc73841 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AttribLayoutKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/AttribLayoutKey.java @@ -1,6 +1,6 @@ package com.gtnewhorizons.angelica.glsm.recording.commands; -import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import java.util.Arrays; @@ -24,7 +24,7 @@ public final class AttribLayoutKey { int base = 0; int maxAlign = 1; for (int i = 0; i < n; i++) { - final int typeSize = VAOManager.Attrib.glTypeSizeBytes(types[i]); + final int typeSize = GLTypes.sizeBytes(types[i]); if (typeSize > maxAlign) maxAlign = typeSize; base = (base + typeSize - 1) & -typeSize; off[i] = base; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/IndexedDrawCapture.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/IndexedDrawCapture.java index 495a6f56f..ea663c104 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/IndexedDrawCapture.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/IndexedDrawCapture.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.recording.commands; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import com.gtnewhorizons.angelica.glsm.QuadConverter; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; import com.gtnewhorizons.angelica.glsm.recording.AttribSnapshot; @@ -60,7 +61,7 @@ public final class IndexedDrawCapture { GLStateManager.warnOnce("quads-misaligned", "[IndexedDrawCapture] GL_QUADS with indicesCount={} not a multiple of 4 — skipping", indicesCount); return null; } - final int srcIndexSize = VAOManager.Attrib.glTypeSizeBytes(srcIndexType); + final int srcIndexSize = GLTypes.sizeBytes(srcIndexType); if (srcIndexSize <= 0) return null; final int prevEBO = GLStateManager.getBoundEBO(); @@ -95,7 +96,7 @@ public final class IndexedDrawCapture { GLStateManager.warnOnce("quads-misaligned", "[IndexedDrawCapture] GL_QUADS with indicesCount={} not a multiple of 4 - skipping", indicesCount); return null; } - final int idxSize = VAOManager.Attrib.glTypeSizeBytes(srcIndexType); + final int idxSize = GLTypes.sizeBytes(srcIndexType); if (idxSize <= 0) return null; if ((long) indicesCount * idxSize > srcByteLength) { GLStateManager.warnOnce("client-idx-range", "[IndexedDrawCapture] index count {} ({} bytes) exceeds client buffer {} bytes - skipping", indicesCount, (long) indicesCount * idxSize, srcByteLength); @@ -120,6 +121,7 @@ public final class IndexedDrawCapture { final int vertexCount = maxVtx - minVtx + 1; snap = AttribSnapshot.snapshot(minVtx, vertexCount); + if (snap == null) return null; int enabledCount = 0; for (int i = 0; i < VAOManager.MAX_ATTRIBS; i++) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexImage2DCmd.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexImage2DCmd.java index d68f21e4b..b641204d6 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexImage2DCmd.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexImage2DCmd.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.recording.commands; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -78,6 +79,6 @@ public record TexImage2DCmd( String dataStr = pixels != null ? (pixels.remaining() + " bytes") : "null"; return String.format("TexImage2D(target=%s, level=%d, internalformat=%s, %dx%d, border=%d, format=%s, type=%s, data=%s, unpack=%s)", GLDebug.getTextureTargetName(target), level, GLDebug.getTextureFormatName(internalformat), - width, height, border, GLDebug.getTextureFormatName(format), GLDebug.getDataTypeName(type), dataStr, unpack); + width, height, border, GLDebug.getTextureFormatName(format), GLTypes.name(type), dataStr, unpack); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexSubImage2DCmd.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexSubImage2DCmd.java index bc32e93e5..2b824ff58 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexSubImage2DCmd.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/commands/TexSubImage2DCmd.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.recording.commands; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -78,6 +79,6 @@ public record TexSubImage2DCmd( String dataStr = pixels != null ? (pixels.remaining() + " bytes") : "null"; return String.format("TexSubImage2D(target=%s, level=%d, offset=(%d,%d), %dx%d, format=%s, type=%s, data=%s, unpack=%s)", GLDebug.getTextureTargetName(target), level, xoffset, yoffset, width, height, - GLDebug.getTextureFormatName(format), GLDebug.getDataTypeName(type), dataStr, unpack); + GLDebug.getTextureFormatName(format), GLTypes.name(type), dataStr, unpack); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java index 0654e1b9d..c651e17ba 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirector.java @@ -2,8 +2,11 @@ package com.gtnewhorizons.angelica.glsm.redirect; import com.google.common.collect.ImmutableSet; import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser; +import com.gtnewhorizons.angelica.config.SystemProperties; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; @@ -21,6 +24,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; /** * Core GL call redirector for GLSM. Rewrites bytecode so that GL calls go through {@code GLStateManager} for state tracking and backend abstraction. @@ -30,12 +34,107 @@ import java.util.Set; */ public class GLSMRedirector { - private static final boolean ASSERT_MAIN_THREAD = Boolean.getBoolean("angelica.assertMainThread"); - private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam"); + private static final boolean LOG_SPAM = SystemProperties.REDIRECTOR_LOGSPAM; private static final Logger LOGGER = LogManager.getLogger("GLSMRedirector"); + private static final String LWJGL_GL_PACKAGE = "org/lwjgl/opengl/"; + + private static final Set DEBUG_OWNERS = ImmutableSet.of( + "org/lwjgl/opengl/ARBDebugOutput", + "org/lwjgl/opengl/AMDDebugOutput" + ); + + private static final Set DEBUG_METHODS = ImmutableSet.of( + "glDebugMessageCallback", + "glDebugMessageControl", + "glDebugMessageInsert", + "glGetDebugMessageLog", + "glObjectLabel", + "glGetObjectLabel", + "glObjectPtrLabel", + "glGetObjectPtrLabel", + "glPushDebugGroup", + "glPopDebugGroup" + ); + + private static final Set UNMAPPED_SEEN = ConcurrentHashMap.newKeySet(); + private static final Set DEBUG_SEEN = ConcurrentHashMap.newKeySet(); + + private static boolean detectionEnabled() { + return SystemProperties.UNMAPPED_GL.detects(); + } + + private static final String GLSYNC_TYPE = "Lorg/lwjgl/opengl/GLSync;"; + + private static boolean isDebugCall(String owner, String name) { + if (!owner.startsWith(LWJGL_GL_PACKAGE)) return false; + return DEBUG_OWNERS.contains(owner) || DEBUG_METHODS.contains(name); + } + + private static boolean isUnmappedGlCall(String owner, String name, String desc) { + if (!owner.startsWith(LWJGL_GL_PACKAGE)) return false; + if (!name.startsWith("gl") && !name.startsWith("ngl")) return false; + if (desc.contains(GLSYNC_TYPE)) return false; + return true; + } + + private static boolean hasLwjglTypedDescriptor(String desc) { + return desc.contains("Lorg/lwjgl/"); + } + + private static final Set AWARE_NON_DISPATCHING = ImmutableSet.of( + "org/lwjgl/opengl/GL getCapabilities", + "org/lwjgl/opengl/GL setCapabilities", + "org/lwjgl/opengl/GL getFunctionProvider", + "org/lwjgl/opengl/GL create", + "org/lwjgl/opengl/GLCapabilities getAddressBuffer", + "org/lwjgl/opengl/GLCapabilities initialize", + "org/lwjgl/opengl/GLDebugMessageCallback create", + "org/lwjgl/opengl/GLDebugMessageCallback createSafe", + "org/lwjgl/opengl/GLDebugMessageCallback getMessage" + ); + + private static boolean isAwareNonDispatching(String owner, String name) { + return AWARE_NON_DISPATCHING.contains(owner + " " + name); + } + + private static void reportAwareUnroutable(String className, String owner, String name, String desc) { + if (!detectionEnabled()) return; + if (UNMAPPED_SEEN.add("aware " + owner + "." + name + desc)) { + LOGGER.warn("Aware-unroutable GL call {}.{}{} in {}; needs an awareOwnerRedirects entry (see AwareGLDebugShim)", owner, name, desc, className); + } + if (SystemProperties.UNMAPPED_GL.failsAwareUnroutable()) { + throw new IllegalStateException("Aware-unroutable GL call " + owner + "." + name + desc + " in " + className); + } + } + + private static void reportUnmapped(String className, String owner, String name, String desc) { + if (!detectionEnabled()) return; + if (UNMAPPED_SEEN.add(owner + "." + name + desc)) { + LOGGER.warn("Unmapped GL call {}.{}{} in {} reached the redirector; on a non-GL backend this will crash at runtime.", owner, name, desc, className); + } + if (SystemProperties.UNMAPPED_GL.failsUnmapped()) { + throw new IllegalStateException("Unmapped GL call " + owner + "." + name + desc + " in " + className); + } + } + + private static void reportDebugPassthrough(String className, String owner, String name, String desc) { + if (!detectionEnabled()) return; + if (DEBUG_SEEN.add(owner + "." + name + desc)) { + LOGGER.info("Debug-output call {}.{}{} in {} bypasses the backend (reaches real GL; unsupported on the SDL backend).", owner, name, desc, className); + } + } + private static final String Drawable = "org/lwjgl/opengl/Drawable"; + private static final String SharedDrawable = "org/lwjgl/opengl/SharedDrawable"; + private static final String Display = "org/lwjgl/opengl/Display"; + + private static boolean isDrawableOwner(String owner) { + return owner.startsWith(Drawable) || owner.equals(SharedDrawable); + } private static final String GLStateManager = "com/gtnewhorizons/angelica/glsm/GLStateManager"; + private static final String AwareGLDebugShim = "com/gtnewhorizons/angelica/sdlgpu/compat/AwareGLDebugShim"; + private static final Map awareOwnerRedirects = new HashMap<>(); private static final String GL_PREFIX = "org/lwjgl/opengl/GL"; private static final String ARBVertexArrayObject = "org/lwjgl/opengl/ARBVertexArrayObject"; private static final String APPLEVertexArrayObject = "org/lwjgl/opengl/APPLEVertexArrayObject"; @@ -53,19 +152,23 @@ public class GLSMRedirector { private static final String ARBBufferStorage = "org/lwjgl/opengl/ARBBufferStorage"; private static final String ARBCopyBuffer = "org/lwjgl/opengl/ARBCopyBuffer"; private static final String ARBMapBufferRange = "org/lwjgl/opengl/ARBMapBufferRange"; + private static final String ARBFramebufferObject = "org/lwjgl/opengl/ARBFramebufferObject"; + private static final String EXTFramebufferObject = "org/lwjgl/opengl/EXTFramebufferObject"; + private static final String ARBVertexShader = "org/lwjgl/opengl/ARBVertexShader"; + private static final String ARBOcclusionQuery = "org/lwjgl/opengl/ARBOcclusionQuery"; + private static final String ARBDrawElementsBaseVertex = "org/lwjgl/opengl/ARBDrawElementsBaseVertex"; + private static final String ARBMultiDrawIndirect = "org/lwjgl/opengl/ARBMultiDrawIndirect"; + private static final String ARBUniformBufferObject = "org/lwjgl/opengl/ARBUniformBufferObject"; + private static final String EXTGpuShader4 = "org/lwjgl/opengl/EXTGpuShader4"; + private static final String EXTGPUShader4 = "org/lwjgl/opengl/EXTGPUShader4"; + private static final String ARBTimerQuery = "org/lwjgl/opengl/ARBTimerQuery"; // Redirect VAO related calls from NHLib private static final String UniversalVAO = "com/gtnewhorizon/gtnhlib/client/opengl/UniversalVAO"; - private static final String MinecraftClient = "net.minecraft.client"; - private static final String SplashProgress = "cpw.mods.fml.client.SplashProgress"; - private static final Set ExcludedMinecraftMainThreadChecks = ImmutableSet.of( - "startGame", "func_71384_a", - "initializeTextures", "func_77474_a" - ); - private static final Map> methodRedirects = new HashMap<>(32); private static final Map glMethodRedirects = new HashMap<>(256); + private static final Map glDescRedirects = new HashMap<>(); private static final Map glCapRedirects = new HashMap<>(); private static final Map typeRedirects = new HashMap<>(); private static final ClassConstantPoolParser cstPoolParser; @@ -78,15 +181,15 @@ public class GLSMRedirector { }; static { - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_ALPHA_TEST, "AlphaTest"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_BLEND, "Blend"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_DEPTH_TEST, "DepthTest"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_CULL_FACE, "Cull"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_LIGHTING, "Lighting"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_TEXTURE_2D, "Texture"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_FOG, "Fog"); - glCapRedirects.put(org.lwjgl.opengl.GL12.GL_RESCALE_NORMAL, "RescaleNormal"); - glCapRedirects.put(org.lwjgl.opengl.GL11.GL_SCISSOR_TEST, "ScissorTest"); + glCapRedirects.put(GL11.GL_ALPHA_TEST, "AlphaTest"); + glCapRedirects.put(GL11.GL_BLEND, "Blend"); + glCapRedirects.put(GL11.GL_DEPTH_TEST, "DepthTest"); + glCapRedirects.put(GL11.GL_CULL_FACE, "Cull"); + glCapRedirects.put(GL11.GL_LIGHTING, "Lighting"); + glCapRedirects.put(GL11.GL_TEXTURE_2D, "Texture"); + glCapRedirects.put(GL11.GL_FOG, "Fog"); + glCapRedirects.put(GL12.GL_RESCALE_NORMAL, "RescaleNormal"); + glCapRedirects.put(GL11.GL_SCISSOR_TEST, "ScissorTest"); final var gl11 = RedirectMap.newMap() // glEnable/Disable - Special cased in GLSMRedirector, but included here for the external API @@ -117,6 +220,7 @@ public class GLSMRedirector { .add("glGenLists") .add("glGenTextures") .add("glIsList") + .add("glIsTexture") .add("glDeleteTextures") .add("glDepthFunc") .add("glDepthMask") @@ -135,6 +239,11 @@ public class GLSMRedirector { .add("glGetFloat") .add("glGetFloatv", "glGetFloat") .add("glGetInteger") + .add("glGetIntegerv", "glGetInteger") + .add("glGetIntegeri") + .add("glGetIntegeri_v") + .add("glGetBooleani") + .add("glGetBooleani_v") .add("glGetLight") .add("glGetMaterial") .add("glGetTexLevelParameteri") @@ -155,6 +264,7 @@ public class GLSMRedirector { .add("glListBase") .add("glLoadIdentity") .add("glLoadMatrix") + .add("glLoadMatrixf", "glLoadMatrix") .add("glLogicOp") .add("glMatrixMode") .add("glMultMatrix") @@ -236,6 +346,7 @@ public class GLSMRedirector { .add("glPolygonStipple") .add("glAccum") .add("glReadBuffer") + .add("glReadPixels") .add("glSampleCoverage") .add("glScissor") .add("glStencilFunc") @@ -273,7 +384,8 @@ public class GLSMRedirector { final var gl12 = RedirectMap.newMap() .add("glTexImage3D") .add("glTexSubImage3D") - .add("glCopyTexSubImage3D"); + .add("glCopyTexSubImage3D") + .add("glDrawRangeElements"); final var gl13 = RedirectMap.newMap() .add("glActiveTexture") .add("glSampleCoverage") @@ -284,7 +396,10 @@ public class GLSMRedirector { final var gl14 = RedirectMap.newMap() .add("glBlendFuncSeparate", "tryBlendFuncSeparate") .add("glBlendColor") - .add("glBlendEquation"); + .add("glBlendEquation") + .add("glMultiDrawArrays") + .add("glPointParameterf") + .add("glPointParameteri"); final var gl15 = RedirectMap.newMap() .add("glGenBuffers") .add("glBindBuffer") @@ -300,7 +415,14 @@ public class GLSMRedirector { .add("glGetBufferParameteri") .add("glGetBufferParameter") .add("glGetBufferParameteriv") - .add("glIsBuffer"); + .add("glIsBuffer") + .add("glIsQuery") + .add("glGenQueries") + .add("glDeleteQueries") + .add("glBeginQuery") + .add("glEndQuery") + .add("glGetQueryObjectui") + .add("glGetQueryObjecti"); final var gl20 = RedirectMap.newMap() .add("glBlendEquationSeparate") .add("glDrawBuffers") @@ -320,6 +442,8 @@ public class GLSMRedirector { .add("glValidateProgram") .add("glGetUniformLocation") .add("glGetAttribLocation") + .add("glIsShader") + .add("glIsProgram") .add("glUniform1f") .add("glUniform2f") .add("glUniform3f") @@ -332,9 +456,13 @@ public class GLSMRedirector { .add("glUniform2") .add("glUniform3") .add("glUniform4") + .add("glUniform1fv", "glUniform1") + .add("glUniform3fv", "glUniform3") + .add("glUniform4fv", "glUniform4") .add("glUniformMatrix2") .add("glUniformMatrix3") .add("glUniformMatrix4") + .add("glUniformMatrix3fv", "glUniformMatrix3") .add("glUniformMatrix4fv", "glUniformMatrix4") .add("glDeleteShader") .add("glGetShaderi") @@ -352,12 +480,14 @@ public class GLSMRedirector { .add("glGetUniform") .add("glVertexAttribPointer") .add("glEnableVertexAttribArray") - .add("glDisableVertexAttribArray"); + .add("glDisableVertexAttribArray") + .add("glGetActiveAttrib"); final var gl30 = RedirectMap.newMap() .add("glGenVertexArrays") .add("glBindVertexArray") .add("glDeleteVertexArrays") .add("glIsVertexArray") + .add("glBindFragDataLocation") .add("glBindFramebuffer") .add("glDeleteFramebuffers") .add("glGenFramebuffers") @@ -368,20 +498,37 @@ public class GLSMRedirector { .add("glGetFramebufferAttachmentParameteri") .add("glBlitFramebuffer") .add("glMapBufferRange") - .add("glFlushMappedBufferRange"); + .add("glFlushMappedBufferRange") + .add("glGenRenderbuffers") + .add("glDeleteRenderbuffers") + .add("glBindRenderbuffer") + .add("glRenderbufferStorage") + .add("glRenderbufferStorageMultisample") + .add("glFramebufferRenderbuffer") + .add("glIsFramebuffer") + .add("glIsRenderbuffer") + .add("glBindBufferBase"); final var gl31 = RedirectMap.newMap() .add("glDrawElementsInstanced") .add("glDrawArraysInstanced") - .add("glCopyBufferSubData"); + .add("glCopyBufferSubData") + .add("glPrimitiveRestartIndex") + .add("glGetUniformBlockIndex") + .add("glUniformBlockBinding"); final var gl32 = RedirectMap.newMap() - .add("glFramebufferTexture"); + .add("glFramebufferTexture") + .add("glDrawRangeElementsBaseVertex") + .add("glDrawElementsBaseVertex"); final var gl33 = RedirectMap.newMap() .add("glGenSamplers") .add("glDeleteSamplers") + .add("glIsSampler") .add("glBindSampler") .add("glSamplerParameteri") .add("glSamplerParameterf") - .add("glVertexAttribDivisor"); + .add("glVertexAttribDivisor") + .add("glQueryCounter") + .add("glGetQueryObjectui64"); final var gl42 = RedirectMap.newMap() .add("glBindImageTexture") .add("glMemoryBarrier") @@ -389,10 +536,12 @@ public class GLSMRedirector { final var gl43 = RedirectMap.newMap() .add("glDispatchCompute") .add("glClearBufferSubData") + .add("glClearBufferData") .add("glBindVertexBuffer") .add("glVertexAttribFormat") .add("glVertexAttribIFormat") - .add("glVertexAttribBinding"); + .add("glVertexAttribBinding") + .add("glMultiDrawElementsIndirect"); final var gl44 = RedirectMap.newMap() .add("glBufferStorage") .add("glClearTexImage"); @@ -400,8 +549,12 @@ public class GLSMRedirector { .add("glCreateBuffers") .add("glNamedBufferData") .add("glNamedBufferSubData"); + final var gl46 = RedirectMap.newMap() + .add("glPolygonOffsetClamp") + .add("glMultiDrawArraysIndirectCount") + .add("glMultiDrawElementsIndirectCount") + .add("glSpecializeShader"); - // Merge all GL version maps into the flat lookup glMethodRedirects.putAll(gl11); glMethodRedirects.putAll(gl12); glMethodRedirects.putAll(gl13); @@ -416,6 +569,7 @@ public class GLSMRedirector { glMethodRedirects.putAll(gl43); glMethodRedirects.putAll(gl44); glMethodRedirects.putAll(gl45); + glMethodRedirects.putAll(gl46); // MINECRAFT methodRedirects.put(OpenGlHelper, RedirectMap.newMap() @@ -435,10 +589,73 @@ public class GLSMRedirector { // ARB methodRedirects.put(ARBMultiTexture, RedirectMap.newMap() .add("glActiveTextureARB") + .add("glClientActiveTextureARB", "glClientActiveTexture") + .add("glMultiTexCoord2fARB", "glMultiTexCoord2f") ); + methodRedirects.put(ARBVertexShader, RedirectMap.newMap() + .add("glGetAttribLocationARB", "glGetAttribLocation") + ); + methodRedirects.put(ARBFramebufferObject, RedirectMap.newMap() + .add("glBindFramebuffer") + .add("glDeleteFramebuffers") + .add("glGenFramebuffers") + .add("glCheckFramebufferStatus") + .add("glFramebufferTexture2D") + .add("glBindRenderbuffer") + .add("glDeleteRenderbuffers") + .add("glGenRenderbuffers") + .add("glRenderbufferStorage") + .add("glFramebufferRenderbuffer") + ); + methodRedirects.put(EXTFramebufferObject, RedirectMap.newMap() + .add("glBindFramebufferEXT", "glBindFramebuffer") + .add("glDeleteFramebuffersEXT", "glDeleteFramebuffers") + .add("glGenFramebuffersEXT", "glGenFramebuffers") + .add("glCheckFramebufferStatusEXT", "glCheckFramebufferStatus") + .add("glFramebufferTexture2DEXT", "glFramebufferTexture2D") + .add("glBindRenderbufferEXT", "glBindRenderbuffer") + .add("glDeleteRenderbuffersEXT", "glDeleteRenderbuffers") + .add("glGenRenderbuffersEXT", "glGenRenderbuffers") + .add("glRenderbufferStorageEXT", "glRenderbufferStorage") + .add("glFramebufferRenderbufferEXT", "glFramebufferRenderbuffer") + ); + methodRedirects.put(ARBOcclusionQuery, RedirectMap.newMap() + .add("glGenQueriesARB", "glGenQueries") + .add("glBeginQueryARB", "glBeginQuery") + .add("glEndQueryARB", "glEndQuery") + .add("glGetQueryObjectuARB", "glGetQueryObjectui") + ); + methodRedirects.put(ARBTimerQuery, RedirectMap.newMap() + .add("glQueryCounter") + .add("glGetQueryObjectui64") + ); + + glDescRedirects.put("org/lwjgl/opengl/GL32C glFenceSync(II)J", "glFenceSync"); + glDescRedirects.put("org/lwjgl/opengl/GL32C glClientWaitSync(JIJ)I", "glClientWaitSync"); + glDescRedirects.put("org/lwjgl/opengl/GL32C glWaitSync(JIJ)V", "glWaitSync"); + glDescRedirects.put("org/lwjgl/opengl/GL32C glGetSynci(JILjava/nio/IntBuffer;)I", "glGetSynci"); + glDescRedirects.put("org/lwjgl/opengl/GL32C glDeleteSync(J)V", "glDeleteSync"); + glDescRedirects.put("org/lwjgl/opengl/GL15C nglMapBuffer(II)J", "nglMapBuffer"); + glDescRedirects.put("org/lwjgl/opengl/GL32C nglMultiDrawElementsBaseVertex(IJIJIJ)V", "nglMultiDrawElementsBaseVertex"); + + for (String o : new String[]{"org/lwjgl/opengl/KHRDebug", "org/lwjgl/opengl/GL43", "org/lwjgl/opengl/GL43C"}) { + glDescRedirects.put(o + " glObjectLabel(IILjava/lang/CharSequence;)V", "glObjectLabel"); + glDescRedirects.put(o + " glGetObjectLabel(III)Ljava/lang/String;", "glGetObjectLabel"); + glDescRedirects.put(o + " glPushDebugGroup(IILjava/lang/CharSequence;)V", "glPushDebugGroup"); + glDescRedirects.put(o + " glPopDebugGroup()V", "glPopDebugGroup"); + glDescRedirects.put(o + " glDebugMessageInsert(IIIILjava/lang/CharSequence;)V", "glDebugMessageInsert"); + glDescRedirects.put(o + " glDebugMessageControl(IIILjava/nio/IntBuffer;Z)V", "glDebugMessageControl"); + glDescRedirects.put(o + " glGetDebugMessageLog(ILjava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/ByteBuffer;)I", "glGetDebugMessageLog"); + glDescRedirects.put(o + " glDebugMessageCallback(Lorg/lwjgl/opengl/KHRDebugCallback;)V", "glDebugMessageCallback"); + awareOwnerRedirects.put(o + " glDebugMessageCallback(Lorg/lwjgl/opengl/GLDebugMessageCallbackI;J)V", AwareGLDebugShim); + } + + awareOwnerRedirects.put("org/lwjgl/opengl/GLUtil setupDebugMessageCallback()Lorg/lwjgl/system/Callback;", AwareGLDebugShim); + awareOwnerRedirects.put("org/lwjgl/opengl/GLUtil setupDebugMessageCallback(Ljava/io/PrintStream;)Lorg/lwjgl/system/Callback;", AwareGLDebugShim); methodRedirects.put(ARBShaderObjects, RedirectMap.newMap() .add("glUseProgramObjectARB", "glUseProgram") .add("glShaderSourceARB", "glShaderSource") + .add("nglShaderSourceARB", "nglShaderSource") .add("glLinkProgramARB", "glLinkProgram") .add("glCreateShaderObjectARB", "glCreateShader") .add("glCompileShaderARB", "glCompileShader") @@ -476,7 +693,23 @@ public class GLSMRedirector { methodRedirects.put(ARBVertexArrayObject, RedirectMap.newMap() .add("glBindVertexArray") .add("glDeleteVertexArrays") + .add("glGenVertexArrays") ); + methodRedirects.put(ARBDrawElementsBaseVertex, RedirectMap.newMap() + .add("glDrawElementsBaseVertex") + ); + methodRedirects.put(ARBMultiDrawIndirect, RedirectMap.newMap() + .add("glMultiDrawElementsIndirect") + ); + final var uniformBufferObject = RedirectMap.newMap() + .add("glBindBufferBase") + .add("glGetUniformBlockIndex") + .add("glUniformBlockBinding"); + methodRedirects.put(ARBUniformBufferObject, uniformBufferObject); + final var gpuShader4 = RedirectMap.newMap() + .add("glVertexAttribIPointerEXT", "glVertexAttribIPointer"); + methodRedirects.put(EXTGpuShader4, gpuShader4); + methodRedirects.put(EXTGPUShader4, gpuShader4); methodRedirects.put(ARBInstancedArrays, RedirectMap.newMap() .add("glVertexAttribDivisorARB") ); @@ -517,6 +750,8 @@ public class GLSMRedirector { // APPLE methodRedirects.put(APPLEVertexArrayObject, RedirectMap.newMap() .add("glBindVertexArrayAPPLE", "glBindVertexArray") + .add("glGenVertexArraysAPPLE", "glGenVertexArrays") + .add("glDeleteVertexArraysAPPLE", "glDeleteVertexArrays") ); // GTNHLib VAO @@ -530,12 +765,15 @@ public class GLSMRedirector { .add("gluPerspective") .add("gluLookAt") .add("gluPickMatrix") + .add("gluUnProject") ); methodRedirects.put(GLU, RedirectMap.newMap() .add("gluPerspective") .add("gluLookAt") .add("gluOrtho2D") .add("gluPickMatrix") + .add("gluBuild2DMipmaps") + .add("gluErrorString") ); // Quadric type replacements @@ -544,33 +782,30 @@ public class GLSMRedirector { typeRedirects.put("org/lwjgl/util/glu/Disk", "com/gtnewhorizons/angelica/glsm/compat/lwjgl/AngelicaDisk"); typeRedirects.put("org/lwjgl/util/glu/PartialDisk", "com/gtnewhorizons/angelica/glsm/compat/lwjgl/AngelicaPartialDisk"); - // Build constant pool scanner final List stringsToSearch = new ArrayList<>(32); - stringsToSearch.add(GL_PREFIX); + stringsToSearch.add(LWJGL_GL_PACKAGE); + stringsToSearch.add(Drawable); + stringsToSearch.add(SharedDrawable); + stringsToSearch.add(Display); stringsToSearch.addAll(typeRedirects.keySet()); - for (String key : methodRedirects.keySet()) { - stringsToSearch.add(key); - } + stringsToSearch.addAll(methodRedirects.keySet()); cstPoolParser = new ClassConstantPoolParser(stringsToSearch.toArray(new String[0])); } - /** Core exclusions that GLSM always requires. */ public String[] getCoreExclusions() { return CORE_EXCLUSIONS.clone(); } - /** The internal-name prefix used to match GL version classes (e.g., {@code "org/lwjgl/opengl/GL"}). */ public static String getGLPrefix() { return GL_PREFIX; } - /** The internal name of the redirect target class. */ public static String getTargetClassName() { return GLStateManager; } - /** Method redirects for GL-prefix classes. Key: original method name, Value: GLStateManager method name. */ + /** Key: original method name, value: GLStateManager method name. */ public static Map getGLPrefixMethodRedirects() { return Collections.unmodifiableMap(glMethodRedirects); } - /** Method redirects for named (non-GL-prefix) classes. Key: internal class name, Value: per-method redirect map. */ + /** Key: internal class name, value: per-method redirect map. */ public static Map> getNamedClassMethodRedirects() { return Collections.unmodifiableMap(methodRedirects); } @@ -579,8 +814,11 @@ public class GLSMRedirector { return cstPoolParser.find(basicClass, true); } - /** @return Was the class changed? */ public boolean transformClassNode(String transformedName, ClassNode cn) { + return transformClassNode(transformedName, cn, false); + } + + public boolean transformClassNode(String transformedName, ClassNode cn, boolean lwjgl3Aware) { boolean changed = false; final boolean isOpenGlHelper = transformedName.equals("net.minecraft.client.renderer.OpenGlHelper"); @@ -588,10 +826,8 @@ public class GLSMRedirector { if (isOpenGlHelper && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) { continue; } - boolean redirectInMethod = false; for (AbstractInsnNode node : mn.instructions.toArray()) { if (node instanceof TypeInsnNode tNode) { - // Redirect NEW and CHECKCAST for quadric classes if (tNode.getOpcode() == Opcodes.NEW || tNode.getOpcode() == Opcodes.CHECKCAST) { final String redirect = typeRedirects.get(tNode.desc); if (redirect != null) { @@ -633,8 +869,7 @@ public class GLSMRedirector { mn.instructions.remove(prevNode); } changed = true; - redirectInMethod = true; - } else if (mNode.name.equals("makeCurrent") && mNode.owner.startsWith(Drawable)) { + } else if (mNode.name.equals("makeCurrent") && isDrawableOwner(mNode.owner)) { mNode.setOpcode(Opcodes.INVOKESTATIC); mNode.owner = GLStateManager; mNode.desc = "(L" + Drawable + ";)V"; @@ -643,10 +878,48 @@ public class GLSMRedirector { if (LOG_SPAM) { LOGGER.info("Redirecting call in {} to GLStateManager.makeCurrent()", transformedName); } + } else if (mNode.name.equals("releaseContext") && isDrawableOwner(mNode.owner)) { + mNode.setOpcode(Opcodes.INVOKESTATIC); + mNode.owner = GLStateManager; + mNode.desc = "(L" + Drawable + ";)V"; + mNode.itf = false; + changed = true; + if (LOG_SPAM) { + LOGGER.info("Redirecting call in {} to GLStateManager.releaseContext()", transformedName); + } + } else if (mNode.name.equals("swapBuffers") && mNode.owner.equals(Display) && mNode.desc.equals("()V")) { + mNode.owner = GLStateManager; + changed = true; + if (LOG_SPAM) { + LOGGER.info("Redirecting call in {} to GLStateManager.swapBuffers()", transformedName); + } + } else if (mNode.name.equals("update") && mNode.owner.equals(Display) && (mNode.desc.equals("()V") || mNode.desc.equals("(Z)V"))) { + mNode.owner = GLStateManager; + mNode.name = "updateDisplay"; + changed = true; + if (LOG_SPAM) { + LOGGER.info("Redirecting call in {} to GLStateManager.updateDisplay{}", transformedName, mNode.desc); + } + } else if (mNode.name.equals("isCurrent") && mNode.owner.equals(Display) && mNode.desc.equals("()Z")) { + mNode.owner = GLStateManager; + changed = true; + if (LOG_SPAM) { + LOGGER.info("Redirecting call in {} to GLStateManager.isCurrent()", transformedName); + } } else { - final Map redirects = mNode.owner.startsWith(GL_PREFIX) ? glMethodRedirects : methodRedirects.get(mNode.owner); - final String glsmName = redirects != null ? redirects.get(mNode.name) : null; - if (glsmName != null) { + String glsmName = glDescRedirects.get(mNode.owner + " " + mNode.name + mNode.desc); + if (glsmName == null) { + final Map redirects = mNode.owner.startsWith(GL_PREFIX) ? glMethodRedirects : methodRedirects.get(mNode.owner); + glsmName = redirects != null ? redirects.get(mNode.name) : null; + } + final String awareOwner = lwjgl3Aware ? awareOwnerRedirects.get(mNode.owner + " " + mNode.name + mNode.desc) : null; + if (awareOwner != null) { + if (LOG_SPAM) { + LOGGER.info("Redirecting aware call in {} from {}.{}{} to {}.{}", transformedName, mNode.owner, mNode.name, mNode.desc, awareOwner, mNode.name); + } + mNode.owner = awareOwner; + changed = true; + } else if (glsmName != null) { if (LOG_SPAM) { final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1); LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, mNode.desc); @@ -654,10 +927,14 @@ public class GLSMRedirector { mNode.owner = GLStateManager; mNode.name = glsmName; changed = true; - redirectInMethod = true; + } else if (lwjgl3Aware && mNode.owner.startsWith(LWJGL_GL_PACKAGE) && hasLwjglTypedDescriptor(mNode.desc) && !isAwareNonDispatching(mNode.owner, mNode.name)) { + reportAwareUnroutable(transformedName, mNode.owner, mNode.name, mNode.desc); + } else if (isDebugCall(mNode.owner, mNode.name)) { + reportDebugPassthrough(transformedName, mNode.owner, mNode.name, mNode.desc); + } else if (isUnmappedGlCall(mNode.owner, mNode.name, mNode.desc)) { + reportUnmapped(transformedName, mNode.owner, mNode.name, mNode.desc); } } - // Redirect calls for quadric classes if (mNode.getOpcode() == Opcodes.INVOKESPECIAL && mNode.name.equals("")) { final String redirect = typeRedirects.get(mNode.owner); if (redirect != null) { @@ -672,22 +949,28 @@ public class GLSMRedirector { // Redirect method handles in invokedynamic bootstrap arguments for (int i = 0; i < dynNode.bsmArgs.length; i++) { if (!(dynNode.bsmArgs[i] instanceof Handle handle)) continue; - final Map redirects = handle.getOwner().startsWith(GL_PREFIX) ? glMethodRedirects : methodRedirects.get(handle.getOwner()); - final String glsmName = redirects != null ? redirects.get(handle.getName()) : null; - if (glsmName == null) continue; + String glsmName = glDescRedirects.get(handle.getOwner() + " " + handle.getName() + handle.getDesc()); + if (glsmName == null) { + final Map redirects = handle.getOwner().startsWith(GL_PREFIX) ? glMethodRedirects : methodRedirects.get(handle.getOwner()); + glsmName = redirects != null ? redirects.get(handle.getName()) : null; + } + if (glsmName == null) { + if (isDebugCall(handle.getOwner(), handle.getName())) { + reportDebugPassthrough(transformedName, handle.getOwner(), handle.getName(), handle.getDesc()); + } else if (isUnmappedGlCall(handle.getOwner(), handle.getName(), handle.getDesc())) { + reportUnmapped(transformedName, handle.getOwner(), handle.getName(), handle.getDesc()); + } + continue; + } if (LOG_SPAM) { final String shortOwner = handle.getOwner().substring(handle.getOwner().lastIndexOf("/") + 1); LOGGER.info("Redirecting invokedynamic handle in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, handle.getName(), handle.getDesc(), glsmName, handle.getDesc()); } dynNode.bsmArgs[i] = new Handle(handle.getTag(), GLStateManager, glsmName, handle.getDesc()); changed = true; - redirectInMethod = true; } } } - if (ASSERT_MAIN_THREAD && redirectInMethod && !transformedName.startsWith(SplashProgress) && !(transformedName.startsWith(MinecraftClient) && ExcludedMinecraftMainThreadChecks.contains(mn.name))) { - mn.instructions.insert(new MethodInsnNode(Opcodes.INVOKESTATIC, GLStateManager, "assertMainThread", "()V", false)); - } } return changed; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/GlslVulkanPreprocess.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/GlslVulkanPreprocess.java new file mode 100644 index 000000000..665a6b834 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/GlslVulkanPreprocess.java @@ -0,0 +1,306 @@ +package com.gtnewhorizons.angelica.glsm.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL20; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLPreParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public final class GlslVulkanPreprocess { + + private static final Logger LOGGER = LogManager.getLogger("GlslVulkanPreprocess"); + + public static final String SAMPLER_RENAMED = "angelica_sampler_renamed"; + + public static final String SAMPLERLESS_EXTENSION = "#extension GL_EXT_samplerless_texture_functions : require"; + + private static final int MAX_VS_INPUT_LOCATIONS = 16; + + private static final int CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap CACHE = new Object2ObjectLinkedOpenHashMap<>(); + + + private GlslVulkanPreprocess() {} + + private record CacheKey(String source, int glShaderType, boolean separateReadOnlyImages) {} + public record Result(String rewrittenSource, Set boolUniforms, Set explicitVsInputs) {} + + /** Replace {@code [startIdx, stopIdx]} with {@code replacement}. */ + public record Edit(int startIdx, int stopIdx, String replacement) {} + + public static int startIdx(ParserRuleContext ctx) { + return ctx.getStart().getStartIndex(); + } + public static int stopIdx(ParserRuleContext ctx) { + return ctx.getStop().getStopIndex(); + } + + /** Apply non-overlapping edits to the source in one pass. */ + public static String applyEdits(String src, List edits) { + if (edits.isEmpty()) return src; + final List sorted; + if (edits.size() == 1) { + sorted = edits; + } else { + sorted = new ArrayList<>(edits); + sorted.sort(Comparator.comparingInt(Edit::startIdx).thenComparingInt(Edit::stopIdx)); + } + final StringBuilder sb = new StringBuilder(src.length()); + int cursor = 0; + for (Edit e : sorted) { + if (e.startIdx < cursor) continue; + sb.append(src, cursor, e.startIdx); + sb.append(e.replacement); + cursor = e.stopIdx + 1; + } + sb.append(src, cursor, src.length()); + return sb.toString(); + } + + /** Returns {@code null} on parse failure — callers treat that the same as a shaderc compile failure. */ + public static @Nullable Result run(String source, int glShaderType, String debugName, boolean separateReadOnlyImages) { + final CacheKey key = new CacheKey(source, glShaderType, separateReadOnlyImages); + synchronized (CACHE) { + final Result hit = CACHE.getAndMoveToFirst(key); + if (hit != null) return hit; + } + + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(source); + } catch (Exception e) { + LOGGER.warn("glsl-transformation-lib parse failed for '{}': {}", debugName, e.getMessage()); + return null; + } + + final List edits = new ArrayList<>(); + final Metadata meta = collectEdits(source, root, glShaderType, debugName, separateReadOnlyImages, edits); + + final Result out = new Result(applyEdits(source, edits), meta.boolUniforms(), meta.explicitVsInputs()); + synchronized (CACHE) { + CACHE.putAndMoveToFirst(key, out); + while (CACHE.size() > CACHE_MAX) CACHE.removeLast(); + } + return out; + } + + public record Metadata(Set boolUniforms, Set explicitVsInputs) {} + + public static Metadata collectEdits(String source, GLSLParser.Translation_unitContext root, int glShaderType, String debugName, boolean separateReadOnlyImages, List edits) { + final boolean isVertex = glShaderType == GL20.GL_VERTEX_SHADER; + final Set bools = new HashSet<>(); + final Set explicitInputs = new HashSet<>(); + final Set readOnlyImages = new HashSet<>(); + final boolean[] needsSamplerless = { false }; + + final int[] maxExplicitLoc = { -1 }; + final List unlocatedVsInputStarts = new ArrayList<>(); + + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void enterInit_declarator_list(GLSLParser.Init_declarator_listContext ctx) { + final GLSLParser.Single_declarationContext single = ctx.single_declaration(); + if (single == null || single.fully_specified_type() == null) return; + + final GLSLParser.Fully_specified_typeContext fst = single.fully_specified_type(); + final GLSLParser.Type_qualifierContext tq = fst.type_qualifier(); + if (tq == null) return; + + boolean hasUniform = false, hasIn = false, hasLocation = false, hasReadonly = false; + int locValue = -1; + int bindingValue = -1; + for (GLSLParser.Single_type_qualifierContext stq : tq.single_type_qualifier()) { + if (stq.storage_qualifier() != null) { + final String s = stq.storage_qualifier().getText(); + if ("uniform".equals(s)) hasUniform = true; + else if ("in".equals(s)) hasIn = true; + else if ("readonly".equals(s)) hasReadonly = true; + } else if (stq.layout_qualifier() != null) { + for (GLSLParser.Layout_qualifier_idContext id : stq.layout_qualifier().layout_qualifier_id_list().layout_qualifier_id()) { + if (id.IDENTIFIER() == null) continue; + final String qualifier = id.IDENTIFIER().getText(); + if ("location".equals(qualifier)) { + hasLocation = true; + if (id.constant_expression() != null) { + try { locValue = Integer.parseInt(id.constant_expression().getText()); } catch (NumberFormatException ignored) {} + } + } else if ("binding".equals(qualifier) && id.constant_expression() != null) { + try { bindingValue = Integer.parseInt(id.constant_expression().getText()); } catch (NumberFormatException ignored) {} + } + } + } + } + + final boolean boolDecl = hasUniform && isBool(fst); + final boolean explicitInputDecl = isVertex && hasIn && hasLocation; + + if (single.typeless_declaration() != null) { + handleDeclarator(single.typeless_declaration(), hasUniform, boolDecl, explicitInputDecl, bools, explicitInputs, edits); + } + for (GLSLParser.Typeless_declarationContext td : ctx.typeless_declaration()) { + handleDeclarator(td, hasUniform, boolDecl, explicitInputDecl, bools, explicitInputs, edits); + } + + if (separateReadOnlyImages && hasUniform && fst.type_specifier() != null) { + final String typeText = fst.type_specifier().getText(); + if (separateTextureType(typeText) != null) { + needsSamplerless[0] = true; + } else if (hasReadonly) { + final String asTexture = separateTextureTypeForImage(typeText); + if (asTexture != null) { + needsSamplerless[0] = true; + collectDeclaredNames(single, ctx, readOnlyImages); + final String binding = bindingValue >= 0 ? "layout(binding = " + bindingValue + ") " : ""; + edits.add(new Edit(startIdx(fst), stopIdx(fst), binding + "uniform " + asTexture)); + } + } + } + + if (isVertex && hasIn) { + if (hasLocation && locValue >= 0) { + if (locValue > maxExplicitLoc[0]) maxExplicitLoc[0] = locValue; + } else if (!hasLocation) { + unlocatedVsInputStarts.add(ctx.getStart().getStartIndex()); + } + } + } + + @Override + public void enterPostfix_expression(GLSLParser.Postfix_expressionContext ctx) { + if (readOnlyImages.isEmpty() || ctx.LEFT_PAREN() == null || ctx.RIGHT_PAREN() == null) return; + final GLSLParser.Function_call_parametersContext params = ctx.function_call_parameters(); + if (params == null || params.assignment_expression() == null || params.assignment_expression().isEmpty()) return; + if (!readOnlyImages.contains(params.assignment_expression(0).getText())) return; + + final ParseTree callee = ctx.getChild(0); + if (!(callee instanceof ParserRuleContext calleeCtx)) return; + final String replacement = switch (calleeCtx.getText()) { + case "imageLoad" -> "texelFetch"; + case "imageSize" -> "textureSize"; + default -> null; + }; + if (replacement == null) return; + + edits.add(new Edit(startIdx(calleeCtx), stopIdx(calleeCtx), replacement)); + final int rparen = ctx.RIGHT_PAREN().getSymbol().getStartIndex(); + edits.add(new Edit(rparen, rparen - 1, ", 0")); + } + + @Override + public void visitTerminal(TerminalNode node) { + final Token tok = node.getSymbol(); + if (tok.getType() != GLSLLexer.IDENTIFIER) return; + final String text = tok.getText(); + switch (text) { + case "sampler" -> edits.add(new Edit(tok.getStartIndex(), tok.getStopIndex(), SAMPLER_RENAMED)); + case "gl_VertexID" -> edits.add(new Edit(tok.getStartIndex(), tok.getStopIndex(), "gl_VertexIndex")); + case "gl_InstanceID" -> edits.add(new Edit(tok.getStartIndex(), tok.getStopIndex(), "gl_InstanceIndex")); + default -> {} + } + } + }, root); + + if (needsSamplerless[0]) { + final int at = versionDirectiveEnd(source); + if (at >= 0) edits.add(new Edit(at, at - 1, "\n" + SAMPLERLESS_EXTENSION)); + } + + if (maxExplicitLoc[0] >= 0 && !unlocatedVsInputStarts.isEmpty()) { + int next = maxExplicitLoc[0] + 1; + int dropped = 0; + for (int start : unlocatedVsInputStarts) { + if (next >= MAX_VS_INPUT_LOCATIONS) { dropped++; continue; } + edits.add(new Edit(start, start - 1, "layout(location = " + next + ") ")); + next++; + } + if (dropped > 0) { + LOGGER.warn("'{}': dropped {} VS input location-conflict fixes (would exceed {} attribute slots)", debugName, dropped, MAX_VS_INPUT_LOCATIONS); + } + } + + return new Metadata(bools, explicitInputs); + } + + public static void clearCache() { + synchronized (CACHE) { CACHE.clear(); } + } + + private static void collectDeclaredNames(GLSLParser.Single_declarationContext single, GLSLParser.Init_declarator_listContext ctx, Set out) { + if (single.typeless_declaration() != null && single.typeless_declaration().IDENTIFIER() != null) { + out.add(single.typeless_declaration().IDENTIFIER().getText()); + } + for (GLSLParser.Typeless_declarationContext td : ctx.typeless_declaration()) { + if (td.IDENTIFIER() != null) out.add(td.IDENTIFIER().getText()); + } + } + + private static @Nullable String separateTextureTypeForImage(String typeText) { + final String dim = switch (typeText) { + case "image1D", "iimage1D", "uimage1D" -> "1D"; + case "image2D", "iimage2D", "uimage2D" -> "2D"; + case "image3D", "iimage3D", "uimage3D" -> "3D"; + default -> null; + }; + if (dim == null) return null; + return typeText.charAt(0) == 'i' ? "itexture" + dim : typeText.charAt(0) == 'u' ? "utexture" + dim : "texture" + dim; + } + + private static @Nullable String separateTextureType(String typeText) { + return switch (typeText) { + case "texture1D", "itexture1D", "utexture1D", + "texture2D", "itexture2D", "utexture2D", + "texture3D", "itexture3D", "utexture3D" -> typeText; + default -> null; + }; + } + + private static int versionDirectiveEnd(String source) { + final GLSLPreParser.Translation_unitContext pre; + try { + pre = GlslTransformUtils.parsePreQuiet(source); + } catch (Exception e) { + return -1; + } + final GLSLPreParser.Version_directiveContext ctx = firstVersionDirective(pre); + return ctx == null || ctx.getStop() == null ? -1 : ctx.getStop().getStopIndex() + 1; + } + + private static GLSLPreParser.@Nullable Version_directiveContext firstVersionDirective(ParseTree node) { + if (node instanceof GLSLPreParser.Version_directiveContext v) return v; + for (int i = 0; i < node.getChildCount(); i++) { + final GLSLPreParser.Version_directiveContext found = firstVersionDirective(node.getChild(i)); + if (found != null) return found; + } + return null; + } + + private static void handleDeclarator(GLSLParser.Typeless_declarationContext td, boolean hasUniform, boolean asBool, boolean asInput, Set bools, Set inputs, List edits) { + if (td.IDENTIFIER() == null) return; + final String name = td.IDENTIFIER().getText(); + if (asBool) bools.add(name); + if (asInput) inputs.add(name); + if (hasUniform && td.EQUAL() != null && td.initializer() != null) { + edits.add(new Edit(td.EQUAL().getSymbol().getStartIndex(), td.initializer().getStop().getStopIndex(), "")); + } + } + + private static boolean isBool(GLSLParser.Fully_specified_typeContext fst) { + return fst.type_specifier() != null && fst.type_specifier().type_specifier_nonarray() != null && "bool".equals(fst.type_specifier().type_specifier_nonarray().getText()); + } +} diff --git a/src/main/java/net/coderbot/iris/gl/shader/ShaderType.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/ShaderType.java similarity index 92% rename from src/main/java/net/coderbot/iris/gl/shader/ShaderType.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/ShaderType.java index 3342617a8..45e5b8148 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/ShaderType.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/ShaderType.java @@ -1,6 +1,6 @@ // This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license. -package net.coderbot.iris.gl.shader; +package com.gtnewhorizons.angelica.glsm.shader; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL32; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvCompiler.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvCompiler.java new file mode 100644 index 000000000..b0a95b0e1 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvCompiler.java @@ -0,0 +1,183 @@ +package com.gtnewhorizons.angelica.glsm.shader; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.lwjgl.system.MemoryUtil.memFree; +import static org.lwjgl.system.MemoryUtil.memUTF8; + +/** GLSL -> SPIR-V via shaderc */ +@Lwjgl3Aware +public final class SpirvCompiler { + private static final Logger LOGGER = LogManager.getLogger("SpirvCompiler"); + + private static final ThreadLocal COMPILER = ThreadLocal.withInitial(() -> { + final long c = Shaderc.shaderc_compiler_initialize(); + if (c == 0L) throw new IllegalStateException("shaderc_compiler_initialize failed"); + return c; + }); + + private static final Path FAILURE_DIR = Paths.get("shaderc_failures"); + private static final AtomicInteger FAILURE_COUNTER = new AtomicInteger(); + + private static final int CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap CACHE = new Object2ObjectLinkedOpenHashMap<>(); + + private record CacheKey(String source, int shaderKind, Options opts) {} + + private SpirvCompiler() {} + + public record Options(int targetEnv, int envVersion, boolean vulkanRulesRelaxed, boolean autoBindUniforms, boolean autoMapLocations, boolean autoCombinedImageSampler, int forcedVersion, int forcedProfile) { + + public static Options vulkanRelaxed() { + return new Options(Shaderc.shaderc_target_env_vulkan, Shaderc.shaderc_env_version_vulkan_1_0, true, true, true, true, 0, 0); + } + + public static Options vulkanForced460Core() { + return new Options(Shaderc.shaderc_target_env_vulkan, Shaderc.shaderc_env_version_vulkan_1_0, true, true, true, false, 460, Shaderc.shaderc_profile_core); + } + } + + public record Result(@Nullable ByteBuffer spirv, @Nullable String error, @Nullable Path dumpPath) {} + + public static Result compile(String source, int shaderKind, String debugName, Options opts) { + final String cleanSrc = source.indexOf('\0') >= 0 ? source.replace("\0", "") : source; + + final CacheKey key = new CacheKey(cleanSrc, shaderKind, opts); + final byte[] cached; + synchronized (CACHE) { + cached = CACHE.getAndMoveToFirst(key); + } + if (cached != null) { + final ByteBuffer copy = MemoryUtil.memAlloc(cached.length); + copy.put(cached).flip(); + return new Result(copy, null, null); + } + + final long compiler = COMPILER.get(); + final long optionsHandle = Shaderc.shaderc_compile_options_initialize(); + if (optionsHandle == 0L) { + return new Result(null, "shaderc_compile_options_initialize failed", null); + } + try { + configureOptions(optionsHandle, opts); + + ByteBuffer srcBuf = null, nameBuf = null, entryBuf = null; + long result = 0L; + try { + srcBuf = memUTF8(cleanSrc, false); + nameBuf = memUTF8(debugName == null ? "shader" : debugName); + entryBuf = memUTF8("main"); + result = Shaderc.shaderc_compile_into_spv(compiler, srcBuf, shaderKind, nameBuf, entryBuf, optionsHandle); + if (result == 0L) { + return new Result(null, "shaderc_compile_into_spv returned null", null); + } + final int status = Shaderc.shaderc_result_get_compilation_status(result); + if (status != Shaderc.shaderc_compilation_status_success) { + final String msg = Shaderc.shaderc_result_get_error_message(result); + final Path dumpPath = writeFailureDump(debugName, shaderKind, msg, cleanSrc); + return new Result(null, msg == null ? "(no error message)" : msg, dumpPath); + } + final ByteBuffer spirv = Shaderc.shaderc_result_get_bytes(result); + if (spirv == null || spirv.remaining() == 0) { + return new Result(null, "shaderc returned empty SPIR-V", null); + } + + final ByteBuffer copy = MemoryUtil.memAlloc(spirv.remaining()); + copy.put(spirv); + copy.flip(); + final byte[] heap = new byte[copy.remaining()]; + copy.duplicate().get(heap); + synchronized (CACHE) { + CACHE.putAndMoveToFirst(key, heap); + while (CACHE.size() > CACHE_MAX) CACHE.removeLast(); + } + return new Result(copy, null, null); + } finally { + if (result != 0L) Shaderc.shaderc_result_release(result); + if (entryBuf != null) memFree(entryBuf); + if (nameBuf != null) memFree(nameBuf); + if (srcBuf != null) memFree(srcBuf); + } + } finally { + Shaderc.shaderc_compile_options_release(optionsHandle); + } + } + + public static String preprocess(String source, int shaderKind, String debugName, Options opts) { + final String cleanSrc = source.indexOf('\0') >= 0 ? source.replace("\0", "") : source; + final long compiler = COMPILER.get(); + final long optionsHandle = Shaderc.shaderc_compile_options_initialize(); + if (optionsHandle == 0L) return null; + try { + configureOptions(optionsHandle, opts); + ByteBuffer srcBuf = null, nameBuf = null, entryBuf = null; + long result = 0L; + try { + srcBuf = memUTF8(cleanSrc, false); + nameBuf = memUTF8(debugName == null ? "shader" : debugName); + entryBuf = memUTF8("main"); + result = Shaderc.shaderc_compile_into_preprocessed_text(compiler, srcBuf, shaderKind, nameBuf, entryBuf, optionsHandle); + if (result == 0L) return null; + if (Shaderc.shaderc_result_get_compilation_status(result) != Shaderc.shaderc_compilation_status_success) { + return null; + } + final ByteBuffer text = Shaderc.shaderc_result_get_bytes(result); + if (text == null || text.remaining() == 0) return null; + return MemoryUtil.memUTF8(text); + } finally { + if (result != 0L) Shaderc.shaderc_result_release(result); + if (entryBuf != null) memFree(entryBuf); + if (nameBuf != null) memFree(nameBuf); + if (srcBuf != null) memFree(srcBuf); + } + } finally { + Shaderc.shaderc_compile_options_release(optionsHandle); + } + } + + private static void configureOptions(long h, Options o) { + Shaderc.shaderc_compile_options_set_target_env(h, o.targetEnv(), o.envVersion()); + Shaderc.shaderc_compile_options_set_source_language(h, Shaderc.shaderc_source_language_glsl); + if (o.vulkanRulesRelaxed()) Shaderc.shaderc_compile_options_set_vulkan_rules_relaxed(h, true); + if (o.autoBindUniforms()) Shaderc.shaderc_compile_options_set_auto_bind_uniforms(h, true); + if (o.autoMapLocations()) Shaderc.shaderc_compile_options_set_auto_map_locations(h, true); + if (o.autoCombinedImageSampler()) Shaderc.shaderc_compile_options_set_auto_combined_image_sampler(h, true); + if (o.forcedVersion() != 0) { + Shaderc.shaderc_compile_options_set_forced_version_profile(h, o.forcedVersion(), o.forcedProfile()); + } + } + + public static void clearCache() { + synchronized (CACHE) { CACHE.clear(); } + } + + private static @Nullable Path writeFailureDump(String debugName, int shaderKind, String msg, String source) { + try { + Files.createDirectories(FAILURE_DIR); + final int n = FAILURE_COUNTER.getAndIncrement(); + final Path p = FAILURE_DIR.resolve(String.format("%03d_%s_kind0x%s.glsl", n, debugName == null ? "shader" : debugName, Integer.toHexString(shaderKind))); + final StringBuilder sb = new StringBuilder(); + sb.append("// shaderc errors:\n"); + if (msg != null) for (String line : msg.split("\\R")) sb.append("// ").append(line).append('\n'); + sb.append('\n').append(source); + Files.writeString(p, sb.toString()); + return p; + } catch (IOException e) { + LOGGER.warn("Failed to write shaderc failure dump for '{}': {}", debugName, e.getMessage()); + return null; + } + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslator.java new file mode 100644 index 000000000..8225c9b38 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslator.java @@ -0,0 +1,420 @@ +package com.gtnewhorizons.angelica.glsm.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.startIdx; +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.stopIdx; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.memFree; + +/** GLSL 330 core -> SPIR-V -> GLSL ES 320 via shaderc + SPIRV-Cross */ +@Lwjgl3Aware +public final class SpirvShaderTranslator { + + private static final Logger LOGGER = LogManager.getLogger("SpirvShaderTranslator"); + + private static final int SPV_DECORATION_LOCATION = 30; + private static final int SPV_DECORATION_BINDING = 33; + + private SpirvShaderTranslator() {} + + public static @Nullable String glslToGlslEs(String source, int glShaderType, String debugName) { + return glslToGlslEsImpl(source, glShaderType, debugName, false); + } + + static @Nullable String glslToGlslEsRawForTest(String source, int glShaderType, String debugName) { + return glslToGlslEsImpl(source, glShaderType, debugName, true); + } + + private static @Nullable String glslToGlslEsImpl(String source, int glShaderType, String debugName, boolean rawOutput) { + final int shaderKind = shaderKindForGlType(glShaderType); + if (shaderKind < 0) { + LOGGER.warn("Unknown GL shader type 0x{} for '{}' - skipping SPIR-V translation", Integer.toHexString(glShaderType), debugName); + return null; + } + + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, debugName, false); + if (pre == null) return null; + + final SpirvCompiler.Result cr = SpirvCompiler.compile(pre.rewrittenSource(), shaderKind, debugName, SpirvCompiler.Options.vulkanRelaxed()); + if (cr.spirv() == null) { + final String firstErr = cr.error() == null ? "(no error)" : cr.error().split("\\R", 2)[0]; + LOGGER.error("shaderc failed for '{}' (kind=0x{}): {} (dumped to {})", + debugName, Integer.toHexString(shaderKind), firstErr, cr.dumpPath() == null ? "" : cr.dumpPath()); + return null; + } + try { + final String emitted = emitGlslEs(cr.spirv(), debugName, glShaderType, pre.explicitVsInputs()); + if (emitted == null) return null; + return rawOutput ? emitted : postProcessEsOutput(emitted, pre.boolUniforms()); + } finally { + memFree(cr.spirv()); + } + } + + private static @Nullable String postProcessEsOutput(String glslEs, Set boolUniformNames) { + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(glslEs); + } catch (Exception e) { + LOGGER.error("Failed to parse spvc ES output for post-processing: {}", e.getMessage()); + return null; + } + + final DefaultBlockInfo block = findDefaultBlock(root); + final List edits = new ArrayList<>(); + + if (block != null) { + edits.add(new Edit(startIdx(block.structExternalDecl), stopIdx(block.structExternalDecl), buildLooseUniforms(block.members, boolUniformNames))); + edits.add(new Edit(startIdx(block.uniformExternalDecl), stopIdx(block.uniformExternalDecl), "")); + } + + final UseSiteRewriter rewriter = new UseSiteRewriter(block, boolUniformNames, edits); + ParseTreeWalker.DEFAULT.walk(rewriter, root); + + return GlslVulkanPreprocess.applyEdits(glslEs, edits); + } + + private record DefaultBlockInfo(ParserRuleContext structExternalDecl, ParserRuleContext uniformExternalDecl, String blockVarName, List members) {} + + private record MemberInfo(String typePrefix, String name) {} + + private static String buildLooseUniforms(List members, Set boolNames) { + final StringBuilder sb = new StringBuilder(); + for (MemberInfo m : members) { + if (boolNames.contains(m.name)) { + sb.append("uniform bool ").append(m.name).append(";\n"); + } else { + sb.append("uniform ").append(m.typePrefix).append(' ').append(m.name).append(";\n"); + } + } + if (!sb.isEmpty() && sb.charAt(sb.length() - 1) == '\n') sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } + + private static @Nullable DefaultBlockInfo findDefaultBlock(GLSLParser.Translation_unitContext root) { + final DefaultBlockFinder finder = new DefaultBlockFinder(); + ParseTreeWalker.DEFAULT.walk(finder, root); + if (finder.structExternalDecl == null || finder.uniformExternalDecl == null) return null; + return new DefaultBlockInfo(finder.structExternalDecl, finder.uniformExternalDecl, finder.blockVarName, finder.members); + } + + private static final class DefaultBlockFinder extends GLSLParserBaseListener { + String structName; + ParserRuleContext structExternalDecl; + ParserRuleContext uniformExternalDecl; + String blockVarName; + final List members = new ArrayList<>(); + + @Override + public void enterStruct_specifier(GLSLParser.Struct_specifierContext ctx) { + if (structExternalDecl != null) return; + final TerminalNode id = ctx.IDENTIFIER(); + if (id == null) return; + final String idText = id.getText(); + if (!idText.startsWith("_RESERVED_IDENTIFIER_FIXUP_") || !idText.endsWith("DefaultUniformBlock")) return; + + structName = idText; + structExternalDecl = findExternalDeclaration(ctx); + + for (GLSLParser.Struct_declarationContext sd : ctx.struct_declaration_list().struct_declaration()) { + final StringBuilder typePrefix = new StringBuilder(); + if (sd.type_qualifier() != null) typePrefix.append(textWithSpaces(sd.type_qualifier())).append(' '); + typePrefix.append(textWithSpaces(sd.type_specifier())); + + for (GLSLParser.Struct_declaratorContext decl : sd.struct_declarator_list().struct_declarator()) { + final String arraySuffix = decl.array_specifier() == null ? "" : decl.array_specifier().getText(); + members.add(new MemberInfo(typePrefix + arraySuffix, decl.IDENTIFIER().getText())); + } + } + } + + @Override + public void enterInit_declarator_list(GLSLParser.Init_declarator_listContext ctx) { + if (structName == null || uniformExternalDecl != null) return; + final GLSLParser.Single_declarationContext single = ctx.single_declaration(); + if (single == null || single.typeless_declaration() == null) return; + final GLSLParser.Fully_specified_typeContext fst = single.fully_specified_type(); + if (fst == null || fst.type_qualifier() == null) return; + + boolean isUniform = false; + for (GLSLParser.Single_type_qualifierContext stq : fst.type_qualifier().single_type_qualifier()) { + if (stq.storage_qualifier() != null && "uniform".equals(stq.storage_qualifier().getText())) { + isUniform = true; + break; + } + } + if (!isUniform) return; + + if (fst.type_specifier() == null || fst.type_specifier().type_specifier_nonarray() == null) return; + final GLSLParser.Type_specifier_nonarrayContext ts = fst.type_specifier().type_specifier_nonarray(); + if (ts.type_name() == null) return; + if (!structName.equals(ts.type_name().getText())) return; + + blockVarName = single.typeless_declaration().IDENTIFIER().getText(); + uniformExternalDecl = findExternalDeclaration(ctx); + } + + private static String textWithSpaces(ParseTree tree) { + final StringBuilder sb = new StringBuilder(); + appendTextWithSpaces(tree, sb); + return sb.toString().trim(); + } + + private static void appendTextWithSpaces(ParseTree tree, StringBuilder sb) { + if (tree instanceof TerminalNode) { + if (!sb.isEmpty() && sb.charAt(sb.length() - 1) != ' ') sb.append(' '); + sb.append(tree.getText()); + return; + } + for (int i = 0; i < tree.getChildCount(); i++) { + appendTextWithSpaces(tree.getChild(i), sb); + } + } + } + + private static ParserRuleContext findExternalDeclaration(ParserRuleContext ctx) { + ParseTree cur = ctx; + while (cur != null && !(cur instanceof GLSLParser.External_declarationContext)) { + cur = cur.getParent(); + } + return (ParserRuleContext) cur; + } + + private static final class UseSiteRewriter extends GLSLParserBaseListener { + private final @Nullable DefaultBlockInfo block; + private final Set boolNames; + private final List edits; + private final Set memberNames; + + UseSiteRewriter(@Nullable DefaultBlockInfo block, Set boolNames, List edits) { + this.block = block; + this.boolNames = boolNames; + this.edits = edits; + this.memberNames = new HashSet<>(); + if (block != null) for (MemberInfo m : block.members) memberNames.add(m.name); + } + + @Override + public void enterBinary_expression(GLSLParser.Binary_expressionContext ctx) { + if (ctx.getChildCount() != 3) return; + final ParseTree opNode = ctx.getChild(1); + if (!(opNode instanceof TerminalNode op)) return; + final String opText = op.getText(); + final boolean isNe = "!=".equals(opText); + final boolean isEq = "==".equals(opText); + if (!isNe && !isEq) return; + + final ParseTree rhs = ctx.getChild(2); + if (!"0u".equals(rhs.getText())) return; + + final ParseTree lhs = ctx.getChild(0); + final String nameIfBool = resolveBoolOperand(lhs); + if (nameIfBool == null) return; + + final String replacement = isNe ? nameIfBool : "!" + nameIfBool; + edits.add(new Edit(startIdx(ctx), stopIdx(ctx), replacement)); + } + + @Override + public void enterPostfix_expression(GLSLParser.Postfix_expressionContext ctx) { + if (ctx.type_specifier() != null && ctx.LEFT_PAREN() != null + && "bool".equals(ctx.type_specifier().getText()) + && ctx.function_call_parameters() != null + && ctx.function_call_parameters().assignment_expression() != null + && ctx.function_call_parameters().assignment_expression().size() == 1) { + final String nameIfBool = resolveBoolOperand(ctx.function_call_parameters().assignment_expression(0)); + if (nameIfBool != null) { + edits.add(new Edit(startIdx(ctx), stopIdx(ctx), nameIfBool)); + return; + } + } + + if (block != null && ctx.getChildCount() == 3 && ctx.DOT() != null && ctx.field_selection() != null) { + final ParseTree inner = ctx.getChild(0); + if (inner.getText().equals(block.blockVarName)) { + final String member = ctx.field_selection().getText(); + if (memberNames.contains(member) && !coveredByAncestorBoolCompare(ctx)) { + edits.add(new Edit(startIdx(ctx), stopIdx(ctx), member)); + } + } + } + } + + private @Nullable String resolveBoolOperand(ParseTree operand) { + final String text = operand.getText(); + if (boolNames.contains(text)) return text; + if (block != null && text.startsWith(block.blockVarName + ".")) { + final String member = text.substring(block.blockVarName.length() + 1); + if (boolNames.contains(member) && memberNames.contains(member)) return member; + } + return null; + } + + private boolean coveredByAncestorBoolCompare(GLSLParser.Postfix_expressionContext ctx) { + final int start = startIdx(ctx), stop = stopIdx(ctx); + for (Edit e : edits) { + if (e.startIdx() <= start && stop <= e.stopIdx() && e.stopIdx() > stop) return true; + } + return false; + } + } + + private static @Nullable String emitGlslEs(ByteBuffer spirv, String debugName, int glShaderType, Set explicitVsInputs) { + try (MemoryStack stack = stackPush()) { + final PointerBuffer pContext = stack.pointers(0); + if (Spvc.spvc_context_create(pContext) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_context_create failed for '{}'", debugName); + return null; + } + final long ctx = pContext.get(0); + try { + final IntBuffer spirvWords = spirv.asIntBuffer(); + final PointerBuffer pIr = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, spirvWords, spirvWords.remaining(), pIr) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_context_parse_spirv failed for '{}': {}", debugName, lastSpvcError(ctx)); + return null; + } + final PointerBuffer pCompiler = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pIr.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_context_create_compiler(GLSL) failed for '{}': {}", debugName, lastSpvcError(ctx)); + return null; + } + final long compiler = pCompiler.get(0); + + final PointerBuffer pOptions = stack.pointers(0); + if (Spvc.spvc_compiler_create_compiler_options(compiler, pOptions) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_compiler_create_compiler_options failed for '{}': {}", debugName, lastSpvcError(ctx)); + return null; + } + final long options = pOptions.get(0); + Spvc.spvc_compiler_options_set_uint(options, Spvc.SPVC_COMPILER_OPTION_GLSL_VERSION, 320); + Spvc.spvc_compiler_options_set_bool(options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES, true); + Spvc.spvc_compiler_options_set_bool(options, Spvc.SPVC_COMPILER_OPTION_GLSL_EMIT_UNIFORM_BUFFER_AS_PLAIN_UNIFORMS, true); + if (Spvc.spvc_compiler_install_compiler_options(compiler, options) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_compiler_install_compiler_options failed for '{}': {}", debugName, lastSpvcError(ctx)); + return null; + } + + applyResourceDecorationFixups(ctx, compiler, glShaderType, explicitVsInputs, debugName); + + final PointerBuffer pSource = stack.pointers(0); + if (Spvc.spvc_compiler_compile(compiler, pSource) != Spvc.SPVC_SUCCESS) { + LOGGER.error("spvc_compiler_compile failed for '{}': {}", debugName, lastSpvcError(ctx)); + return null; + } + final long sourcePtr = pSource.get(0); + if (sourcePtr == 0L) { + LOGGER.error("spvc_compiler_compile returned NULL source for '{}'", debugName); + return null; + } + + return MemoryUtil.memUTF8(sourcePtr); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + } + + private static void applyResourceDecorationFixups(long ctx, long compiler, int glShaderType, Set explicitVsInputs, String debugName) { + if (glShaderType == GL20.GL_VERTEX_SHADER) { + unsetDecorationForResourceType(ctx, compiler, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, SPV_DECORATION_LOCATION, null, debugName); + unsetDecorationForResourceType(ctx, compiler, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, SPV_DECORATION_LOCATION, explicitVsInputs, debugName); + } else if (glShaderType == GL20.GL_FRAGMENT_SHADER) { + unsetDecorationForResourceType(ctx, compiler, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, SPV_DECORATION_LOCATION, null, debugName); + } else if (glShaderType == GL32.GL_GEOMETRY_SHADER || glShaderType == GL40.GL_TESS_CONTROL_SHADER || glShaderType == GL40.GL_TESS_EVALUATION_SHADER) { + unsetDecorationForResourceType(ctx, compiler, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, SPV_DECORATION_LOCATION, null, debugName); + unsetDecorationForResourceType(ctx, compiler, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, SPV_DECORATION_LOCATION, null, debugName); + } + + if (glShaderType != GL43.GL_COMPUTE_SHADER) { + for (int resourceType : BINDING_STRIP_RESOURCE_TYPES) { + unsetDecorationForResourceType(ctx, compiler, resourceType, SPV_DECORATION_BINDING, null, debugName); + } + } + } + + private static final int[] BINDING_STRIP_RESOURCE_TYPES = { + Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, + Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, + Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, + Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, + Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, + }; + + private static void unsetDecorationForResourceType(long ctx, long compiler, int resourceType, int decoration, Set preserve, String debugName) { + try (MemoryStack stack = stackPush()) { + final PointerBuffer pResources = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(compiler, pResources) != Spvc.SPVC_SUCCESS) { + LOGGER.warn("spvc_compiler_create_shader_resources failed for '{}': {}", debugName, lastSpvcError(ctx)); + return; + } + final long resources = pResources.get(0); + + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) { + LOGGER.warn("spvc_resources_get_resource_list_for_type failed for '{}': {}", debugName, lastSpvcError(ctx)); + return; + } + final long listAddr = pList.get(0); + final long count = pCount.get(0); + if (listAddr == 0L || count <= 0L) return; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(listAddr, (int) count); + for (int i = 0; i < list.remaining(); i++) { + final SpvcReflectedResource res = list.get(i); + if (preserve != null) { + final String name = res.nameString(); + if (name != null && preserve.contains(name)) continue; + } + Spvc.spvc_compiler_unset_decoration(compiler, res.id(), decoration); + } + } + } + + private static String lastSpvcError(long ctx) { + final String msg = Spvc.spvc_context_get_last_error_string(ctx); + return msg == null || msg.isEmpty() ? "(no error message)" : msg; + } + + private static int shaderKindForGlType(int glShaderType) { + return switch (glShaderType) { + case GL20.GL_VERTEX_SHADER -> Shaderc.shaderc_vertex_shader; + case GL20.GL_FRAGMENT_SHADER -> Shaderc.shaderc_fragment_shader; + case GL32.GL_GEOMETRY_SHADER -> Shaderc.shaderc_geometry_shader; + case GL40.GL_TESS_CONTROL_SHADER -> Shaderc.shaderc_tess_control_shader; + case GL40.GL_TESS_EVALUATION_SHADER -> Shaderc.shaderc_tess_evaluation_shader; + case GL43.GL_COMPUTE_SHADER -> Shaderc.shaderc_compute_shader; + default -> -1; + }; + } +} diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformType.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/UniformType.java similarity index 69% rename from src/main/java/net/coderbot/iris/gl/uniform/UniformType.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/UniformType.java index 03cbd383d..f0bd06a59 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/UniformType.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/shader/UniformType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package com.gtnewhorizons.angelica.glsm.shader; public enum UniformType { INT, diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BlendStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BlendStateStack.java index 2f1e6e116..eae884850 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BlendStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BlendStateStack.java @@ -38,4 +38,8 @@ public class BlendStateStack extends BlendState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Color4Stack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Color4Stack.java index 2a92e7a13..0015bdb96 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Color4Stack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Color4Stack.java @@ -43,4 +43,8 @@ public class Color4Stack extends Color4 implements IStateStack { public boolean isEmpty() { return pointer == 0; } + + public boolean topChanged() { + return pointer > 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ColorMaskStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ColorMaskStack.java index 16455e632..38f077524 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ColorMaskStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ColorMaskStack.java @@ -38,4 +38,8 @@ public class ColorMaskStack extends ColorMask implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/DepthStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/DepthStateStack.java index 5c3e77ad3..550f20e48 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/DepthStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/DepthStateStack.java @@ -38,4 +38,8 @@ public class DepthStateStack extends DepthState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/IntegerStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/IntegerStateStack.java index 241c7f2da..29f7570a4 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/IntegerStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/IntegerStateStack.java @@ -45,4 +45,8 @@ public class IntegerStateStack extends IntegerState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/LineStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/LineStateStack.java index 1fb9cbeff..96a61acf2 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/LineStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/LineStateStack.java @@ -39,4 +39,8 @@ public class LineStateStack extends LineState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PointStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PointStateStack.java index 1672eca39..be090946f 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PointStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PointStateStack.java @@ -39,4 +39,8 @@ public class PointStateStack extends PointState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PolygonStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PolygonStateStack.java index 54fe37236..2eabddae6 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PolygonStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/PolygonStateStack.java @@ -39,4 +39,8 @@ public class PolygonStateStack extends PolygonState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/StencilStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/StencilStateStack.java index 3e72464a1..38cbcdc35 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/StencilStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/StencilStateStack.java @@ -39,4 +39,8 @@ public class StencilStateStack extends StencilState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureBindingStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureBindingStack.java index 7d027e8f6..be546439a 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureBindingStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureBindingStack.java @@ -42,4 +42,8 @@ public class TextureBindingStack extends TextureBinding implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java index aa7128986..db95630c1 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import org.lwjgl.opengl.GL13; /** @@ -37,10 +38,16 @@ public class TextureUnitBooleanStateStack extends BooleanStateStack { } private void setEnabledWithUnitSwitch(boolean enabled) { - final boolean bypass = GLStateManager.shouldBypassCache(); + final boolean bypass = !GLStateManager.isCachingEnabled(); if (bypass || enabled != this.enabled) { if (!bypass) this.enabled = enabled; + if (GLSMHooks.TEXTURE_UNIT_STATE.hasListeners()) { + GLSMHooks.textureUnitStateEvent.unit = unitIndex; + GLSMHooks.textureUnitStateEvent.enabled = enabled; + GLSMHooks.TEXTURE_UNIT_STATE.post(GLSMHooks.textureUnitStateEvent); + } + if (!ffpStateOnly) { final int currentUnit = GLStateManager.getActiveTextureUnit(); final boolean needsSwitch = currentUnit != unitIndex; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ViewPortStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ViewPortStateStack.java index 7eba221b5..7ecfa2e6b 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ViewPortStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/ViewPortStateStack.java @@ -38,4 +38,8 @@ public class ViewPortStateStack extends ViewportState implements IStateStack 0 && !sameAs(stack[pointer - 1]); + } } diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaTestFunction.java similarity index 97% rename from src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaTestFunction.java index e06eb3aa8..4c2b9e639 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaTestFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.blending; +package com.gtnewhorizons.angelica.glsm.states; import org.lwjgl.opengl.GL11; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java index 972ef3734..5c8da8f40 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java @@ -22,6 +22,15 @@ public class BooleanState implements ISettableState { this.ffpStateOnly = ffpStateOnly; } + public void applyToBackend() { + if (ffpStateOnly) return; + if (enabled) { + RENDER_BACKEND.enable(glCap); + } else { + RENDER_BACKEND.disable(glCap); + } + } + public void setUnknownState() { stateUnknown = true; } @@ -35,12 +44,10 @@ public class BooleanState implements ISettableState { } public void setEnabled(boolean enabled) { - final boolean bypass = GLStateManager.shouldBypassCache(); + final boolean bypass = !GLStateManager.isCachingEnabled(); if (stateUnknown || bypass || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.vendorIsAMD() && GLStateManager.isPoppingAttributes())) { stateUnknown = false; - if (!bypass) { - this.enabled = enabled; - } + this.enabled = enabled; if (!ffpStateOnly) { if (enabled) { RENDER_BACKEND.enable(this.glCap); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitArray.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitArray.java new file mode 100644 index 000000000..d5937e0c9 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitArray.java @@ -0,0 +1,33 @@ +package com.gtnewhorizons.angelica.glsm.states; + +import com.gtnewhorizons.angelica.glsm.RenderSystem; + +public class ImageUnitArray { + + private static final int MIN_UNITS = 8; + + private volatile ImageUnitBinding[] bindings; + + public ImageUnitBinding get(int unit) { + if (unit < 0) return null; + ImageUnitBinding[] local = bindings; + if (local == null) local = allocate(); + return unit < local.length ? local[unit] : null; + } + + public int size() { + final ImageUnitBinding[] local = bindings; + return local == null ? 0 : local.length; + } + + private synchronized ImageUnitBinding[] allocate() { + ImageUnitBinding[] local = bindings; + if (local == null) { + final int count = Math.max(MIN_UNITS, RenderSystem.getMaxImageUnits()); + local = new ImageUnitBinding[count]; + for (int i = 0; i < count; i++) local[i] = new ImageUnitBinding(); + bindings = local; + } + return local; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitBinding.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitBinding.java new file mode 100644 index 000000000..daa3cdd1a --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ImageUnitBinding.java @@ -0,0 +1,44 @@ +package com.gtnewhorizons.angelica.glsm.states; + +import lombok.Getter; + +public class ImageUnitBinding implements ISettableState { + @Getter protected int texture; + @Getter protected int level; + @Getter protected boolean layered; + @Getter protected int layer; + @Getter protected int access; + @Getter protected int format; + + public void setBinding(int texture, int level, boolean layered, int layer, int access, int format) { + this.texture = texture; + this.level = level; + this.layered = layered; + this.layer = layer; + this.access = access; + this.format = format; + } + + @Override + public ImageUnitBinding set(ImageUnitBinding state) { + this.texture = state.texture; + this.level = state.level; + this.layered = state.layered; + this.layer = state.layer; + this.access = state.access; + this.format = state.format; + return this; + } + + @Override + public boolean sameAs(Object state) { + if (this == state) return true; + if (!(state instanceof ImageUnitBinding other)) return false; + return texture == other.texture && level == other.level && layered == other.layered && layer == other.layer && access == other.access && format == other.format; + } + + @Override + public ImageUnitBinding copy() { + return new ImageUnitBinding().set(this); + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java index 3dae9c79d..7c5e6d739 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java @@ -29,7 +29,7 @@ public class LightModelState implements ISettableState { public boolean setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -39,7 +39,7 @@ public class LightModelState implements ISettableState { public boolean setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -47,7 +47,7 @@ public class LightModelState implements ISettableState { } public boolean setColorControl(int val) { - if (GLStateManager.shouldBypassCache() || this.colorControl != val) { + if (!GLStateManager.isCachingEnabled() || this.colorControl != val) { this.colorControl = val; return true; } @@ -59,7 +59,7 @@ public class LightModelState implements ISettableState { } public boolean setLocalViewer(float val) { - if (GLStateManager.shouldBypassCache() || Float.compare(this.localViewer, val) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(this.localViewer, val) != 0) { this.localViewer = val; return true; } @@ -79,7 +79,7 @@ public class LightModelState implements ISettableState { } public boolean setTwoSide(float val) { - if (GLStateManager.shouldBypassCache() || Float.compare(this.twoSide, val) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(this.twoSide, val) != 0) { this.twoSide = val; return true; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java index 37a3fd4b5..191aa380e 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java @@ -74,18 +74,18 @@ public class LightState implements ISettableState { this.rawPosition = new Vector4f(position); this.position = position; this.position.mul(GLStateManager.getModelViewMatrix()); - this.posMvGeneration = GLStateManager.mvGeneration; + this.posMvGeneration = GLStateManager.getMvGeneration(); this.rawSpotDirection = new Vector3f(spotDirection); this.spotDirection = spotDirection; GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.mul(matrix3f); - this.spotDirLinearGeneration = GLStateManager.mvLinearGeneration; + this.spotDirLinearGeneration = GLStateManager.getMvLinearGeneration(); } public boolean setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -95,7 +95,7 @@ public class LightState implements ISettableState { public boolean setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -104,7 +104,7 @@ public class LightState implements ISettableState { public boolean setDiffuse(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); return true; } @@ -114,7 +114,7 @@ public class LightState implements ISettableState { public boolean setDiffuse(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); return true; } @@ -123,7 +123,7 @@ public class LightState implements ISettableState { public boolean setSpecular(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); return true; } @@ -133,7 +133,7 @@ public class LightState implements ISettableState { public boolean setSpecular(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); return true; } @@ -152,8 +152,8 @@ public class LightState implements ISettableState { } private boolean applyPosition(Vector4f raw) { - final int mvGen = GLStateManager.mvGeneration; - if (GLStateManager.shouldBypassCache() || this.posMvGeneration != mvGen || !this.rawPosition.equals(raw)) { + final int mvGen = GLStateManager.getMvGeneration(); + if (!GLStateManager.isCachingEnabled() || this.posMvGeneration != mvGen || !this.rawPosition.equals(raw)) { this.rawPosition.set(raw); this.posMvGeneration = mvGen; this.position.set(raw); @@ -175,8 +175,8 @@ public class LightState implements ISettableState { } private boolean applySpotDirection(Vector3f raw) { - final int mvLinearGen = GLStateManager.mvLinearGeneration; - if (GLStateManager.shouldBypassCache() || this.spotDirLinearGeneration != mvLinearGen || !this.rawSpotDirection.equals(raw)) { + final int mvLinearGen = GLStateManager.getMvLinearGeneration(); + if (!GLStateManager.isCachingEnabled() || this.spotDirLinearGeneration != mvLinearGen || !this.rawSpotDirection.equals(raw)) { this.rawSpotDirection.set(raw); this.spotDirLinearGeneration = mvLinearGen; GLStateManager.getModelViewMatrix().get3x3(matrix3f); @@ -200,7 +200,7 @@ public class LightState implements ISettableState { } public boolean setSpotExponent(float f) { - if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotExponent) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(f, this.spotExponent) != 0) { this.spotExponent = f; return true; } @@ -220,7 +220,7 @@ public class LightState implements ISettableState { } public boolean setSpotCutoff(float f) { - if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotCutoff) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(f, this.spotCutoff) != 0) { this.spotCutoff = f; this.spotCosCutoff = (float) Math.cos(Math.toRadians(f)); return true; @@ -241,7 +241,7 @@ public class LightState implements ISettableState { } public boolean setConstantAttenuation(float f) { - if (GLStateManager.shouldBypassCache() || Float.compare(f, this.constantAttenuation) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(f, this.constantAttenuation) != 0) { this.constantAttenuation = f; return true; } @@ -261,7 +261,7 @@ public class LightState implements ISettableState { } public boolean setLinearAttenuation(float f) { - if (GLStateManager.shouldBypassCache() || Float.compare(f, this.linearAttenuation) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(f, this.linearAttenuation) != 0) { this.linearAttenuation = f; return true; } @@ -281,7 +281,7 @@ public class LightState implements ISettableState { } public boolean setQuadraticAttenuation(float f) { - if (GLStateManager.shouldBypassCache() || Float.compare(f, this.quadraticAttenuation) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(f, this.quadraticAttenuation) != 0) { this.quadraticAttenuation = f; return true; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java index 71edc532d..c031354bc 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java @@ -39,7 +39,7 @@ public class MaterialState implements ISettableState { public boolean setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -49,7 +49,7 @@ public class MaterialState implements ISettableState { public boolean setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); return true; } @@ -58,7 +58,7 @@ public class MaterialState implements ISettableState { public boolean setDiffuse(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); return true; } @@ -68,7 +68,7 @@ public class MaterialState implements ISettableState { public boolean setDiffuse(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); return true; } @@ -77,7 +77,7 @@ public class MaterialState implements ISettableState { public boolean setSpecular(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); return true; } @@ -87,7 +87,7 @@ public class MaterialState implements ISettableState { public boolean setSpecular(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); return true; } @@ -96,7 +96,7 @@ public class MaterialState implements ISettableState { public boolean setEmission(FloatBuffer newBuffer) { vector4f.set(newBuffer); - if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); return true; } @@ -106,7 +106,7 @@ public class MaterialState implements ISettableState { public boolean setEmission(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); - if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { + if (!GLStateManager.isCachingEnabled() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); return true; } @@ -114,7 +114,7 @@ public class MaterialState implements ISettableState { } public boolean setShininess(float val) { - if (GLStateManager.shouldBypassCache() || Float.compare(this.shininess, val) != 0) { + if (!GLStateManager.isCachingEnabled() || Float.compare(this.shininess, val) != 0) { this.shininess = val; return true; } @@ -141,7 +141,7 @@ public class MaterialState implements ISettableState { vector3f.set(newBuffer); } - if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { + if (!GLStateManager.isCachingEnabled() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); return true; } @@ -151,7 +151,7 @@ public class MaterialState implements ISettableState { public boolean setColorIndexes(IntBuffer newBuffer) { vector3i.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1)); vector3f.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z); - if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { + if (!GLStateManager.isCachingEnabled() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); return true; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java index 5713881ef..16c422548 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java @@ -14,12 +14,7 @@ public class MatrixMode implements ISettableState { return; } - final boolean bypass = GLStateManager.shouldBypassCache(); - if (bypass || this.mode != mode) { - if (!bypass) { - this.mode = mode; - } - } + this.mode = mode; } public int getMatrix() { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/PolygonState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/PolygonState.java index aea5c56e6..0f2727c20 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/PolygonState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/PolygonState.java @@ -14,6 +14,7 @@ public class PolygonState implements ISettableState { private int backMode = GL11.GL_FILL; private float offsetFactor = 0.0f; private float offsetUnits = 0.0f; + private float offsetClamp = 0.0f; private int cullFaceMode = GL11.GL_BACK; private int frontFace = GL11.GL_CCW; @@ -23,6 +24,7 @@ public class PolygonState implements ISettableState { this.backMode = state.backMode; this.offsetFactor = state.offsetFactor; this.offsetUnits = state.offsetUnits; + this.offsetClamp = state.offsetClamp; this.cullFaceMode = state.cullFaceMode; this.frontFace = state.frontFace; return this; @@ -36,6 +38,7 @@ public class PolygonState implements ISettableState { && backMode == polygonState.backMode && Float.compare(offsetFactor, polygonState.offsetFactor) == 0 && Float.compare(offsetUnits, polygonState.offsetUnits) == 0 + && Float.compare(offsetClamp, polygonState.offsetClamp) == 0 && cullFaceMode == polygonState.cullFaceMode && frontFace == polygonState.frontFace; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureBinding.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureBinding.java index 1d17eddd1..f42ee0671 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureBinding.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/TextureBinding.java @@ -1,15 +1,38 @@ package com.gtnewhorizons.angelica.glsm.states; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import lombok.Getter; -import lombok.Setter; -@Getter public class TextureBinding implements ISettableState { - @Setter protected int binding; + @Getter protected int binding; + @Getter protected int target; + protected TextureInfo info; + + public void setBinding(int binding) { + setBinding(binding, 0); + } + + public void setBinding(int binding, int target) { + this.binding = binding; + this.target = target; + this.info = null; + } + + public TextureInfo getOrResolveInfo() { + TextureInfo resolved = info; + if (resolved == null) { + resolved = TextureInfoCache.INSTANCE.getInfo(binding); + info = resolved; + } + return resolved; + } @Override public TextureBinding set(TextureBinding state) { this.binding = state.binding; + this.target = state.target; + this.info = null; return this; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java index 977e2b8f9..400abd05d 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java @@ -29,6 +29,13 @@ public class ViewportState implements ISettableState { params.put(3, height); } + public void get(int[] params) { + params[0] = x; + params[1] = y; + params[2] = width; + params[3] = height; + } + @Override public ViewportState set(ViewportState state) { this.x = state.x; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/GlStreamingRing.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/GlStreamingRing.java new file mode 100644 index 000000000..8ed7d95b9 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/GlStreamingRing.java @@ -0,0 +1,172 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL44; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; + +/** + * Persistent-mapped fence-reclaimed ring over any buffer target. Callers reserve a range and + * memCopy into address() + offset themselves. + */ +final class GlStreamingRing { + + private final int target; + private final int capacity; + private final ByteBuffer mappedBuffer; + private final long mappedAddress; + private int bufferId; + + private static final long SYNC_WAIT_SLICE_NANOS = 10_000_000L; + private static final long SYNC_WAIT_TOTAL_NANOS = 5_000_000_000L; + + private final ObjectArrayFIFOQueue fenceQueue = new ObjectArrayFIFOQueue<>(); + private int writePos; + private int remaining; + private int pendingBytes; + private int wraps; + private int fencesIssued; + private int forcedReclaims; + + private GlStreamingRing(int target, int capacity, int bufferId, ByteBuffer mappedBuffer) { + this.target = target; + this.capacity = capacity; + this.bufferId = bufferId; + this.mappedBuffer = mappedBuffer; + this.mappedAddress = memAddress0(mappedBuffer); + this.remaining = capacity; + } + + static GlStreamingRing create(int target, int capacity) { + return create(target, capacity, SystemProperties.FORCE_ORPHAN_STREAMING); + } + + static GlStreamingRing create(int target, int capacity, boolean forceOrphan) { + if (forceOrphan || !RenderSystem.supportsBufferStorage()) return null; + final int id = RENDER_BACKEND.genBuffers(); + RENDER_BACKEND.bindBuffer(target, id); + final int storageFlags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_COHERENT_BIT | GL44.GL_CLIENT_STORAGE_BIT; + RenderSystem.bufferStorage(target, capacity, storageFlags); + final int mapFlags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_COHERENT_BIT; + final ByteBuffer mapped = RENDER_BACKEND.mapBufferRange(target, 0, capacity, mapFlags); + RENDER_BACKEND.bindBuffer(target, 0); + if (mapped == null) { + GLStateManager.glDeleteBuffers(id); + GLStateManager.LOGGER.warn("Persistent map failed for streaming ring (target=0x{}, {} bytes)", Integer.toHexString(target), capacity); + return null; + } + GLStateManager.LOGGER.info("Streaming ring created (target=0x{}, {}KB)", Integer.toHexString(target), capacity / 1024); + return new GlStreamingRing(target, capacity, id, mapped); + } + + /** Byte offset of a reserved range, or -1 when it can never be served. */ + long reserve(int bytes, int alignment) { + if (bytes > capacity) return -1; + if (remaining < capacity / 2) { + reclaim(); + } + int offset = (writePos + alignment - 1) / alignment * alignment; + int waste = offset - writePos; + if (offset + bytes > capacity) { + waste = capacity - writePos; + offset = 0; + wraps++; + } + if (!ensureRemaining(waste + bytes)) return -1; + writePos = offset + bytes; + remaining -= waste + bytes; + pendingBytes += waste + bytes; + if (pendingBytes >= capacity / 4) { + fence(); + } + return offset; + } + + private boolean ensureRemaining(int needed) { + while (remaining < needed) { + if (fenceQueue.isEmpty()) { + if (pendingBytes == 0) return false; + fence(); + } + syncOldest(); + } + return true; + } + + private void fence() { + if (pendingBytes > 0) { + fenceQueue.enqueue(new FencedRegion(RENDER_BACKEND.fenceSync(GL32.GL_SYNC_GPU_COMMANDS_COMPLETE, 0), pendingBytes)); + pendingBytes = 0; + fencesIssued++; + } + } + + private static boolean signaled(int status) { + return status == GL32.GL_ALREADY_SIGNALED || status == GL32.GL_CONDITION_SATISFIED; + } + + private void reclaim() { + while (!fenceQueue.isEmpty()) { + final FencedRegion region = fenceQueue.first(); + if (!signaled(RENDER_BACKEND.clientWaitSync(region.fenceId, 0, 0L))) break; + GLStateManager.glDeleteSync(region.fenceId); + fenceQueue.dequeue(); + remaining += region.bytes; + } + } + + private void syncOldest() { + final FencedRegion region = fenceQueue.dequeue(); + forcedReclaims++; + final long deadline = System.nanoTime() + SYNC_WAIT_TOTAL_NANOS; + long remainingNanos = SYNC_WAIT_TOTAL_NANOS; + int status; + do { + status = RENDER_BACKEND.clientWaitSync(region.fenceId, GL32.GL_SYNC_FLUSH_COMMANDS_BIT, Math.min(SYNC_WAIT_SLICE_NANOS, remainingNanos)); + remainingNanos = deadline - System.nanoTime(); + } while (status == GL32.GL_TIMEOUT_EXPIRED && remainingNanos > 0); + if (!signaled(status)) { + GLStateManager.LOGGER.warn("Streaming ring fence wait did not signal (status=0x{}); reclaiming anyway", Integer.toHexString(status)); + } + GLStateManager.glDeleteSync(region.fenceId); + remaining += region.bytes; + reclaim(); + } + + void endFrame() { + fence(); + reclaim(); + } + + long address() { return mappedAddress; } + ByteBuffer mapped() { return mappedBuffer; } + int bufferId() { return bufferId; } + int capacity() { return capacity; } + int remaining() { return remaining; } + int wraps() { return wraps; } + int fencesIssued() { return fencesIssued; } + int forcedReclaims() { return forcedReclaims; } + + void destroy() { + while (!fenceQueue.isEmpty()) { + GLStateManager.glDeleteSync(fenceQueue.dequeue().fenceId); + } + if (bufferId != 0) { + RENDER_BACKEND.bindBuffer(target, bufferId); + RENDER_BACKEND.unmapBuffer(target); + RENDER_BACKEND.bindBuffer(target, 0); + GLStateManager.glDeleteBuffers(bufferId); + bufferId = 0; + } + } + + private record FencedRegion(long fenceId, int bytes) {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/PersistentStreamingBuffer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/PersistentStreamingBuffer.java index a038be1e7..ffffdd7c4 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/PersistentStreamingBuffer.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/PersistentStreamingBuffer.java @@ -1,184 +1,60 @@ package com.gtnewhorizons.angelica.glsm.streaming; -import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.RenderSystem; -import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue; -import org.embeddedt.embeddium.impl.gl.sync.GlFence; +import com.gtnewhorizons.angelica.config.SystemProperties; import org.lwjgl.opengl.GL15; -import org.lwjgl.opengl.GL30; -import org.lwjgl.opengl.GL32; -import org.lwjgl.opengl.GL44; import java.nio.ByteBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; -import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopy; +import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; +public final class PersistentStreamingBuffer { -/** - * Persistent-mapped ring buffer for streaming vertex data on GL4.4+ - */ -public class PersistentStreamingBuffer implements StreamingBuffer { + public static final int DEFAULT_CAPACITY = 16 * 1024 * 1024; - public static final int DEFAULT_CAPACITY = 16 * 1024 * 1024; // 16 MB + private final GlStreamingRing ring; - private int bufferId; - private final int capacity; - private final ByteBuffer mappedBuffer; - private final long mappedAddress; - private final ObjectArrayFIFOQueue fenceQueue = new ObjectArrayFIFOQueue<>(); - - private int writePos; - private int remaining; - private int pendingBytes; - - public PersistentStreamingBuffer() { - this(DEFAULT_CAPACITY); + private PersistentStreamingBuffer(GlStreamingRing ring) { + this.ring = ring; } - public PersistentStreamingBuffer(int capacity) { - this.capacity = capacity; - this.remaining = capacity; - - this.bufferId = RENDER_BACKEND.genBuffers(); - RENDER_BACKEND.bindBuffer(GL15.GL_ARRAY_BUFFER, bufferId); - - final int storageFlags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_COHERENT_BIT | GL44.GL_CLIENT_STORAGE_BIT; - RenderSystem.bufferStorage(GL15.GL_ARRAY_BUFFER, capacity, storageFlags); - - final int mapFlags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_COHERENT_BIT; - this.mappedBuffer = RENDER_BACKEND.mapBufferRange(GL15.GL_ARRAY_BUFFER, 0, capacity, mapFlags); - - RENDER_BACKEND.bindBuffer(GL15.GL_ARRAY_BUFFER, 0); - - if (this.mappedBuffer == null) { - GLStateManager.glDeleteBuffers(bufferId); - bufferId = 0; - throw new RuntimeException("Failed to persistently map streaming buffer"); - } - this.mappedAddress = memAddress0(mappedBuffer); + public static PersistentStreamingBuffer createOrNull(int capacity) { + return createOrNull(capacity, SystemProperties.FORCE_ORPHAN_STREAMING); } - @Override + public static PersistentStreamingBuffer createOrNull(int capacity, boolean forceOrphan) { + final GlStreamingRing ring = GlStreamingRing.create(GL15.GL_ARRAY_BUFFER, capacity, forceOrphan); + return ring == null ? null : new PersistentStreamingBuffer(ring); + } + + public int upload(ByteBuffer data, int vertexStride) { - final int dataSize = data.remaining(); - if (dataSize > capacity) { - return -1; - } - - reclaim(); - - final int alignUnit = vertexStride * 4; - final int alignedPos = ((writePos + alignUnit - 1) / alignUnit) * alignUnit; - final int alignmentWaste = alignedPos - writePos; - final int tailSpace = capacity - alignedPos; - - if (dataSize <= tailSpace) { - // Fits at tail — just need enough remaining budget - if (ensureRemaining(alignmentWaste + dataSize)) { - return writeAt(alignedPos, data, dataSize, alignmentWaste, vertexStride); - } - } else { - // Must wrap to start — burn remaining tail space - final int wrapWaste = capacity - writePos; - if (ensureRemaining(wrapWaste + dataSize)) { - return writeAtStart(data, dataSize, wrapWaste); - } - } - - return -1; + return upload(data, vertexStride, 1); } - /** Sync fences until {@code needed} bytes are available, or no fences remain. */ - private boolean ensureRemaining(int needed) { - while (remaining < needed) { - if (!syncOldest()) return false; - } - return true; + public int upload(ByteBuffer data, int vertexStride, int vertexAlignment) { + final int size = data.remaining(); + final long offset = ring.reserve(size, vertexStride * vertexAlignment); + if (offset < 0) return -1; + memCopy(memAddress0(data) + data.position(), ring.address() + offset, size); + RENDER_BACKEND.onPersistentBufferWrite(ring.bufferId(), offset, size); + return (int) (offset / vertexStride); } - private int writeAt(int offset, ByteBuffer data, int dataSize, int waste, int vertexStride) { - memCopy(memAddress0(data) + data.position(), mappedAddress + offset, dataSize); + public int getBufferId() { return ring.bufferId(); } + public int getCapacity() { return ring.capacity(); } + public int getRemaining() { return ring.remaining(); } + public int getForcedReclaims() { return ring.forcedReclaims(); } + public int getWraps() { return ring.wraps(); } - final int totalCost = waste + dataSize; - writePos = offset + dataSize; - remaining -= totalCost; - pendingBytes += totalCost; - return offset / vertexStride; - } + ByteBuffer getMappedBuffer() { return ring.mapped(); } - private int writeAtStart(ByteBuffer data, int dataSize, int wrapWaste) { - memCopy(memAddress0(data) + data.position(), mappedAddress, dataSize); - - final int totalCost = wrapWaste + dataSize; - writePos = dataSize; - remaining -= totalCost; - pendingBytes += totalCost; - return 0; - } - - @Override - public int getCapacity() { - return capacity; - } - - public int getRemaining() { return remaining; } - - @Override - public int getBufferId() { - return bufferId; - } - - @Override public void postDraw() { - if (pendingBytes > 0) { - final long fenceId = RENDER_BACKEND.fenceSync(GL32.GL_SYNC_GPU_COMMANDS_COMPLETE, 0); - fenceQueue.enqueue(new FencedRegion(new GlFence(fenceId), pendingBytes)); - pendingBytes = 0; - } + ring.endFrame(); } - @Override public void destroy() { - while (!fenceQueue.isEmpty()) { - fenceQueue.dequeue().fence.delete(); - } - if (bufferId != 0) { - RENDER_BACKEND.bindBuffer(GL15.GL_ARRAY_BUFFER, bufferId); - RENDER_BACKEND.unmapBuffer(GL15.GL_ARRAY_BUFFER); - RENDER_BACKEND.bindBuffer(GL15.GL_ARRAY_BUFFER, 0); - GLStateManager.glDeleteBuffers(bufferId); - bufferId = 0; - } + ring.destroy(); } - - private void reclaim() { - while (!fenceQueue.isEmpty()) { - final FencedRegion region = fenceQueue.first(); - if (!region.fence.isCompleted()) break; - region.fence.delete(); - fenceQueue.dequeue(); - remaining += region.bytes; - } - } - - /** Sync on oldest fence. Returns true if bytes were reclaimed. */ - private boolean syncOldest() { - if (fenceQueue.isEmpty()) return false; - final FencedRegion region = fenceQueue.first(); - if (!region.fence.sync()) { - GLStateManager.LOGGER.warn("Streaming buffer fence wait did not signal; reclaiming {} bytes anyway", region.bytes); - } - region.fence.delete(); - fenceQueue.dequeue(); - remaining += region.bytes; - reclaim(); // opportunistically reclaim any additional completed fences - return true; - } - - // Package-private accessors for testing - ByteBuffer getMappedBuffer() { return mappedBuffer; } - - private record FencedRegion(GlFence fence, int bytes) {} } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBuffer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBuffer.java deleted file mode 100644 index 0ede3e26e..000000000 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBuffer.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.streaming; - -import java.nio.ByteBuffer; - -public interface StreamingBuffer { - - int upload(ByteBuffer data, int vertexStride); - int getBufferId(); - void postDraw(); - int getCapacity(); - void destroy(); -} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingUploader.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingUploader.java index 2bc0d6c99..8c95cbb6c 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingUploader.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingUploader.java @@ -45,8 +45,12 @@ public final class StreamingUploader { return data.remaining(); } final int dataSize = data.remaining(); - final ByteBuffer mapped = RENDER_BACKEND.mapBufferRange(GL15.GL_ARRAY_BUFFER, 0, dataSize, MAP_WRITE_INVALIDATE_BUFFER); - memCopy(memAddress0(data), memAddress0(mapped), dataSize); + final long dst = RENDER_BACKEND.mapBufferRangeAddress(GL15.GL_ARRAY_BUFFER, 0, dataSize, MAP_WRITE_INVALIDATE_BUFFER); + if (dst == 0L) { + RENDER_BACKEND.bufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STREAM_DRAW); + return data.remaining(); + } + memCopy(memAddress0(data), dst, dataSize); RENDER_BACKEND.unmapBuffer(GL15.GL_ARRAY_BUFFER); return capacity; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java index 2f69ab7d9..e4b68de15 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java @@ -4,9 +4,13 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.QuadConverter; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import net.minecraft.client.renderer.Tessellator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -16,6 +20,7 @@ import org.lwjgl.opengl.GL15; import java.nio.ByteBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static org.joml.Math.clamp; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; @@ -28,6 +33,8 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; */ public class TessellatorStreamingDrawer { + private static final Tracy.ZoneId Z_SDL_STREAM_DRAW = Tracy.zoneId("sdlStreamDraw", Tracy.COLOR_FFP); + private static final Logger LOGGER = LogManager.getLogger("TessellatorStreamingDrawer"); private static final int FORMAT_COUNT = VertexFlags.BITSET_SIZE; // 16 @@ -43,6 +50,14 @@ public class TessellatorStreamingDrawer { private static boolean initialized = false; + // Tracy profiling counters + public static long streamedBytes; + public static long streamDraws; + public static long orphanFallbacks; + public static long streamContiguous; + private static int lastStreamEndVertex = -1; + private static int lastStreamDrawMode = -1; + static { // Initial repack buffer: 64KB repackCapacity = 0x10000; @@ -54,15 +69,7 @@ public class TessellatorStreamingDrawer { if (initialized) return; initialized = true; - if (RenderSystem.supportsBufferStorage() && !Boolean.getBoolean("angelica.forceOrphanStreaming")) { - try { - persistentBuffer = new PersistentStreamingBuffer(); - LOGGER.info("Persistent streaming buffer created ({}MB)", PersistentStreamingBuffer.DEFAULT_CAPACITY / (1024 * 1024)); - } catch (Exception e) { - LOGGER.warn("Failed to create persistent streaming buffer, using orphan fallback", e); - persistentBuffer = null; - } - } + persistentBuffer = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY); } /** @@ -84,7 +91,57 @@ public class TessellatorStreamingDrawer { // Determine the optimal vertex format from the tessellator's flags final int flags = VertexFlags.convertToFlags(tess.hasTexture, tess.hasColor, tess.hasNormals, tess.hasBrightness); - final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[flags]; + + final int effectiveFlags; + if (GLSMConfig.expandVertexFormats) { + effectiveFlags = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT | VertexFlags.BRIGHTNESS_BIT; + if (effectiveFlags != flags) { + final int[] rawBuffer = tess.rawBuffer; + final int defaultColor; + if (!tess.hasColor) { + final var c = GLStateManager.getColor(); + defaultColor = ((int)(clamp(0f, 1f, c.getAlpha()) * 255) << 24) | ((int)(clamp(0f, 1f, c.getBlue()) * 255) << 16) + | ((int)(clamp(0f, 1f, c.getGreen()) * 255) << 8) | (int)(clamp(0f, 1f, c.getRed()) * 255); + } else { + defaultColor = 0; + } + + final int defaultBrightness; + if (!tess.hasBrightness) { + defaultBrightness = ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF); + } else { + defaultBrightness = 0; + } + + final int defaultNormal; + if (!tess.hasNormals) { + final var n = ShaderManager.getCurrentNormal(); + defaultNormal = ((int)(clamp(-1f, 1f, n.z) * 127) << 16) | (((int)(clamp(-1f, 1f, n.y) * 127) & 0xFF) << 8) | ((int)(clamp(-1f, 1f, n.x) * 127) & 0xFF); + } else { + defaultNormal = 0; + } + + final int defaultTexU, defaultTexV; + if (!tess.hasTexture) { + final var tc = ShaderManager.getCurrentTexCoord(); + defaultTexU = Float.floatToRawIntBits(tc.x); + defaultTexV = Float.floatToRawIntBits(tc.y); + } else { + defaultTexU = 0; defaultTexV = 0; + } + + for (int i = 0; i < vertexCount; i++) { + final int base = i * 8; + if (!tess.hasTexture) { rawBuffer[base + 3] = defaultTexU; rawBuffer[base + 4] = defaultTexV; } + if (!tess.hasColor) { rawBuffer[base + 5] = defaultColor; } + if (!tess.hasNormals) { rawBuffer[base + 6] = defaultNormal; } + if (!tess.hasBrightness) { rawBuffer[base + 7] = defaultBrightness; } + } + } + } else { + effectiveFlags = flags; + } + final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[effectiveFlags]; final int vertexSize = format.getVertexSize(); final int requiredBytes = vertexCount * vertexSize; @@ -96,7 +153,7 @@ public class TessellatorStreamingDrawer { repackBuffer.position(0); repackBuffer.limit((int)(writePtr - repackAddress)); - uploadAndDraw(repackBuffer, flags, format, vertexSize, tess.drawMode, vertexCount); + uploadAndDraw(repackBuffer, effectiveFlags, format, vertexSize, tess.drawMode, vertexCount); } finally { if (locked) GLStateManager.releaseDrawLock(); } @@ -166,9 +223,9 @@ public class TessellatorStreamingDrawer { } if (persistentBuffer != null) { - cachedDebugInfo = String.format("Stream: Persistent %s (%s free) + %d orphan (%s)", + cachedDebugInfo = String.format("Stream: Persistent %s (%s free, %d forced) + %d orphan (%s)", formatBytes(persistentBuffer.getCapacity()), formatBytes(persistentBuffer.getRemaining()), - orphanCount, formatBytes(orphanBytes)); + persistentBuffer.getForcedReclaims(), orphanCount, formatBytes(orphanBytes)); } else { cachedDebugInfo = String.format("Stream: Orphan (%d bufs, %s)", orphanCount, formatBytes(orphanBytes)); } @@ -192,31 +249,49 @@ public class TessellatorStreamingDrawer { * Tries the persistent ring buffer first, falls back to orphan buffer on overflow. */ private static void uploadAndDraw(ByteBuffer packed, int flags, VertexFormat format, int vertexSize, int drawMode, int vertexCount) { + Tracy.beginZone(Z_SDL_STREAM_DRAW); final boolean locked = GLStateManager.acquireDrawLock(); try { ensureVAO(flags, format); + if (Tracy.ENABLED) { + streamedBytes += packed.remaining(); + streamDraws++; + } + int firstVertex = -1; if (persistentBuffer != null) { - firstVertex = persistentBuffer.upload(packed, vertexSize); + firstVertex = persistentBuffer.upload(packed, vertexSize, drawMode == GL11.GL_QUADS ? 4 : 1); } - if (firstVertex >= 0) { + final boolean fromRing = firstVertex >= 0; + if (fromRing) { GLStateManager.glBindVertexArray(persistentVAOs[flags]); } else { + if (Tracy.ENABLED && persistentBuffer != null) orphanFallbacks++; GLStateManager.glBindVertexArray(orphanVAOs[flags]); orphanBuffers[flags].upload(packed); firstVertex = 0; } + if (Tracy.ENABLED) { + if (fromRing && firstVertex == lastStreamEndVertex && drawMode == lastStreamDrawMode) streamContiguous++; + lastStreamEndVertex = fromRing ? firstVertex + vertexCount : -1; + lastStreamDrawMode = drawMode; + } + drawWithQuadConversion(drawMode, firstVertex, vertexCount); - GLStateManager.glBindVertexArray(0); } finally { if (locked) GLStateManager.releaseDrawLock(); + Tracy.endZone(); } } + public static long ringWraps() { + return persistentBuffer == null ? 0L : persistentBuffer.getWraps(); + } + private static void drawWithQuadConversion(int drawMode, int firstVertex, int vertexCount) { if (drawMode == GL11.GL_QUADS) { QuadConverter.drawQuadsAsTriangles(firstVertex, vertexCount); @@ -264,7 +339,6 @@ public class TessellatorStreamingDrawer { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, orphanBuffers[flags].getBufferId()); format.setupBufferState(0L); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); - GLStateManager.glBindVertexArray(0); } if (persistentBuffer != null && persistentVAOs[flags] == 0) { @@ -273,7 +347,6 @@ public class TessellatorStreamingDrawer { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, persistentBuffer.getBufferId()); format.setupBufferState(0L); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); - GLStateManager.glBindVertexArray(0); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBuffer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBuffer.java new file mode 100644 index 000000000..e5bd7e86c --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBuffer.java @@ -0,0 +1,99 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopy; +import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; + +public final class UniformRingBuffer { + + private static final int OFFSET_ALIGNMENT = 256; + + private final int capacity; + private final int blockSize; + private final int stride; + private final GlStreamingRing ring; + private int orphanBufferId; + + private int writePos; + private int orphanWraps; + + public UniformRingBuffer(int capacity, int blockSize) { + this(capacity, blockSize, SystemProperties.FORCE_ORPHAN_STREAMING); + } + + public UniformRingBuffer(int capacity, int blockSize, boolean forceOrphan) { + this.capacity = capacity; + this.blockSize = blockSize; + this.stride = (blockSize + OFFSET_ALIGNMENT - 1) & -OFFSET_ALIGNMENT; + this.ring = GlStreamingRing.create(GL31.GL_UNIFORM_BUFFER, capacity, forceOrphan); + if (ring == null) { + orphanBufferId = RENDER_BACKEND.genBuffers(); + RENDER_BACKEND.bindBuffer(GL31.GL_UNIFORM_BUFFER, orphanBufferId); + RENDER_BACKEND.bufferData(GL31.GL_UNIFORM_BUFFER, capacity, GL15.GL_STREAM_DRAW); + RENDER_BACKEND.bindBuffer(GL31.GL_UNIFORM_BUFFER, 0); + } + } + + public int writeBlock(ByteBuffer src) { + final long srcAddress = memAddress0(src); + if (ring != null) { + final long offset = ring.reserve(stride, OFFSET_ALIGNMENT); + if (offset < 0) { + throw new IllegalStateException("uniform ring exhausted with nothing in flight (needed=" + stride + ")"); + } + memCopy(srcAddress, ring.address() + offset, blockSize); + return (int) offset; + } + return writeOrphan(srcAddress); + } + + private int writeOrphan(long srcAddress) { + RENDER_BACKEND.bindBuffer(GL31.GL_UNIFORM_BUFFER, orphanBufferId); + int offset = writePos; + if (offset + stride > capacity) { + RENDER_BACKEND.bufferData(GL31.GL_UNIFORM_BUFFER, capacity, GL15.GL_STREAM_DRAW); + offset = 0; + orphanWraps++; + } + final long dst = RENDER_BACKEND.mapBufferRangeAddress(GL31.GL_UNIFORM_BUFFER, offset, blockSize, GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_INVALIDATE_RANGE_BIT | GL30.GL_MAP_UNSYNCHRONIZED_BIT); + if (dst == 0L) { + throw new IllegalStateException("mapBufferRange failed on uniform ring (offset=" + offset + ")"); + } + memCopy(srcAddress, dst, blockSize); + RENDER_BACKEND.unmapBuffer(GL31.GL_UNIFORM_BUFFER); + RENDER_BACKEND.bindBuffer(GL31.GL_UNIFORM_BUFFER, 0); + writePos = offset + stride; + return offset; + } + + public void endFrame() { + if (ring != null) { + ring.endFrame(); + } + } + + public int getBufferId() { return ring != null ? ring.bufferId() : orphanBufferId; } + public int getBlockSize() { return blockSize; } + public int getStride() { return stride; } + public boolean isPersistent() { return ring != null; } + public int getWraps() { return ring != null ? ring.wraps() : orphanWraps; } + public int getFencesIssued() { return ring != null ? ring.fencesIssued() : 0; } + public int getForcedReclaims() { return ring != null ? ring.forcedReclaims() : 0; } + + public void destroy() { + if (ring != null) { + ring.destroy(); + } else if (orphanBufferId != 0) { + GLStateManager.glDeleteBuffers(orphanBufferId); + orphanBufferId = 0; + } + } +} diff --git a/src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/DepthBufferFormat.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/DepthBufferFormat.java index 6b06c2472..2c332d460 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/DepthBufferFormat.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.texture; +package com.gtnewhorizons.angelica.glsm.texture; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; @@ -77,4 +77,12 @@ public enum DepthBufferFormat { public boolean isCombinedStencil() { return combinedStencil; } + + public DepthBufferFormat stripStencil() { + return switch (this) { + case DEPTH_STENCIL, DEPTH24_STENCIL8 -> DEPTH24; + case DEPTH32F_STENCIL8 -> DEPTH32F; + default -> this; + }; + } } diff --git a/src/main/java/net/coderbot/iris/gl/GlVersion.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/GlVersion.java similarity index 60% rename from src/main/java/net/coderbot/iris/gl/GlVersion.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/GlVersion.java index f67d0cbcd..42e5d9901 100644 --- a/src/main/java/net/coderbot/iris/gl/GlVersion.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/GlVersion.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl; +package com.gtnewhorizons.angelica.glsm.texture; public enum GlVersion { GL_11, diff --git a/src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/InternalTextureFormat.java similarity index 98% rename from src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/InternalTextureFormat.java index 755e5609c..5d460149f 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/InternalTextureFormat.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.gl.texture; +package com.gtnewhorizons.angelica.glsm.texture; import com.gtnewhorizons.angelica.glsm.RenderSystem; -import net.coderbot.iris.gl.GlVersion; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL31; diff --git a/src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelFormat.java similarity index 94% rename from src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelFormat.java index 338dd3f7c..2f1133330 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelFormat.java @@ -1,6 +1,5 @@ -package net.coderbot.iris.gl.texture; +package com.gtnewhorizons.angelica.glsm.texture; -import net.coderbot.iris.gl.GlVersion; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL30; diff --git a/src/main/java/net/coderbot/iris/gl/texture/PixelType.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelType.java similarity index 96% rename from src/main/java/net/coderbot/iris/gl/texture/PixelType.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelType.java index fb65c89e6..f309bb55f 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/PixelType.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/PixelType.java @@ -1,6 +1,5 @@ -package net.coderbot.iris.gl.texture; +package com.gtnewhorizons.angelica.glsm.texture; -import net.coderbot.iris.gl.GlVersion; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL30; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java index 6767c8433..0ebb6f2ea 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java @@ -1,29 +1,38 @@ package com.gtnewhorizons.angelica.glsm.texture; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import lombok.Getter; import lombok.Setter; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; public class TextureInfo { + private static final int UNSET_INT = Integer.MIN_VALUE; + private static final float UNSET_FLOAT = Float.NEGATIVE_INFINITY; + @Getter protected final int id; + @Getter @Setter protected int target = GL11.GL_TEXTURE_2D; protected int internalFormat = -1; protected int resolvedInternalFormat = -1; protected int width = -1; protected int height = -1; - @Getter @Setter protected int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR; - @Getter @Setter protected int magFilter = GL11.GL_LINEAR; - @Getter @Setter protected int wrapS = GL11.GL_REPEAT; - @Getter @Setter protected int wrapT = GL11.GL_REPEAT; + @Setter protected int minFilter = UNSET_INT; + @Setter protected int magFilter = UNSET_INT; + @Setter protected int wrapS = UNSET_INT; + @Setter protected int wrapT = UNSET_INT; + @Setter protected int maxLevel = UNSET_INT; @Getter @Setter protected int baseLevel = 0; - @Getter @Setter protected int maxLevel = 1000; @Getter @Setter protected int minLod = -1000; @Getter @Setter protected int maxLod = 1000; @Getter @Setter protected float lodBias = 0.0f; - @Getter @Setter protected float maxAnisotropy = 1.0f; + @Setter protected float maxAnisotropy = UNSET_FLOAT; @Getter @Setter protected boolean generateMipmap = false; @@ -62,4 +71,51 @@ public class TextureInfo { } return height; } + + public int getMinFilter() { + if (minFilter == UNSET_INT) minFilter = queryParameteri(GL11.GL_TEXTURE_MIN_FILTER); + return minFilter; + } + + public int getMagFilter() { + if (magFilter == UNSET_INT) magFilter = queryParameteri(GL11.GL_TEXTURE_MAG_FILTER); + return magFilter; + } + + public int getWrapS() { + if (wrapS == UNSET_INT) wrapS = queryParameteri(GL11.GL_TEXTURE_WRAP_S); + return wrapS; + } + + public int getWrapT() { + if (wrapT == UNSET_INT) wrapT = queryParameteri(GL11.GL_TEXTURE_WRAP_T); + return wrapT; + } + + public int getMaxLevel() { + if (maxLevel == UNSET_INT) maxLevel = queryParameteri(GL12.GL_TEXTURE_MAX_LEVEL); + return maxLevel; + } + + public float getMaxAnisotropy() { + if (maxAnisotropy == UNSET_FLOAT) { + if (!RENDER_BACKEND.isAnisotropicSupported()) maxAnisotropy = 1.0f; + else maxAnisotropy = queryParameterf(EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT); + } + return maxAnisotropy; + } + + private int queryParameteri(int pname) { + if (GLStateManager.getBoundTextureForServerState() == id) { + return RENDER_BACKEND.getTexParameteri(target, pname); + } + return RENDER_BACKEND.getTextureParameteri(id, target, pname); + } + + private float queryParameterf(int pname) { + if (GLStateManager.getBoundTextureForServerState() == id) { + return RENDER_BACKEND.getTexParameterf(target, pname); + } + return RENDER_BACKEND.getTextureParameterf(id, target, pname); + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java index 7d3f2e416..2a5ba876c 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java @@ -5,6 +5,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL21; import org.lwjgl.opengl.GL30; @@ -44,9 +45,10 @@ public class TextureInfoCache { } public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) { - if (target == GL11.GL_TEXTURE_2D && level == 0) { + if (isTrackedTarget(target) && level == 0) { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; + info.setTarget(target); info.internalFormat = internalformat; info.resolvedInternalFormat = isGenericCompressedInternalFormat(internalformat) ? -1 : internalformat; info.width = width; @@ -55,9 +57,10 @@ public class TextureInfoCache { } public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) { - if (target == GL11.GL_TEXTURE_2D && level == 0) { + if (isTrackedTarget(target) && level == 0) { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; + info.setTarget(target); info.internalFormat = internalformat; info.resolvedInternalFormat = isGenericCompressedInternalFormat(internalformat) ? -1 : internalformat; info.width = width; @@ -77,6 +80,15 @@ public class TextureInfoCache { }; } + private static boolean isTrackedTarget(int target) { + return target == GL11.GL_TEXTURE_2D + || target == GL11.GL_TEXTURE_1D + || target == GL12.GL_TEXTURE_3D + || target == GL13.GL_TEXTURE_CUBE_MAP + || target == GL30.GL_TEXTURE_2D_ARRAY + || target == GL30.GL_TEXTURE_1D_ARRAY; + } + public void onDeleteTexture(int id) { if (id < 0) return; diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureType.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureType.java similarity index 96% rename from src/main/java/net/coderbot/iris/gl/texture/TextureType.java rename to glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureType.java index 812b417dd..8b55d8df0 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureType.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.texture; +package com.gtnewhorizons.angelica.glsm.texture; import com.gtnewhorizons.angelica.glsm.RenderSystem; import org.lwjgl.opengl.GL11; diff --git a/glsm/src/stubs/java/net/minecraft/launchwrapper/Launch.java b/glsm/src/stubs/java/net/minecraft/launchwrapper/Launch.java new file mode 100644 index 000000000..06f0ecf94 --- /dev/null +++ b/glsm/src/stubs/java/net/minecraft/launchwrapper/Launch.java @@ -0,0 +1,8 @@ +package net.minecraft.launchwrapper; + +import java.util.Map; + +// Compile-only stub. +public class Launch { + public static Map blackboard; +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CaptureGateTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CaptureGateTest.java new file mode 100644 index 000000000..2b29699de --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CaptureGateTest.java @@ -0,0 +1,66 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CaptureGateTest { + + @Test + void gateOffWhenNothingAttached() { + assertFalse(CaptureGate.gateValue(false, false, false)); + } + + @Test + void gateOnWhenForced() { + assertTrue(CaptureGate.gateValue(true, false, false)); + } + + @Test + void gateOnWhenToolAttached() { + assertTrue(CaptureGate.gateValue(false, true, false)); + } + + @Test + void gateOnWhenTracyConnected() { + assertTrue(CaptureGate.gateValue(false, false, true)); + } + + @Test + void envDetectionMatchesRenderDocVariables() { + assertTrue(CaptureGate.detectFromEnv(k -> "RENDERDOC_CAPTURE_KEYPRESS".equals(k) ? "1" : null)); + assertTrue(CaptureGate.detectFromEnv(k -> "ENABLE_VULKAN_RENDERDOC_CAPTURE".equals(k) ? "1" : null)); + assertTrue(CaptureGate.detectFromEnv(k -> "RENDERDOC_HOOK_EGL".equals(k) ? "1" : null)); + } + + @Test + void envDetectionIgnoresUnrelatedVariables() { + assertFalse(CaptureGate.detectFromEnv(k -> "PATH".equals(k) ? "/usr/bin" : null)); + } + + @Test + void mapsDetectionFindsCaptureLibraries() { + assertTrue(CaptureGate.detectFromMaps(mapsWith("/usr/lib/librenderdoc.so"))); + assertTrue(CaptureGate.detectFromMaps(mapsWith("/usr/lib/x86_64-linux-gnu/libVkLayer_GLES_RenderDoc.so"))); + assertTrue(CaptureGate.detectFromMaps(mapsWith("/usr/lib/apitrace/wrappers/glxtrace.so"))); + assertTrue(CaptureGate.detectFromMaps(mapsWith("/usr/lib/apitrace/wrappers/egltrace.so"))); + } + + @Test + void mapsDetectionIgnoresOrdinaryLibraries() { + assertFalse(CaptureGate.detectFromMaps(mapsWith("/usr/lib/libvulkan.so.1"))); + assertFalse(CaptureGate.detectFromMaps(Collections.emptyList())); + } + + private static List mapsWith(String path) { + return Arrays.asList( + "55a1b2c00000-55a1b2c21000 r--p 00000000 fd:01 262401 /usr/lib/jvm/java-21/bin/java", + "7f2c1a000000-7f2c1a021000 r-xp 00000000 fd:01 262402 " + path, + "7ffd1a000000-7ffd1a021000 rw-p 00000000 00:00 0 [stack]"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java index bf955e733..89b65320a 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java @@ -69,7 +69,7 @@ class CompatShaderTransformerTest { """; String result = CompatShaderTransformer.transform(src, false); - // texture2D → texture + // texture2D -> texture assertFalse(result.contains("texture2D")); assertTrue(result.contains("texture")); } @@ -263,13 +263,13 @@ class CompatShaderTransformerTest { String result = CompatShaderTransformer.transform(src, true); assertFalse(result.contains("shadow2D("), "shadow2D should be renamed"); - // shadow2D → texture with vec4 wrapping + // shadow2D -> texture with vec4 wrapping assertTrue(result.contains("texture"), "shadow2D should be renamed to texture"); } @Test void testReservedWordTextureAsVariable() { - // Shader declares 'texture' as a sampler variable — this is valid in GLSL 120 + // Shader declares 'texture' as a sampler variable - this is valid in GLSL 120 // but 'texture' is a reserved word in GLSL 330+, causing parse failures without pre-rename String src = """ #version 120 @@ -279,7 +279,7 @@ class CompatShaderTransformerTest { } """; - // Should not throw — the pre-parse replaceTexture handles this + // Should not throw - the pre-parse replaceTexture handles this String result = CompatShaderTransformer.transform(src, true); assertNotNull(result); assertTrue(result.contains("#version 330 core")); @@ -362,7 +362,7 @@ class CompatShaderTransformerTest { """; String result = CompatShaderTransformer.transform(src, false); - assertTrue(result.contains("angelica_Color"), "gl_Color → angelica_Color (vertex attribute)"); + assertTrue(result.contains("angelica_Color"), "gl_Color -> angelica_Color (vertex attribute)"); assertTrue(result.contains("in vec4 angelica_Color"), "should have in declaration"); assertTrue(result.contains("location = 1"), "should use attribute location 1"); assertFalse(result.contains("gl_Color"), "gl_Color should not remain"); @@ -469,8 +469,8 @@ class CompatShaderTransformerTest { @Test void testGlColorVertexVsFragmentDifferentTreatment() { - // Vertex: gl_Color = vertex attribute → angelica_Color - // Fragment: gl_Color = interpolated gl_FrontColor → angelica_FrontColor + // Vertex: gl_Color = vertex attribute -> angelica_Color + // Fragment: gl_Color = interpolated gl_FrontColor -> angelica_FrontColor String vertSrc = """ #version 120 void main() { @@ -488,14 +488,14 @@ class CompatShaderTransformerTest { String vertResult = CompatShaderTransformer.transform(vertSrc, false); String fragResult = CompatShaderTransformer.transform(fragSrc, true); - // Vertex shader: gl_Color → angelica_Color (attribute), gl_FrontColor → angelica_FrontColor (out) - assertTrue(vertResult.contains("angelica_Color"), "vertex gl_Color → angelica_Color"); - assertTrue(vertResult.contains("angelica_FrontColor"), "vertex gl_FrontColor → angelica_FrontColor"); + // Vertex shader: gl_Color -> angelica_Color (attribute), gl_FrontColor -> angelica_FrontColor (out) + assertTrue(vertResult.contains("angelica_Color"), "vertex gl_Color -> angelica_Color"); + assertTrue(vertResult.contains("angelica_FrontColor"), "vertex gl_FrontColor -> angelica_FrontColor"); assertFalse(vertResult.contains("gl_Color"), "no gl_Color should remain in vertex"); assertFalse(vertResult.contains("gl_FrontColor"), "no gl_FrontColor should remain"); - // Fragment shader: gl_Color → angelica_FrontColor (in varying) - assertTrue(fragResult.contains("angelica_FrontColor"), "fragment gl_Color → angelica_FrontColor"); + // Fragment shader: gl_Color -> angelica_FrontColor (in varying) + assertTrue(fragResult.contains("angelica_FrontColor"), "fragment gl_Color -> angelica_FrontColor"); assertFalse(fragResult.contains("gl_Color"), "fragment should NOT have gl_Color"); } @@ -588,15 +588,37 @@ class CompatShaderTransformerTest { String vertResult = CompatShaderTransformer.transform(vertSrc, false); String fragResult = CompatShaderTransformer.transform(fragSrc, true); - // attribute → in, varying → out (vertex) + // attribute -> in, varying -> out (vertex) assertFalse(vertResult.contains("attribute"), "no 'attribute' keyword in core profile"); assertFalse(vertResult.contains("varying"), "no 'varying' keyword in vertex"); - assertTrue(vertResult.contains("in float a_Custom"), "attribute → in"); - assertTrue(vertResult.contains("out vec2 v_TexCoord"), "varying → out in vertex"); + assertTrue(vertResult.contains("in float a_Custom"), "attribute -> in"); + assertTrue(vertResult.contains("out vec2 v_TexCoord"), "varying -> out in vertex"); - // varying → in (fragment) + // varying -> in (fragment) assertFalse(fragResult.contains("varying"), "no 'varying' keyword in fragment"); - assertTrue(fragResult.contains("in vec2 v_TexCoord"), "varying → in in fragment"); + assertTrue(fragResult.contains("in vec2 v_TexCoord"), "varying -> in in fragment"); + } + + @Test + void testPassthroughVertexShader_matchesPrecisionQualifiedFragmentInputs() { + final String esFrag = """ + #version 320 es + precision mediump float; + precision highp int; + in highp vec4 angelica_TexCoord0; + in highp vec4 angelica_FrontColor; + in highp float angelica_FogFragCoord; + layout(location = 0) out highp vec4 angelica_FragData0; + void main() { + angelica_FragData0 = angelica_FrontColor * angelica_TexCoord0 + vec4(angelica_FogFragCoord); + } + """; + + final String vs = CompatShaderTransformer.generatePassthroughVertexShader(esFrag); + assertNotNull(vs); + assertTrue(vs.contains("out vec4 angelica_FrontColor"), "VS must declare angelica_FrontColor output\n" + vs); + assertTrue(vs.contains("out vec4 angelica_TexCoord0"), "VS must declare angelica_TexCoord0 output\n" + vs); + assertTrue(vs.contains("out float angelica_FogFragCoord"), "VS must declare angelica_FogFragCoord output\n" + vs); } @Test diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java index 1c69893de..bd602766e 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm; +import org.lwjgl.opengl.GL11; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL20; @@ -70,7 +71,7 @@ class CompatUniformManagerTest { CompatUniformManager.refreshCompatUniforms(program); // Verify no GL errors - assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after uniform upload"); + assertEquals(0, GL11.glGetError(), "GL error after uniform upload"); } @Test @@ -147,7 +148,7 @@ class CompatUniformManagerTest { GL20.glUseProgram(program); CompatUniformManager.refreshCompatUniforms(program); - assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after fog uniform upload"); + assertEquals(0, GL11.glGetError(), "GL error after fog uniform upload"); } @Test diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java deleted file mode 100644 index d3ff6cb91..000000000 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java +++ /dev/null @@ -1,287 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; - -import java.nio.FloatBuffer; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** Tests GLSM display list behavior matches OpenGL spec. */ -@GLCompatTest -class DisplayListCompilationGLSMTest { - - private int testList = -1; - - private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) { - for (int i = 0; i < 16; i++) { - assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")"); - } - } - - @BeforeEach - void setup() { - // Ensure not recording from a previous failed test - if (DisplayListManager.isRecording()) { - try { GLStateManager.glEndList(); } catch (Exception ignored) {} - } - GLStateManager.disableBlend(); - GLStateManager.disableDepthTest(); - GLStateManager.disableCull(); - // Reset matrix to identity for transform tests - GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - GLStateManager.glLoadIdentity(); - } - - @AfterEach - void cleanup() { - // End any open recording - if (DisplayListManager.isRecording()) { - try { GLStateManager.glEndList(); } catch (Exception ignored) {} - } - if (testList > 0) { - GLStateManager.glDeleteLists(testList, 1); - testList = -1; - } - GLStateManager.disableBlend(); - GLStateManager.disableDepthTest(); - GLStateManager.disableCull(); - } - - @Test - void glsm_compile_doesNotChangeState() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.enableBlend(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged"); - - GLStateManager.glEndList(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged"); - - GLStateManager.glCallList(testList); - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed"); - } - - @Test - void glsm_compileAndExecute_changesStateImmediately() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - GLStateManager.enableBlend(); - - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed"); - - GLStateManager.glEndList(); - - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains"); - } - - @Test - void glsm_compile_transformNotApplied() { - FloatBuffer before = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); - - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.glTranslatef(10, 20, 30); - - FloatBuffer during = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); - assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged"); - - GLStateManager.glEndList(); - } - - @Test - void glsm_compileAndExecute_transformAppliedImmediately() { - // COMPILE_AND_EXECUTE: transforms apply to GLSM stack immediately (not deferred). This is required because state commands between transforms and draws - // may trigger Iris program activation, which reads the matrix from the GLSM stack. - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - GLStateManager.glTranslatef(10, 0, 0); // Applied immediately - DisplayListManager.flushMatrix(); - - FloatBuffer afterTranslate = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterTranslate); - assertEquals(10.0f, afterTranslate.get(12), 0.001f, "After translate: applied immediately"); - - GLStateManager.enableBlend(); - - FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); - assertEquals(10.0f, afterStateCmd.get(12), 0.001f, "After state cmd: still applied"); - - GLStateManager.glEndList(); - - FloatBuffer afterEndList = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterEndList); - assertEquals(10.0f, afterEndList.get(12), 0.001f, "After glEndList: still applied"); - } - - @Test - void glsm_playback_appliesRecordedState() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.enableBlend(); - GLStateManager.glEndList(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After compile: unchanged"); - - GLStateManager.glCallList(testList); - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: enabled"); - } - - @Test - void glsm_compile_multipleStateChanges() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.enableBlend(); - GLStateManager.enableDepthTest(); - GLStateManager.enableCull(); - GLStateManager.glEndList(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged"); - assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged"); - assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged"); - - GLStateManager.glCallList(testList); - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled"); - assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled"); - assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled"); - } - - @Test - void glsm_compile_matrixModeChangeRecorded() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GLStateManager.glTranslatef(5, 0, 0); - GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - GLStateManager.glTranslatef(10, 0, 0); - GLStateManager.glEndList(); - - FloatBuffer proj = BufferUtils.createFloatBuffer(16); - FloatBuffer mv = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); - assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); - assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); - - GLStateManager.glCallList(testList); - - proj.clear(); mv.clear(); - GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); - assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)"); - assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); - } - - @Test - void glsm_compile_pushPopMatrixRecorded() { - GLStateManager.glTranslatef(100, 0, 0); // Base transform - - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - GLStateManager.glPushMatrix(); - GLStateManager.glTranslatef(10, 0, 0); - GLStateManager.glPopMatrix(); - GLStateManager.glEndList(); - - FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); - assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base"); - - GLStateManager.glCallList(testList); - - FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); - assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base"); - } - - @Test - void glsm_compileAndExecute_matrixModeWithTransforms() { - GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GLStateManager.glLoadIdentity(); - GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - - GLStateManager.glTranslatef(10, 0, 0); // Applied immediately - GLStateManager.glRotatef(45, 0, 1, 0); // Applied immediately - DisplayListManager.flushMatrix(); - - FloatBuffer afterTransforms = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterTransforms); - assertNotEquals(0.0f, afterTransforms.get(12), "After transforms: applied immediately"); - - GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - - FloatBuffer proj = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - assertEquals(0.0f, proj.get(12), 0.001f, "PROJECTION still identity"); - - GLStateManager.glEndList(); - - // Cleanup: restore matrix mode to MODELVIEW - GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - } - - @Test - void glsm_compileAndExecute_pushPopMatrix() { - // Push/pop work correctly with immediate transform application - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - - GLStateManager.glPushMatrix(); - GLStateManager.glTranslatef(10, 0, 0); // Applied immediately - DisplayListManager.flushMatrix(); - - FloatBuffer afterTranslate = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterTranslate); - assertEquals(10.0f, afterTranslate.get(12), 0.001f, "After translate: applied immediately"); - - GLStateManager.glPopMatrix(); // Pops back to pre-push state - - FloatBuffer afterPop = BufferUtils.createFloatBuffer(16); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); - assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity (pushed state)"); - - GLStateManager.glEndList(); - } - - @Test - void glsm_unsupportedOpInList_abortsCleanly() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - assertTrue(DisplayListManager.isRecording(), "recording after glNewList"); - - assertThrows(UnsupportedOperationException.class, () -> GLStateManager.glReadBuffer(GL11.GL_FRONT)); - - assertFalse(DisplayListManager.isRecording(), "recording state must be reset after an in-list throw"); - assertEquals(DisplayListManager.RecordMode.NONE, DisplayListManager.getRecordMode()); - - assertDoesNotThrow(() -> GLStateManager.glReadBuffer(GL11.GL_FRONT)); - assertDoesNotThrow(GLStateManager::glEndList); - } - - @Test - void glsm_abortIfLeaked_recoversOpenList() { - testList = GL11.glGenLists(1); - GLStateManager.glNewList(testList, GL11.GL_COMPILE); - assertTrue(DisplayListManager.isRecording()); - - DisplayListManager.abortIfLeaked(); - - assertFalse(DisplayListManager.isRecording(), "frame-begin backstop must clear a leaked open list"); - } -} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationParityTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationParityTest.java new file mode 100644 index 000000000..f31a3738b --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationParityTest.java @@ -0,0 +1,244 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCompatTest +class DisplayListCompilationParityTest { + + enum Caller { + GLSM { + void newList(int list, int mode) { GLStateManager.glNewList(list, mode); } + void endList() { GLStateManager.glEndList(); } + void callList(int list) { GLStateManager.glCallList(list); } + void enable(int cap) { GLStateManager.glEnable(cap); } + void translate(float x, float y, float z) { GLStateManager.glTranslatef(x, y, z); } + void pushMatrix() { GLStateManager.glPushMatrix(); } + void popMatrix() { GLStateManager.glPopMatrix(); } + void matrixMode(int mode) { GLStateManager.glMatrixMode(mode); } + void getFloat(int pname, FloatBuffer dst) { GLStateManager.glGetFloat(pname, dst); } + void flushMatrix() { DisplayListManager.flushMatrix(); } + }, + RAW { + void newList(int list, int mode) { GL11.glNewList(list, mode); } + void endList() { GL11.glEndList(); } + void callList(int list) { GL11.glCallList(list); } + void enable(int cap) { GL11.glEnable(cap); } + void translate(float x, float y, float z) { GL11.glTranslatef(x, y, z); } + void pushMatrix() { GL11.glPushMatrix(); } + void popMatrix() { GL11.glPopMatrix(); } + void matrixMode(int mode) { GL11.glMatrixMode(mode); } + void getFloat(int pname, FloatBuffer dst) { GL11.glGetFloat(pname, dst); } + void flushMatrix() {} + }; + + abstract void newList(int list, int mode); + abstract void endList(); + abstract void callList(int list); + abstract void enable(int cap); + abstract void translate(float x, float y, float z); + abstract void pushMatrix(); + abstract void popMatrix(); + abstract void matrixMode(int mode); + abstract void getFloat(int pname, FloatBuffer dst); + + /** GL applies transforms as they are issued; GLSM defers to its own stack until flushed. */ + abstract void flushMatrix(); + } + + private int testList = -1; + + private static FloatBuffer matrix(Caller c, int pname) { + final FloatBuffer buf = BufferUtils.createFloatBuffer(16); + c.getFloat(pname, buf); + return buf; + } + + private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) { + for (int i = 0; i < 16; i++) { + assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")"); + } + } + + @BeforeEach + void setup() { + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GL11.glDisable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + } + + @AfterEach + void cleanup() { + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + if (testList > 0) { + GLStateManager.glDeleteLists(testList, 1); + testList = -1; + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GL11.glDisable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compile_doesNotChangeState(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE); + c.enable(GL11.GL_BLEND); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged"); + + c.endList(); + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged"); + + c.callList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed"); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compileAndExecute_changesStateImmediately(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE_AND_EXECUTE); + c.enable(GL11.GL_BLEND); + + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed"); + + c.endList(); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains"); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compileAndExecute_transformAppliedImmediately(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE_AND_EXECUTE); + c.translate(10, 0, 0); + c.flushMatrix(); + + assertEquals(10.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "During GL_COMPILE_AND_EXECUTE: transform applied immediately"); + + c.enable(GL11.GL_BLEND); + assertEquals(10.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After a state command: still applied"); + + c.endList(); + assertEquals(10.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After endList: still applied"); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compileAndExecute_pushPopMatrixExecutedImmediately(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + c.pushMatrix(); + c.translate(10, 0, 0); + c.flushMatrix(); + + assertEquals(10.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "Inside push: translate visible"); + + c.popMatrix(); + + assertEquals(0.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After pop: back to the pushed state"); + + c.endList(); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compile_transformNotApplied(Caller c) { + final FloatBuffer before = matrix(c, GL11.GL_MODELVIEW_MATRIX); + + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE); + c.translate(10, 20, 30); + + assertMatrixEquals(before, matrix(c, GL11.GL_MODELVIEW_MATRIX), "During GL_COMPILE: matrix unchanged"); + + c.endList(); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compile_multipleStateChanges(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE); + c.enable(GL11.GL_BLEND); + c.enable(GL11.GL_DEPTH_TEST); + c.enable(GL11.GL_CULL_FACE); + c.endList(); + + assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged"); + assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged"); + + c.callList(testList); + assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled"); + assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled"); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compile_matrixModeChangeRecorded(Caller c) { + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE); + c.matrixMode(GL11.GL_PROJECTION); + c.translate(5, 0, 0); + c.matrixMode(GL11.GL_MODELVIEW); + c.translate(10, 0, 0); + c.endList(); + + assertEquals(0.0f, matrix(c, GL11.GL_PROJECTION_MATRIX).get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); + assertEquals(0.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); + + c.callList(testList); + + assertEquals(5.0f, matrix(c, GL11.GL_PROJECTION_MATRIX).get(12), 0.001f, "After playback: PROJECTION has translate(5)"); + assertEquals(10.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); + } + + @ParameterizedTest + @EnumSource(Caller.class) + void compile_pushPopMatrixRecorded(Caller c) { + c.translate(100, 0, 0); // Base transform + + testList = GL11.glGenLists(1); + c.newList(testList, GL11.GL_COMPILE); + c.pushMatrix(); + c.translate(10, 0, 0); + c.popMatrix(); + c.endList(); + + assertEquals(100.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After GL_COMPILE: matrix at base"); + + c.callList(testList); + + assertEquals(100.0f, matrix(c, GL11.GL_MODELVIEW_MATRIX).get(12), 0.001f, "After playback: matrix at base (push/pop balanced)"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java deleted file mode 100644 index 875c0a9d6..000000000 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationRawGLTest.java +++ /dev/null @@ -1,261 +0,0 @@ -package com.gtnewhorizons.angelica.glsm; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; - -import java.nio.FloatBuffer; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** Tests raw GL11 display list behavior (reference for GLSM). */ -@GLCompatTest -class DisplayListCompilationRawGLTest { - - private int testList = -1; - - private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) { - for (int i = 0; i < 16; i++) { - assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")"); - } - } - - @BeforeEach - void setup() { - GL11.glDisable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_CULL_FACE); - } - - @AfterEach - void cleanup() { - if (testList > 0) { - GL11.glDeleteLists(testList, 1); - testList = -1; - } - GL11.glDisable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_CULL_FACE); - } - - @Test - void rawGL_compile_doesNotChangeState() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - GL11.glEnable(GL11.GL_BLEND); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged"); - - GL11.glEndList(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged"); - - GL11.glCallList(testList); - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed"); - } - - @Test - void rawGL_compileAndExecute_changesStateImmediately() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - GL11.glEnable(GL11.GL_BLEND); - - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed"); - - GL11.glEndList(); - - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains"); - } - - @Test - void rawGL_compile_transformNotApplied() { - FloatBuffer before = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); - - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - GL11.glTranslatef(10, 20, 30); - - FloatBuffer during = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); - assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged"); - - GL11.glEndList(); - } - - @Test - void rawGL_compileAndExecute_transformAppliedImmediately() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - GL11.glTranslatef(10, 0, 0); - - FloatBuffer matrix = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrix); - assertEquals(10.0f, matrix.get(12), 0.001f, "During GL_COMPILE_AND_EXECUTE: transform applied"); - - GL11.glEndList(); - } - - @Test - void rawGL_compile_multipleStateChanges() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_CULL_FACE); - GL11.glEndList(); - - assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged"); - assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged"); - assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged"); - - GL11.glCallList(testList); - assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled"); - assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled"); - assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled"); - } - - @Test - void rawGL_compile_matrixModeChangeRecorded() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glTranslatef(5, 0, 0); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glTranslatef(10, 0, 0); - GL11.glEndList(); - - FloatBuffer proj = BufferUtils.createFloatBuffer(16); - FloatBuffer mv = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); - assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); - assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); - - GL11.glCallList(testList); - - proj.clear(); mv.clear(); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); - assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)"); - assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); - } - - @Test - void rawGL_compile_pushPopMatrixRecorded() { - GL11.glTranslatef(100, 0, 0); // Base transform - - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - GL11.glPushMatrix(); - GL11.glTranslatef(10, 0, 0); - GL11.glPopMatrix(); - GL11.glEndList(); - - FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); - assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base"); - - GL11.glCallList(testList); - - FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); - assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base (push/pop balanced)"); - } - - @Test - void rawGL_compileAndExecute_pushPopMatrixExecutedImmediately() { - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - - GL11.glPushMatrix(); - GL11.glTranslatef(10, 0, 0); - - FloatBuffer inside = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, inside); - assertEquals(10.0f, inside.get(12), 0.001f, "Inside push: translate visible"); - - GL11.glPopMatrix(); - - FloatBuffer afterPop = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); - assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity"); - - GL11.glEndList(); - } - - // ==================== Immediate Mode with Transforms (Raw GL) ==================== - - @Test - void rawGL_compile_immediateModeWithTransforms() { - // Verifies GL_COMPILE doesn't execute, playback applies transforms - GL11.glLoadIdentity(); - GL11.glTranslatef(100.0f, 0.0f, 0.0f); // Base position - - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE); - - GL11.glPushMatrix(); - GL11.glTranslatef(50.0f, 25.0f, 0.0f); - GL11.glScalef(0.5f, 0.5f, 1.0f); - - GL11.glBegin(GL11.GL_QUADS); - GL11.glVertex3f(0.0f, 0.0f, 0.0f); - GL11.glVertex3f(16.0f, 0.0f, 0.0f); - GL11.glVertex3f(16.0f, 16.0f, 0.0f); - GL11.glVertex3f(0.0f, 16.0f, 0.0f); - GL11.glEnd(); - - GL11.glPopMatrix(); - GL11.glEndList(); - - // Matrix should still be at base position after GL_COMPILE - FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); - assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix unchanged"); - - // Playback - push/pop should preserve base transform - GL11.glCallList(testList); - - FloatBuffer afterPlayback = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlayback); - assertEquals(100.0f, afterPlayback.get(12), 0.001f, "After playback: base position preserved"); - assertEquals(1.0f, afterPlayback.get(0), 0.001f, "After playback: no scale (popped)"); - - GL11.glLoadIdentity(); - } - - @Test - void rawGL_compileAndExecute_immediateModeExecutesImmediately() { - // Verifies GL_COMPILE_AND_EXECUTE executes transforms during recording - GL11.glLoadIdentity(); - - testList = GL11.glGenLists(1); - GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); - - GL11.glScalef(0.5f, 0.5f, 0.5f); - - FloatBuffer during = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); - assertEquals(0.5f, during.get(0), 0.001f, "During COMPILE_AND_EXECUTE: scale applied"); - - GL11.glBegin(GL11.GL_QUADS); - GL11.glVertex3f(0.0f, 0.0f, 0.0f); - GL11.glVertex3f(1.0f, 0.0f, 0.0f); - GL11.glVertex3f(1.0f, 1.0f, 0.0f); - GL11.glVertex3f(0.0f, 1.0f, 0.0f); - GL11.glEnd(); - - GL11.glEndList(); - - FloatBuffer after = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, after); - assertEquals(0.5f, after.get(0), 0.001f, "After COMPILE_AND_EXECUTE: scale remains"); - - GL11.glLoadIdentity(); - } -} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationTest.java new file mode 100644 index 000000000..a02055a0e --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationTest.java @@ -0,0 +1,170 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCompatTest +class DisplayListCompilationTest { + + private int testList = -1; + + @BeforeEach + void setup() { + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + } + + @AfterEach + void cleanup() { + if (DisplayListManager.isRecording()) { + try { GLStateManager.glEndList(); } catch (Exception ignored) {} + } + if (testList > 0) { + GLStateManager.glDeleteLists(testList, 1); + testList = -1; + } + GLStateManager.disableBlend(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + } + + private static FloatBuffer matrix(int pname) { + final FloatBuffer buf = BufferUtils.createFloatBuffer(16); + GLStateManager.glGetFloat(pname, buf); + return buf; + } + + @Test + void glsm_compileAndExecute_matrixModeWithTransforms() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GLStateManager.glTranslatef(10, 0, 0); + GLStateManager.glRotatef(45, 0, 1, 0); + DisplayListManager.flushMatrix(); + + assertNotEquals(0.0f, matrix(GL11.GL_MODELVIEW_MATRIX).get(12), "After transforms: applied immediately"); + + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + assertEquals(0.0f, matrix(GL11.GL_PROJECTION_MATRIX).get(12), 0.001f, "PROJECTION still identity"); + + GLStateManager.glEndList(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + @Test + void glsm_unsupportedOpInList_abortsCleanly() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + assertTrue(DisplayListManager.isRecording(), "recording after glNewList"); + + assertThrows(UnsupportedOperationException.class, () -> GLStateManager.glReadBuffer(GL11.GL_FRONT)); + + assertFalse(DisplayListManager.isRecording(), "recording state must be reset after an in-list throw"); + assertEquals(DisplayListManager.RecordMode.NONE, DisplayListManager.getRecordMode()); + + assertDoesNotThrow(() -> GLStateManager.glReadBuffer(GL11.GL_FRONT)); + assertDoesNotThrow(GLStateManager::glEndList); + GLStateManager.glReadBuffer(GL11.GL_BACK); + } + + @Test + void glsm_abortIfLeaked_recoversOpenList() { + testList = GL11.glGenLists(1); + GLStateManager.glNewList(testList, GL11.GL_COMPILE); + assertTrue(DisplayListManager.isRecording()); + + DisplayListManager.abortIfLeaked(); + + assertFalse(DisplayListManager.isRecording(), "frame-begin backstop must clear a leaked open list"); + } + + @Test + void rawGL_compile_immediateModeWithTransforms() { + GL11.glLoadIdentity(); + GL11.glTranslatef(100.0f, 0.0f, 0.0f); + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE); + + GL11.glPushMatrix(); + GL11.glTranslatef(50.0f, 25.0f, 0.0f); + GL11.glScalef(0.5f, 0.5f, 1.0f); + + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex3f(0.0f, 0.0f, 0.0f); + GL11.glVertex3f(16.0f, 0.0f, 0.0f); + GL11.glVertex3f(16.0f, 16.0f, 0.0f); + GL11.glVertex3f(0.0f, 16.0f, 0.0f); + GL11.glEnd(); + + GL11.glPopMatrix(); + GL11.glEndList(); + + final FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); + assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix unchanged"); + + GL11.glCallList(testList); + + final FloatBuffer afterPlayback = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlayback); + assertEquals(100.0f, afterPlayback.get(12), 0.001f, "After playback: base position preserved"); + assertEquals(1.0f, afterPlayback.get(0), 0.001f, "After playback: no scale (popped)"); + + GL11.glLoadIdentity(); + } + + @Test + void rawGL_compileAndExecute_immediateModeExecutesImmediately() { + GL11.glLoadIdentity(); + + testList = GL11.glGenLists(1); + GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); + + GL11.glScalef(0.5f, 0.5f, 0.5f); + + final FloatBuffer during = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); + assertEquals(0.5f, during.get(0), 0.001f, "During COMPILE_AND_EXECUTE: scale applied"); + + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex3f(0.0f, 0.0f, 0.0f); + GL11.glVertex3f(1.0f, 0.0f, 0.0f); + GL11.glVertex3f(1.0f, 1.0f, 0.0f); + GL11.glVertex3f(0.0f, 1.0f, 0.0f); + GL11.glEnd(); + + GL11.glEndList(); + + final FloatBuffer after = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, after); + assertEquals(0.5f, after.get(0), 0.001f, "After COMPILE_AND_EXECUTE: scale remains"); + + GL11.glLoadIdentity(); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java index 2e5a5aae9..8529fbd7f 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica.glsm; +import java.util.HashSet; +import java.util.Set; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -181,7 +183,7 @@ class DisplayListIdAllocatorTest { void noDoubleAllocation() { DisplayListIDAllocator alloc = new DisplayListIDAllocator(); // Allocate many IDs and verify uniqueness - java.util.Set seen = new java.util.HashSet<>(); + Set seen = new HashSet<>(); for (int i = 0; i < 500; i++) { int id = alloc.allocRange(1); assertTrue(seen.add(id), "Duplicate ID returned: " + id); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESCapsTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESCapsTest.java new file mode 100644 index 000000000..c3b875e39 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESCapsTest.java @@ -0,0 +1,84 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL32; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GLESCapsTest { + + private static final int[] DESKTOP_ONLY = { + GL11.GL_LINE_SMOOTH, + GL11.GL_POLYGON_SMOOTH, + GL13.GL_MULTISAMPLE, + GL13.GL_SAMPLE_ALPHA_TO_ONE, + GL11.GL_COLOR_LOGIC_OP, + GL11.GL_POLYGON_OFFSET_POINT, + GL11.GL_POLYGON_OFFSET_LINE, + GL20.GL_VERTEX_PROGRAM_POINT_SIZE, + GL30.GL_FRAMEBUFFER_SRGB, + GL31.GL_PRIMITIVE_RESTART, + GL32.GL_DEPTH_CLAMP, + }; + + private static final int[] VALID_ON_GLES = { + GL11.GL_BLEND, + GL11.GL_DEPTH_TEST, + GL11.GL_CULL_FACE, + GL11.GL_SCISSOR_TEST, + GL11.GL_STENCIL_TEST, + GL11.GL_DITHER, + GL11.GL_POLYGON_OFFSET_FILL, + GL13.GL_SAMPLE_COVERAGE, + GL13.GL_SAMPLE_ALPHA_TO_COVERAGE, + }; + + private static boolean onGles(int cap) { + return GLESCaps.isCapAllowed(cap, true, true); + } + + @Test + void desktopOnlyCapsAreSuppressedOnGles() { + for (int cap : DESKTOP_ONLY) { + assertFalse(onGles(cap), () -> "cap 0x" + Integer.toHexString(cap) + " raises GL_INVALID_ENUM on a GLES context and must not reach the driver"); + } + } + + @Test + void capsValidOnGlesStillReachTheDriver() { + for (int cap : VALID_ON_GLES) { + assertTrue(onGles(cap), () -> "cap 0x" + Integer.toHexString(cap) + " is legal on GLES 3.2 and suppressing it would break rendering"); + } + } + + @Test + void desktopContextAllowsEveryCap() { + for (int cap : DESKTOP_ONLY) { + assertTrue(GLESCaps.isCapAllowed(cap, false, false), () -> "cap 0x" + Integer.toHexString(cap) + " is legal on desktop core and the gate must never suppress it there"); + } + for (int cap : VALID_ON_GLES) { + assertTrue(GLESCaps.isCapAllowed(cap, false, false)); + } + } + + @Test + void clipPlanesFollowClipCullDistance() { + for (int i = 0; i < GLStateManager.MAX_CLIP_PLANES; i++) { + final int cap = GL11.GL_CLIP_PLANE0 + i; + assertTrue(GLESCaps.isCapAllowed(cap, true, true), () -> "clip plane " + cap + " works where EXT_clip_cull_distance is present and must not be suppressed"); + assertFalse(GLESCaps.isCapAllowed(cap, true, false), () -> "clip plane " + cap + " is invalid on GLES without EXT_clip_cull_distance"); + } + } + + @Test + void capsOutsideTheClipPlaneRangeAreUnaffectedByClipCullDistance() { + assertTrue(GLESCaps.isCapAllowed(GL11.GL_BLEND, true, false)); + assertTrue(GLESCaps.isCapAllowed(GL11.GL_CLIP_PLANE0 + GLStateManager.MAX_CLIP_PLANES, true, false)); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemapTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemapTest.java new file mode 100644 index 000000000..2f45a8038 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLESFormatRemapTest.java @@ -0,0 +1,107 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GLESFormatRemapTest { + + private static GLESFormatRemap.Result remap(int internal, int format, int type) { + return GLESFormatRemap.apply(internal, format, type, /* isGLES = */ true); + } + + private static GLESFormatRemap.Result remapDesktop(int internal, int format, int type) { + return GLESFormatRemap.apply(internal, format, type, /* isGLES = */ false); + } + + @Test + void alphaSizedFormatsPromoteToRgba_onBothDesktopAndGles() { + assertEquals(GL11.GL_RGBA4, remap(GL11.GL_ALPHA4, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).internalFormat()); + assertEquals(GL11.GL_RGBA8, remap(GL11.GL_ALPHA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).internalFormat()); + assertEquals(GL11.GL_RGBA4, remapDesktop(GL11.GL_ALPHA4, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).internalFormat()); + } + + @Test + void rgb16AndRgba16_remapToHalfFloat_onGles() { + final var r1 = remap(GL11.GL_RGB16, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE); + assertEquals(GL30.GL_RGB16F, r1.internalFormat()); + assertEquals(GL30.GL_HALF_FLOAT, r1.type()); + + final var r2 = remap(GL11.GL_RGBA16, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE); + assertEquals(GL30.GL_RGBA16F, r2.internalFormat()); + assertEquals(GL30.GL_HALF_FLOAT, r2.type()); + } + + @Test + void rgb16AndRgba16_passThroughUntouched_onDesktop() { + final var r = remapDesktop(GL11.GL_RGB16, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE); + assertEquals(GL11.GL_RGB16, r.internalFormat()); + assertEquals(GL11.GL_UNSIGNED_BYTE, r.type()); + } + + @Test + void halfFloatInternalFormats_getHalfFloatType() { + assertEquals(GL30.GL_HALF_FLOAT, remap(GL30.GL_R16F, GL11.GL_RED, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL30.GL_HALF_FLOAT, remap(GL30.GL_RG16F, GL30.GL_RG, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL30.GL_HALF_FLOAT, remap(GL30.GL_RGB16F, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL30.GL_HALF_FLOAT, remap(GL30.GL_RGBA16F, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).type()); + } + + @Test + void floatInternalFormats_getFloatType() { + assertEquals(GL11.GL_FLOAT, remap(GL30.GL_RGBA32F, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL11.GL_FLOAT, remap(GL30.GL_RGB32F, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE).type()); + } + + @Test + void snormInternalFormats_getByteType() { + assertEquals(GL11.GL_BYTE, remap(GL31.GL_RGBA8_SNORM, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL11.GL_BYTE, remap(GL31.GL_RGB8_SNORM, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE).type()); + } + + @Test + void r11fG11fB10f_getsHalfFloatType() { + final var r = remap(GL30.GL_R11F_G11F_B10F, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE); + assertEquals(GL30.GL_R11F_G11F_B10F, r.internalFormat()); // not remapped + assertEquals(GL30.GL_HALF_FLOAT, r.type()); + } + + @Test + void rgb10A2_getsPackedType() { + final var r = remap(GL11.GL_RGB10_A2, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE); + assertEquals(GL12.GL_UNSIGNED_INT_2_10_10_10_REV, r.type()); + } + + @Test + void depthFormats_getMatchingType() { + assertEquals(GL11.GL_UNSIGNED_INT, remap(GL14.GL_DEPTH_COMPONENT24, GL11.GL_DEPTH_COMPONENT, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL11.GL_FLOAT, remap(GL30.GL_DEPTH_COMPONENT32F, GL11.GL_DEPTH_COMPONENT, GL11.GL_UNSIGNED_BYTE).type()); + assertEquals(GL30.GL_UNSIGNED_INT_24_8, remap(GL30.GL_DEPTH24_STENCIL8, GL30.GL_DEPTH_STENCIL, GL11.GL_UNSIGNED_BYTE).type()); + } + + @Test + void alreadyValidType_isLeftAlone() { + final var r = remap(GL30.GL_RGBA16F, GL11.GL_RGBA, GL30.GL_HALF_FLOAT); + assertEquals(GL30.GL_HALF_FLOAT, r.type()); + } + + @Test + void packedArgb_remapsToUnsignedByte_onGles() { + final var r = remap(GL11.GL_RGBA8, GL11.GL_RGBA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV); + assertEquals(GL11.GL_UNSIGNED_BYTE, r.type()); + + final var r2 = remap(GL11.GL_RGBA8, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV); + assertEquals(GL11.GL_UNSIGNED_BYTE, r2.type()); + } + + @Test + void packedArgb_untouched_onDesktop() { + final var r = remapDesktop(GL11.GL_RGBA8, GL11.GL_RGBA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV); + assertEquals(GL12.GL_UNSIGNED_INT_8_8_8_8_REV, r.type()); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DirtyTracking_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DirtyTracking_UnitTest.java index 700a22eb4..914444ffc 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DirtyTracking_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DirtyTracking_UnitTest.java @@ -32,37 +32,37 @@ public class GLSM_DirtyTracking_UnitTest { void materialBumpsOnlyOnChange() { newf4b(0.1F, 0.2F, 0.3F, 0.4F); GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, f4b); - final int gen = GLStateManager.lightingGeneration; + final int gen = GLStateManager.getLightingGeneration(); newf4b(0.1F, 0.2F, 0.3F, 0.4F); GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, f4b); - assertEquals(gen, GLStateManager.lightingGeneration, "identical material must not bump lightingGeneration"); + assertEquals(gen, GLStateManager.getLightingGeneration(), "identical material must not bump lightingGeneration"); newf4b(0.9F, 0.2F, 0.3F, 0.4F); GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, f4b); - assertEquals(gen + 1, GLStateManager.lightingGeneration, "changed material must bump lightingGeneration once"); + assertEquals(gen + 1, GLStateManager.getLightingGeneration(), "changed material must bump lightingGeneration once"); } @Test void lightModelBumpsOnlyOnChange() { newf4b(0.5F, 0.5F, 0.5F, 1.0F); GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, f4b); - final int gen = GLStateManager.lightingGeneration; + final int gen = GLStateManager.getLightingGeneration(); newf4b(0.5F, 0.5F, 0.5F, 1.0F); GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, f4b); - assertEquals(gen, GLStateManager.lightingGeneration, "identical light model ambient must not bump"); + assertEquals(gen, GLStateManager.getLightingGeneration(), "identical light model ambient must not bump"); } @Test void lightColorBumpsOnlyOnChange() { newf4b(0.25F, 0.5F, 0.75F, 1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, f4b); - final int gen = GLStateManager.lightingGeneration; + final int gen = GLStateManager.getLightingGeneration(); newf4b(0.25F, 0.5F, 0.75F, 1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, f4b); - assertEquals(gen, GLStateManager.lightingGeneration, "identical light diffuse must not bump"); + assertEquals(gen, GLStateManager.getLightingGeneration(), "identical light diffuse must not bump"); } @Test @@ -74,16 +74,16 @@ public class GLSM_DirtyTracking_UnitTest { newf4b(0.1F, 0.2F, 0.3F, 1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, f4b); - final int gen = GLStateManager.lightingGeneration; + final int gen = GLStateManager.getLightingGeneration(); newf4b(0.1F, 0.2F, 0.3F, 1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, f4b); - assertEquals(gen, GLStateManager.lightingGeneration, "same position under same modelview must not bump"); + assertEquals(gen, GLStateManager.getLightingGeneration(), "same position under same modelview must not bump"); GLStateManager.glTranslatef(5.0F, 0.0F, 0.0F); newf4b(0.1F, 0.2F, 0.3F, 1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, f4b); - assertEquals(gen + 1, GLStateManager.lightingGeneration, "same raw position under changed modelview must bump"); + assertEquals(gen + 1, GLStateManager.getLightingGeneration(), "same raw position under changed modelview must bump"); GLStateManager.glPopMatrix(); } @@ -93,19 +93,19 @@ public class GLSM_DirtyTracking_UnitTest { GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); GLStateManager.glPushMatrix(); - final int mv = GLStateManager.mvGeneration; - final int lin = GLStateManager.mvLinearGeneration; + final int mv = GLStateManager.getMvGeneration(); + final int lin = GLStateManager.getMvLinearGeneration(); GLStateManager.glTranslatef(1.0F, 2.0F, 3.0F); - assertEquals(mv + 1, GLStateManager.mvGeneration, "translate must bump mvGeneration"); - assertEquals(lin, GLStateManager.mvLinearGeneration, "translate must NOT bump mvLinearGeneration"); + assertEquals(mv + 1, GLStateManager.getMvGeneration(), "translate must bump mvGeneration"); + assertEquals(lin, GLStateManager.getMvLinearGeneration(), "translate must NOT bump mvLinearGeneration"); GLStateManager.glRotatef(30.0F, 0.0F, 1.0F, 0.0F); - assertEquals(mv + 2, GLStateManager.mvGeneration, "rotate must bump mvGeneration"); - assertEquals(lin + 1, GLStateManager.mvLinearGeneration, "rotate must bump mvLinearGeneration"); + assertEquals(mv + 2, GLStateManager.getMvGeneration(), "rotate must bump mvGeneration"); + assertEquals(lin + 1, GLStateManager.getMvLinearGeneration(), "rotate must bump mvLinearGeneration"); GLStateManager.glScalef(2.0F, 2.0F, 2.0F); - assertEquals(lin + 2, GLStateManager.mvLinearGeneration, "scale must bump mvLinearGeneration"); + assertEquals(lin + 2, GLStateManager.getMvLinearGeneration(), "scale must bump mvLinearGeneration"); GLStateManager.glPopMatrix(); } @@ -113,13 +113,13 @@ public class GLSM_DirtyTracking_UnitTest { @Test void fogBumpsOnlyOnChange() { GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 0.5F); - final int gen = GLStateManager.fragmentGeneration; + final int gen = GLStateManager.getFragmentGeneration(); GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 0.5F); - assertEquals(gen, GLStateManager.fragmentGeneration, "identical fog density must not bump fragmentGeneration"); + assertEquals(gen, GLStateManager.getFragmentGeneration(), "identical fog density must not bump fragmentGeneration"); GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 0.7F); - assertEquals(gen + 1, GLStateManager.fragmentGeneration, "changed fog density must bump fragmentGeneration"); + assertEquals(gen + 1, GLStateManager.getFragmentGeneration(), "changed fog density must bump fragmentGeneration"); } @Test @@ -130,17 +130,17 @@ public class GLSM_DirtyTracking_UnitTest { newf3b(0.0F, 0.0F, -1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, f3b); - final int gen = GLStateManager.lightingGeneration; + final int gen = GLStateManager.getLightingGeneration(); GLStateManager.glTranslatef(5.0F, 0.0F, 0.0F); newf3b(0.0F, 0.0F, -1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, f3b); - assertEquals(gen, GLStateManager.lightingGeneration, "spot direction under translation-only must not bump"); + assertEquals(gen, GLStateManager.getLightingGeneration(), "spot direction under translation-only must not bump"); GLStateManager.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); newf3b(0.0F, 0.0F, -1.0F); GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, f3b); - assertEquals(gen + 1, GLStateManager.lightingGeneration, "same raw spot direction under changed 3x3 must bump"); + assertEquals(gen + 1, GLStateManager.getLightingGeneration(), "same raw spot direction under changed 3x3 must bump"); GLStateManager.glPopMatrix(); } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_GLU_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_GLU_UnitTest.java index 9bd76c66f..221b64534 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_GLU_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_GLU_UnitTest.java @@ -1,13 +1,17 @@ package com.gtnewhorizons.angelica.glsm; import org.joml.Matrix4f; +import org.joml.Vector4f; import org.junit.jupiter.api.Test; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; +import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -203,4 +207,112 @@ public class GLSM_GLU_UnitTest { GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); } + + @Test + void gluErrorString_glErrors() { + assertEquals("No error", GLStateManager.gluErrorString(GL11.GL_NO_ERROR)); + assertEquals("Invalid enum", GLStateManager.gluErrorString(GL11.GL_INVALID_ENUM)); + assertEquals("Invalid value", GLStateManager.gluErrorString(GL11.GL_INVALID_VALUE)); + assertEquals("Invalid operation", GLStateManager.gluErrorString(GL11.GL_INVALID_OPERATION)); + assertEquals("Out of memory", GLStateManager.gluErrorString(GL11.GL_OUT_OF_MEMORY)); + } + + @Test + void gluErrorString_gluErrors() { + assertEquals("Invalid enum (glu)", GLStateManager.gluErrorString(100900)); + assertEquals("Invalid value (glu)", GLStateManager.gluErrorString(100901)); + assertEquals("Out of memory (glu)", GLStateManager.gluErrorString(100902)); + } + + @Test + void gluErrorString_unknownCode() { + assertEquals("Unknown error: 99999", GLStateManager.gluErrorString(99999)); + } + + @Test + void gluUnProject_identity() { + FloatBuffer model = BufferUtils.createFloatBuffer(16); + FloatBuffer proj = BufferUtils.createFloatBuffer(16); + new Matrix4f().get(model); + new Matrix4f().get(proj); + + IntBuffer viewport = BufferUtils.createIntBuffer(4); + viewport.put(0, 0).put(1, 0).put(2, 800).put(3, 600); + + FloatBuffer result = BufferUtils.createFloatBuffer(3); + boolean ok = GLStateManager.gluUnProject(400.0f, 300.0f, 0.5f, model, proj, viewport, result); + assertTrue(ok, "gluUnProject should succeed"); + assertEquals(0.0f, result.get(0), 0.001f, "X"); + assertEquals(0.0f, result.get(1), 0.001f, "Y"); + assertEquals(0.0f, result.get(2), 0.001f, "Z"); + } + + @Test + void gluUnProject_withPerspective() { + Matrix4f proj = new Matrix4f().perspective((float) Math.toRadians(60.0f), 800.0f / 600.0f, 0.1f, 100.0f); + Matrix4f model = new Matrix4f().lookAt(0, 0, 5, 0, 0, 0, 0, 1, 0); + + Vector4f worldPt = new Vector4f(0, 0, 0, 1); + Matrix4f mvp = new Matrix4f(proj).mul(model); + mvp.transform(worldPt); + float ndcX = worldPt.x / worldPt.w; + float ndcY = worldPt.y / worldPt.w; + float ndcZ = worldPt.z / worldPt.w; + float winX = (ndcX * 0.5f + 0.5f) * 800.0f; + float winY = (ndcY * 0.5f + 0.5f) * 600.0f; + float winZ = ndcZ * 0.5f + 0.5f; + + FloatBuffer modelBuf = BufferUtils.createFloatBuffer(16); + FloatBuffer projBuf = BufferUtils.createFloatBuffer(16); + model.get(modelBuf); + proj.get(projBuf); + + IntBuffer viewport = BufferUtils.createIntBuffer(4); + viewport.put(0, 0).put(1, 0).put(2, 800).put(3, 600); + + FloatBuffer result = BufferUtils.createFloatBuffer(3); + boolean ok = GLStateManager.gluUnProject(winX, winY, winZ, modelBuf, projBuf, viewport, result); + assertTrue(ok, "gluUnProject should succeed"); + assertEquals(0.0f, result.get(0), 0.01f, "X should unproject back to 0"); + assertEquals(0.0f, result.get(1), 0.01f, "Y should unproject back to 0"); + assertEquals(0.0f, result.get(2), 0.01f, "Z should unproject back to 0"); + } + + @Test + void gluUnProject_singularMatrix() { + FloatBuffer model = BufferUtils.createFloatBuffer(16); + FloatBuffer proj = BufferUtils.createFloatBuffer(16); + for (int i = 0; i < 16; i++) { + model.put(i, 0.0f); + proj.put(i, 0.0f); + } + + IntBuffer viewport = BufferUtils.createIntBuffer(4); + viewport.put(0, 0).put(1, 0).put(2, 800).put(3, 600); + + FloatBuffer result = BufferUtils.createFloatBuffer(3); + assertFalse(GLStateManager.gluUnProject(400, 300, 0.5f, model, proj, viewport, result)); + } + + + @Test + void gluBuild2DMipmaps_invalidSize() { + assertEquals(100901, GLStateManager.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, GL11.GL_RGBA, 0, 10, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, BufferUtils.createByteBuffer(1))); + assertEquals(100901, GLStateManager.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, GL11.GL_RGBA, 10, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, BufferUtils.createByteBuffer(1))); + } + + @Test + void gluBuild2DMipmaps_uploadsTexture() { + int texId = GL11.glGenTextures(); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId); + + ByteBuffer pixels = BufferUtils.createByteBuffer(4 * 4 * 4); + for (int i = 0; i < 4 * 4 * 4; i++) pixels.put((byte) 0xFF); + pixels.flip(); + + int result = GLStateManager.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, GL11.GL_RGBA, 4, 4, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + assertEquals(0, result, "gluBuild2DMipmaps should return 0 on success"); + + GL11.glDeleteTextures(texId); + } } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ImageUnitBindingCache_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ImageUnitBindingCache_UnitTest.java new file mode 100644 index 000000000..f526fe82a --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ImageUnitBindingCache_UnitTest.java @@ -0,0 +1,170 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.glsm.states.ImageUnitBinding; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL42; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@GLCoreTest +public class GLSM_ImageUnitBindingCache_UnitTest { + + private static void drainErrors() { + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + } + + private static void unbind(int unit) { + GLStateManager.glBindImageTexture(unit, 0, 0, false, 0, GL15.GL_READ_ONLY, 0); + } + + @Test + void bindThenQueryReturnsFullTuple() { + drainErrors(); + final int tex = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(2, tex, 1, false, 3, GL15.GL_READ_ONLY, GL30.GL_RGBA32UI); + + assertEquals(tex, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 2)); + assertEquals(1, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LEVEL, 2)); + assertEquals(GL11.GL_FALSE, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LAYERED, 2)); + assertEquals(3, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LAYER, 2)); + assertEquals(GL15.GL_READ_ONLY, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_ACCESS, 2)); + assertEquals(GL30.GL_RGBA32UI, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_FORMAT, 2)); + } finally { + unbind(2); + GLStateManager.glDeleteTextures(tex); + drainErrors(); + } + } + + @Test + void saveRestoreRoundTripsTheWholeTuple() { + drainErrors(); + final int a = GL11.glGenTextures(); + final int b = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(0, a, 2, true, 0, GL15.GL_READ_WRITE, GL30.GL_R32UI); + final ImageUnitBinding live = GLStateManager.getImageUnitBinding(0); + assertNotNull(live); + final ImageUnitBinding saved = live.copy(); + + GLStateManager.glBindImageTexture(0, b, 0, true, 0, GL15.GL_WRITE_ONLY, 0); + assertEquals(b, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 0)); + + GLStateManager.glBindImageTexture(0, saved.getTexture(), saved.getLevel(), saved.isLayered(), saved.getLayer(), saved.getAccess(), saved.getFormat()); + + assertTrue(saved.sameAs(GLStateManager.getImageUnitBinding(0)), "restore must reproduce every field"); + assertEquals(a, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 0)); + assertEquals(2, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LEVEL, 0)); + assertEquals(GL15.GL_READ_WRITE, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_ACCESS, 0)); + } finally { + unbind(0); + GLStateManager.glDeleteTextures(a); + GLStateManager.glDeleteTextures(b); + drainErrors(); + } + } + + @Test + void resetToZeroIsNotARestore() { + drainErrors(); + final int tex = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(0, tex, 1, true, 0, GL15.GL_READ_WRITE, GL30.GL_R32UI); + GLStateManager.glBindImageTexture(0, 0, 0, true, 0, GL15.GL_WRITE_ONLY, 0); + + assertEquals(0, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 0)); + assertEquals(0, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LEVEL, 0)); + } finally { + unbind(0); + GLStateManager.glDeleteTextures(tex); + drainErrors(); + } + } + + @Test + void deletingTheBoundTextureClearsTheImageUnit() { + drainErrors(); + final int tex = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(1, tex, 0, true, 0, GL15.GL_READ_WRITE, GL30.GL_R32UI); + assertEquals(tex, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 1)); + + GLStateManager.glDeleteTextures(tex); + assertEquals(0, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 1), "GL unbinds a deleted texture from every image unit"); + } finally { + unbind(1); + drainErrors(); + } + } + + @Test + void unitsAreIndependentAndUnitZeroIsNotSpecial() { + drainErrors(); + final int a = GL11.glGenTextures(); + final int b = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(0, a, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + GLStateManager.glBindImageTexture(3, b, 1, false, 2, GL15.GL_WRITE_ONLY, GL30.GL_RGBA32UI); + + assertEquals(a, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 0)); + assertEquals(b, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 3)); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LAYERED, 0)); + assertEquals(GL11.GL_FALSE, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_LAYERED, 3)); + } finally { + unbind(0); + unbind(3); + GLStateManager.glDeleteTextures(a); + GLStateManager.glDeleteTextures(b); + drainErrors(); + } + } + + @Test + void outOfRangeUnitDoesNotCorruptNeighbours() { + drainErrors(); + final int tex = GL11.glGenTextures(); + try { + GLStateManager.glBindImageTexture(0, tex, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + final int beyond = GLStateManager.getImageUnitBinding(0) == null ? 0 : Integer.MAX_VALUE - 1; + assertFalse(beyond == 0, "unit 0 must resolve for this test to mean anything"); + + GLStateManager.glBindImageTexture(beyond, tex, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + assertEquals(tex, GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 0)); + } finally { + unbind(0); + GLStateManager.glDeleteTextures(tex); + drainErrors(); + } + } + + @Test + void driverAgreesWhenAvailable() { + assumeTrue(GLStateManager.capabilities != null && GLStateManager.capabilities.OpenGL42, "no GL 4.2 image load/store on this context"); + drainErrors(); + final int tex = GL11.glGenTextures(); + try { + GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex); + GL42.glTexStorage2D(GL11.GL_TEXTURE_2D, 1, GL30.GL_R32UI, 4, 4); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + + GLStateManager.glBindImageTexture(1, tex, 0, false, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + drainErrors(); + + assertEquals(GL30.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 1), GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_NAME, 1)); + assertEquals(GL30.glGetInteger(GL42.GL_IMAGE_BINDING_ACCESS, 1), GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_ACCESS, 1)); + assertEquals(GL30.glGetInteger(GL42.GL_IMAGE_BINDING_FORMAT, 1), GLStateManager.glGetInteger(GL42.GL_IMAGE_BINDING_FORMAT, 1)); + } finally { + unbind(1); + GLStateManager.glDeleteTextures(tex); + drainErrors(); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MaxBoundTextureUnit_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MaxBoundTextureUnit_UnitTest.java new file mode 100644 index 000000000..a317c4f18 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MaxBoundTextureUnit_UnitTest.java @@ -0,0 +1,36 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import static org.junit.jupiter.api.Assertions.*; + +@GLCompatTest +public class GLSM_MaxBoundTextureUnit_UnitTest { + + @Test + void testHighWaterMarkTracksNonZeroBindsOnly() { + final int texId = GL11.glGenTextures(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE5); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + assertTrue(GLStateManager.getMaxBoundTextureUnit() >= 5); + + final int before = GLStateManager.getMaxBoundTextureUnit(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + before + 3); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + assertEquals(before, GLStateManager.getMaxBoundTextureUnit(), "binding 0 must not raise the mark"); + + GLStateManager.trackMaxBoundTextureUnit(before + 7); + assertEquals(before + 7, GLStateManager.getMaxBoundTextureUnit()); + GLStateManager.trackMaxBoundTextureUnit(0); + assertEquals(before + 7, GLStateManager.getMaxBoundTextureUnit(), "mark is monotonic"); + } finally { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE5); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GL11.glDeleteTextures(texId); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PerThread_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PerThread_UnitTest.java new file mode 100644 index 000000000..287e039c6 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PerThread_UnitTest.java @@ -0,0 +1,162 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +public class GLSM_PerThread_UnitTest { + + private static void runThreaded(int n, ThreadBody body) throws Throwable { + final CyclicBarrier barrier = new CyclicBarrier(n); + final Throwable[] errs = new Throwable[n]; + final Thread[] ts = new Thread[n]; + for (int i = 0; i < n; i++) { + final int tid = i; + ts[i] = new Thread(() -> { + try { + body.run(tid, barrier); + } catch (Throwable t) { + errs[tid] = t; + } + }, "glsm-perthread-" + i); + } + for (Thread t : ts) t.start(); + for (Thread t : ts) t.join(); + for (int i = 0; i < n; i++) if (errs[i] != null) throw errs[i]; + } + + interface ThreadBody { + void run(int tid, CyclicBarrier barrier) throws Exception; + } + + @Test + void holdersAreDistinctPerThreadAndDoNotBleed() throws Throwable { + final int n = 6; + final GLContextState mainHolder = GLStateManager.ctx(); + final GLContextState[] holders = new GLContextState[n]; + + runThreaded(n, (tid, barrier) -> { + final GLContextState c = GLStateManager.enterWorkerContext(); + try { + holders[tid] = c; + assertSame(c, GLStateManager.ctx(), "ctx() must be stable within a worker thread"); + assertNotSame(mainHolder, c, "worker holder must differ from the primary (main-thread) holder"); + + c.activeProgram = 1000 + tid; + c.boundVBO = 2000 + tid; + c.mvGeneration = 3000 + tid; + c.savedMvGen[0] = 4000 + tid; + c.activeTextureUnit.setValue(tid); + + barrier.await(); + + assertEquals(1000 + tid, c.activeProgram, "activeProgram bled across threads"); + assertEquals(2000 + tid, c.boundVBO, "boundVBO bled across threads"); + assertEquals(3000 + tid, c.mvGeneration, "mvGeneration bled across threads"); + assertEquals(4000 + tid, c.savedMvGen[0], "savedMvGen bled across threads"); + assertEquals(tid, c.activeTextureUnit.getValue(), "activeTextureUnit stack bled across threads"); + } finally { + GLStateManager.exitWorkerContext(); + } + }); + + final Set distinct = Collections.newSetFromMap(new IdentityHashMap<>()); + distinct.add(mainHolder); + for (GLContextState h : holders) distinct.add(h); + assertEquals(n + 1, distinct.size(), "every thread must own a distinct holder"); + } + + @Test + void matrixStackAndMvGenerationArePerThread() throws Throwable { + final int n = 6; + runThreaded(n, (tid, barrier) -> { + GLStateManager.enterWorkerContext(); + try { + final int count = tid + 1; + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + final int gen0 = GLStateManager.getMvGeneration(); + + for (int k = 0; k < count; k++) GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); + + barrier.await(); + + assertEquals(gen0 + count, GLStateManager.getMvGeneration(), "mvGeneration must advance only by this thread's own translate count"); + final Matrix4f m = new Matrix4f(GLStateManager.getModelViewMatrix()); + assertEquals((float) count, m.m30(), 1e-6f, "accumulated X translation must reflect only this thread's ops"); + } finally { + GLStateManager.exitWorkerContext(); + } + }); + } + + @Test + void pushPopMatrixBalancesPerThread() throws Throwable { + final int n = 4; + runThreaded(n, (tid, barrier) -> { + GLStateManager.enterWorkerContext(); + try { + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glPushMatrix(); + GLStateManager.glTranslatef(5.0f + tid, 0.0f, 0.0f); + assertEquals(5.0f + tid, new Matrix4f(GLStateManager.getModelViewMatrix()).m30(), 1e-6f, "translation must apply within the pushed scope"); + barrier.await(); + GLStateManager.glPopMatrix(); + assertEquals(0.0f, new Matrix4f(GLStateManager.getModelViewMatrix()).m30(), 1e-6f, "pop must restore this thread's matrix independent of other threads"); + } finally { + GLStateManager.exitWorkerContext(); + } + }); + } + + @Test + void globalImmutableStateIdenticalAcrossThreads() throws Throwable { + final int n = 6; + final int units = GLStateManager.MAX_TEXTURE_UNITS; + final Thread mainThread = GLStateManager.getMainThread(); + runThreaded(n, (tid, barrier) -> { + assertEquals(units, GLStateManager.MAX_TEXTURE_UNITS, "limits must be global-immutable"); + assertSame(mainThread, GLStateManager.getMainThread(), "MainThread must be global-immutable"); + }); + } + + @Test + void concurrentGetterSetterAndPushPopStress() throws Throwable { + final int n = 8; + final int iterations = 20_000; + final AtomicInteger mismatches = new AtomicInteger(); + runThreaded(n, (tid, barrier) -> { + final GLContextState c = GLStateManager.enterWorkerContext(); + try { + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + barrier.await(); + for (int i = 0; i < iterations; i++) { + c.activeProgram = tid; + GLStateManager.glPushMatrix(); + GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); + GLStateManager.glPopMatrix(); + if (GLStateManager.getActiveProgram() != tid) mismatches.incrementAndGet(); + if (c.activeProgram != tid) mismatches.incrementAndGet(); + } + assertEquals(0.0f, new Matrix4f(GLStateManager.getModelViewMatrix()).m30(), 1e-6f, "balanced push/pop must leave this thread's matrix at identity"); + } finally { + GLStateManager.exitWorkerContext(); + } + }); + assertTrue(mismatches.get() == 0, "cross-thread state bleed detected under contention: " + mismatches.get()); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PolygonOffsetClamp_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PolygonOffsetClamp_UnitTest.java new file mode 100644 index 000000000..bba6a3985 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PolygonOffsetClamp_UnitTest.java @@ -0,0 +1,43 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +public class GLSM_PolygonOffsetClamp_UnitTest { + + @AfterEach + void reset() { + GLStateManager.glPolygonOffset(0.0f, 0.0f); + } + + private static float cachedClamp() { + return GLStateManager.ctx().polygonState.getOffsetClamp(); + } + + @Test + void zeroClampTakesThePlainPath() { + GLStateManager.glPolygonOffsetClamp(1.5f, 2.5f, 0.0f); + assertEquals(1.5f, GLStateManager.ctx().polygonState.getOffsetFactor()); + assertEquals(2.5f, GLStateManager.ctx().polygonState.getOffsetUnits()); + assertEquals(0.0f, cachedClamp()); + } + + @Test + void plainOffsetClearsTheCachedClamp() { + GLStateManager.ctx().polygonState.setOffsetClamp(0.25f); + GLStateManager.glPolygonOffset(1.0f, 1.0f); + assertEquals(0.0f, cachedClamp()); + } + + @Test + void nonZeroClampFailsByNameOnTheGLBackend() { + final UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> GLStateManager.glPolygonOffsetClamp(1.0f, 1.0f, 0.5f)); + assertTrue(e.getMessage().contains("polygon offset clamp"), e::getMessage); + assertTrue(e.getMessage().indexOf(':') > 0, () -> "message must name the backend: " + e.getMessage()); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java index d799766d7..72c9251dd 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java @@ -1179,4 +1179,30 @@ class GLSM_PushPop_UnitTest { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "Active Texture - Reset"); } + + @Test + void testUntouchedPushPopRoundTripLeavesStateIdentical() { + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GLStateManager.glLineWidth(3.0f); + GLStateManager.glViewport(2, 2, 640, 480); + GLStateManager.glCullFace(GL11.GL_FRONT); + + GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GLStateManager.glPopAttrib(); + + verifyState(GL11.GL_DEPTH_FUNC, GL11.GL_LEQUAL, "Depth Func - untouched round trip"); + verifyState(GL11.GL_BLEND_SRC, GL11.GL_SRC_ALPHA, "Blend Source - untouched round trip"); + verifyState(GL11.GL_BLEND_DST, GL11.GL_ONE_MINUS_SRC_ALPHA, "Blend Destination - untouched round trip"); + verifyState(GL11.GL_LINE_WIDTH, 3.0f, "Line Width - untouched round trip"); + verifyState(GL11.GL_VIEWPORT, new int[] { 2, 2, 640, 480 }, "Viewport - untouched round trip"); + verifyState(GL11.GL_CULL_FACE_MODE, GL11.GL_FRONT, "Cull Face Mode - untouched round trip"); + verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "Active Texture - untouched round trip"); + + GLStateManager.glDepthFunc(GL11.GL_LESS); + GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO); + GLStateManager.glLineWidth(1.0f); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.glCullFace(GL11.GL_BACK); + } } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java index fd8c07856..ba1894f46 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ServerSideState_UnitTest.java @@ -9,7 +9,6 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.SharedDrawable; -import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -40,16 +39,12 @@ public class GLSM_ServerSideState_UnitTest { private volatile boolean shutdownRequested; private boolean originalSplashComplete; - private static void setSplashComplete(boolean value) throws Exception { - final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete"); - splashCompleteField.setAccessible(true); - splashCompleteField.setBoolean(null, value); + private static void setSplashComplete(boolean value) { + SplashWindow.setSplashComplete(value); } - private static boolean getSplashComplete() throws Exception { - final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete"); - splashCompleteField.setAccessible(true); - return splashCompleteField.getBoolean(null); + private static boolean getSplashComplete() { + return SplashWindow.isSplashComplete(); } @BeforeEach @@ -144,7 +139,7 @@ public class GLSM_ServerSideState_UnitTest { GLStateManager.setDrawableGL(null); setSplashComplete(originalSplashComplete); if (originalSplashComplete) { - GLStateManager.markSplashComplete(); + GLStateManager.markSplashComplete("test"); } } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCachingCoverage_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCachingCoverage_UnitTest.java new file mode 100644 index 000000000..26ffef16f --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCachingCoverage_UnitTest.java @@ -0,0 +1,147 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack; +import org.lwjgl.opengl.GL11; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +public class GLSM_SplashCachingCoverage_UnitTest { + + @BeforeEach + void enterSplashWindow() throws IllegalAccessException { + SplashWindow.enter(); + assertFalse(GLStateManager.isCachingEnabled(), "setup must reproduce the caching=false window"); + } + + @AfterEach + void leaveSplashWindow() throws IllegalAccessException { + SplashWindow.leave(); + GLStateManager.glDepthFunc(GL11.GL_LESS); + } + + @Test + void depthFuncSetDuringSplashLandsInCache() { + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + + assertEquals(GL11.GL_LEQUAL, GLStateManager.getDepthState().getFunc(), "cache write dropped while caching=false"); + } + + @Test + void popAttribDoesNotRevertDepthFuncSetDuringSplash() throws IllegalAccessException { + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + + SplashWindow.setSplashComplete(true); + GLStateManager.setDrawableGLHolder(Thread.currentThread()); + + GLStateManager.glPushAttrib(GL11.GL_DEPTH_BUFFER_BIT); + GLStateManager.glPopAttrib(); + + assertEquals(GL11.GL_LEQUAL, GLStateManager.getDepthState().getFunc(), "popAttrib reverted to the stale default"); + } + + @Test + void everyBooleanStateIsCollectedForReplay() throws IllegalAccessException { + final GLContextState ctx = GLStateManager.ctx(); + final Set tracked = Collections.newSetFromMap(new IdentityHashMap<>()); + tracked.addAll(ctx.allBooleanStates); + assertEquals(ctx.allBooleanStates.size(), tracked.size(), "duplicate entries in allBooleanStates"); + + int declared = 0; + for (Field f : GLContextState.class.getDeclaredFields()) { + f.setAccessible(true); + if (f.getType() == BooleanStateStack.class) { + final BooleanStateStack s = (BooleanStateStack) f.get(ctx); + if (s == null) continue; + declared++; + assertTrue(tracked.contains(s), f.getName() + " skipped track() - missing from replay coverage"); + } else if (f.getType() == BooleanStateStack[].class) { + for (BooleanStateStack s : (BooleanStateStack[]) f.get(ctx)) { + if (s == null) continue; + declared++; + assertTrue(tracked.contains(s), f.getName() + " element skipped track() - missing from replay coverage"); + } + } + } + + assertTrue(declared > 0, "no BooleanStateStack fields found - the check is broken"); + assertEquals(declared, ctx.allBooleanStates.size(), "allBooleanStates contains states not declared on GLContextState"); + } + + @Test + void replayPushesCachedStateWithoutDisturbingIt() { + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glCullFace(GL11.GL_FRONT); + + GLStateManager.replayStateToBackend(); + + assertEquals(GL11.GL_LEQUAL, GLStateManager.getDepthState().getFunc(), "replay must not mutate the cache"); + assertEquals(GL11.GL_FRONT, GLStateManager.getPolygonState().getCullFaceMode(), "replay must not mutate the cache"); + } + + @Test + void replayPushesDepthFuncToRealGL() { + assertNotNull(BackendManager.RENDER_BACKEND, "no backend: replay would no-op and this test would pass vacuously"); + + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GL11.glDepthFunc(GL11.GL_LESS); + assertEquals(GL11.GL_LESS, GL11.glGetInteger(GL11.GL_DEPTH_FUNC), "setup failed to diverge real GL"); + + GLStateManager.replayStateToBackend(); + + assertEquals(GL11.GL_LEQUAL, GL11.glGetInteger(GL11.GL_DEPTH_FUNC), "cached depth func never reached real GL; GUI draws at equal depth would be rejected"); + } + + @Test + void firstFrameAfterSplashSeedsRealGL() throws IllegalAccessException { + assertNotNull(BackendManager.RENDER_BACKEND, "no backend: this test would pass vacuously"); + + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GL11.glDepthFunc(GL11.GL_LESS); + + SplashWindow.setSplashComplete(false); + GLStateManager.markSplashComplete("test-seed"); + GLStateManager.setDrawableGLHolder(Thread.currentThread()); + + BackendManager.RENDER_BACKEND.onFrameBegin(); + + assertEquals(GL11.GL_LEQUAL, GL11.glGetInteger(GL11.GL_DEPTH_FUNC), "first frame after splash did not seed cached state into real GL"); + + GL11.glDepthFunc(GL11.GL_LESS); + BackendManager.RENDER_BACKEND.onFrameBegin(); + assertEquals(GL11.GL_LESS, GL11.glGetInteger(GL11.GL_DEPTH_FUNC), "seed re-ran on a later frame; it must fire exactly once"); + } + + @Test + void splashCompleteRequestsSeedOnceAndIssuesNoGLItself() throws IllegalAccessException { + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GL11.glDepthFunc(GL11.GL_LESS); + + SplashWindow.setSplashComplete(false); + GLStateManager.markSplashComplete("test-seed"); + + assertEquals(GL11.GL_LESS, GL11.glGetInteger(GL11.GL_DEPTH_FUNC), "markSplashComplete must only request the seed: releaseContext already dropped the context on that thread"); + assertTrue(GLStateManager.takeStateSeedPending(), "end of splash must request a state seed"); + assertFalse(GLStateManager.takeStateSeedPending(), "seed must be consumed exactly once, not once per frame"); + assertFalse(GLStateManager.takeStateSeedPending(), "seed must stay consumed"); + } + + @Test + void cullFaceSetDuringSplashLandsInCache() { + GLStateManager.glCullFace(GL11.GL_FRONT); + + assertEquals(GL11.GL_FRONT, GLStateManager.getPolygonState().getCullFaceMode(), "cache write dropped while caching=false"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCompleteLatch_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCompleteLatch_UnitTest.java new file mode 100644 index 000000000..4d6e36ebf --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_SplashCompleteLatch_UnitTest.java @@ -0,0 +1,66 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +public class GLSM_SplashCompleteLatch_UnitTest { + + @BeforeEach + void enterSplashWindow() throws IllegalAccessException { + SplashWindow.enter(); + } + + @AfterEach + void leaveSplashWindow() throws IllegalAccessException { + SplashWindow.leave(); + } + + @Test + void markLatchesAndReleasesTheDrawableHolder() { + assertFalse(GLStateManager.isSplashComplete()); + + GLStateManager.markSplashComplete("test"); + + assertTrue(GLStateManager.isSplashComplete()); + assertNull(GLStateManager.getDrawableGLHolder(), "holder must be released so caching stops keying off it"); + } + + @Test + void secondMarkIsANoOp() { + GLStateManager.markSplashComplete("first"); + final Thread reacquired = new Thread("late-holder"); + GLStateManager.setDrawableGLHolder(reacquired); + + GLStateManager.markSplashComplete("second"); + + assertTrue(GLStateManager.isSplashComplete()); + assertSame(reacquired, GLStateManager.getDrawableGLHolder(), "a second mark must not re-run the latch body"); + } + + @Test + void cachingIsThreadScopedBeforeTheLatchAndGlobalAfter() throws Exception { + final AtomicBoolean cachingOffThread = new AtomicBoolean(true); + final Runnable probe = () -> cachingOffThread.set(GLStateManager.isCachingEnabled()); + + Thread t = new Thread(probe, "non-holder"); + t.start(); + t.join(); + assertFalse(cachingOffThread.get(), "caching must be holder-scoped during the dual-context window"); + + GLStateManager.markSplashComplete("test"); + + t = new Thread(probe, "non-holder"); + t.start(); + t.join(); + assertTrue(cachingOffThread.get(), "after the latch caching is global - this is what the latch buys"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateQueryRoundTrip_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateQueryRoundTrip_UnitTest.java new file mode 100644 index 000000000..3e0e527f7 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateQueryRoundTrip_UnitTest.java @@ -0,0 +1,147 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@GLCompatTest +public class GLSM_StateQueryRoundTrip_UnitTest { + + @Test + void activeTextureRoundTrips() { + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE3); + assertEquals(GL13.GL_TEXTURE3, GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE), "must return the GL_TEXTURE# enum, not the unit index"); + assertEquals(GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE), GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + } finally { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + } + + @Test + void invalidTextureUnitIsIgnored() { + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); + + GLStateManager.glActiveTexture(0); + assertEquals(GL13.GL_TEXTURE2, GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + GLStateManager.MAX_TEXTURE_UNITS); + assertEquals(GL13.GL_TEXTURE2, GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + } finally { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + } + + @Test + void depthWriteMaskRoundTripsAsInteger() { + try { + GLStateManager.glDepthMask(false); + assertEquals(GL11.GL_FALSE, GLStateManager.glGetInteger(GL11.GL_DEPTH_WRITEMASK)); + GLStateManager.glDepthMask(true); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetInteger(GL11.GL_DEPTH_WRITEMASK)); + } finally { + GLStateManager.glDepthMask(true); + } + } + + @Test + void cullFaceModeRoundTrips() { + try { + GLStateManager.glCullFace(GL11.GL_FRONT); + assertEquals(GL11.GL_FRONT, GLStateManager.glGetInteger(GL11.GL_CULL_FACE_MODE)); + assertEquals(GL11.glGetInteger(GL11.GL_CULL_FACE_MODE), GLStateManager.glGetInteger(GL11.GL_CULL_FACE_MODE)); + } finally { + GLStateManager.glCullFace(GL11.GL_BACK); + } + } + + @Test + void polygonModeRoundTripsBothFaces() { + try { + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); + assertEquals(GL11.GL_LINE, GLStateManager.glGetInteger(GL11.GL_POLYGON_MODE)); + + final IntBuffer params = BufferUtils.createIntBuffer(2); + GLStateManager.glGetInteger(GL11.GL_POLYGON_MODE, params); + assertEquals(GL11.GL_LINE, params.get(0), "front mode"); + assertEquals(GL11.GL_LINE, params.get(1), "back mode"); + } finally { + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL); + } + } + + @Test + void pixelUnpackStateRoundTrips() { + try { + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 64); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 2); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 3); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); + + assertEquals(64, GLStateManager.glGetInteger(GL11.GL_UNPACK_ROW_LENGTH)); + assertEquals(2, GLStateManager.glGetInteger(GL11.GL_UNPACK_SKIP_PIXELS)); + assertEquals(3, GLStateManager.glGetInteger(GL11.GL_UNPACK_SKIP_ROWS)); + assertEquals(1, GLStateManager.glGetInteger(GL11.GL_UNPACK_ALIGNMENT)); + } finally { + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 4); + } + } + + @Test + void viewportFillsAllFourComponentsViaIntArray() { + GLStateManager.glViewport(3, 5, 17, 23); + + final int[] params = new int[4]; + GLStateManager.glGetInteger(GL11.GL_VIEWPORT, params); + assertEquals(3, params[0]); + assertEquals(5, params[1]); + assertEquals(17, params[2]); + assertEquals(23, params[3]); + } + + @Test + void saveDisturbRestoreIsIdentity() { + final int activeTexture = GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE); + final int depthWriteMask = GLStateManager.glGetInteger(GL11.GL_DEPTH_WRITEMASK); + final int cullMode = GLStateManager.glGetInteger(GL11.GL_CULL_FACE_MODE); + final int polygonMode = GLStateManager.glGetInteger(GL11.GL_POLYGON_MODE); + final int unpackAlignment = GLStateManager.glGetInteger(GL11.GL_UNPACK_ALIGNMENT); + final int[] viewport = new int[4]; + GLStateManager.glGetInteger(GL11.GL_VIEWPORT, viewport); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + 4); + GLStateManager.glDepthMask(false); + GLStateManager.glCullFace(GL11.GL_FRONT_AND_BACK); + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_POINT); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 8); + GLStateManager.glViewport(1, 1, 2, 2); + + GLStateManager.glActiveTexture(activeTexture); + GLStateManager.glDepthMask(depthWriteMask == GL11.GL_TRUE); + GLStateManager.glCullFace(cullMode); + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, polygonMode); + GLStateManager.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, unpackAlignment); + GLStateManager.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + + assertEquals(activeTexture, GLStateManager.glGetInteger(GL13.GL_ACTIVE_TEXTURE)); + assertEquals(depthWriteMask, GLStateManager.glGetInteger(GL11.GL_DEPTH_WRITEMASK)); + assertEquals(cullMode, GLStateManager.glGetInteger(GL11.GL_CULL_FACE_MODE)); + assertEquals(polygonMode, GLStateManager.glGetInteger(GL11.GL_POLYGON_MODE)); + assertEquals(unpackAlignment, GLStateManager.glGetInteger(GL11.GL_UNPACK_ALIGNMENT)); + final int[] restored = new int[4]; + GLStateManager.glGetInteger(GL11.GL_VIEWPORT, restored); + assertEquals(viewport[0], restored[0]); + assertEquals(viewport[1], restored[1]); + assertEquals(viewport[2], restored[2]); + assertEquals(viewport[3], restored[3]); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureBindingTargetCache_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureBindingTargetCache_UnitTest.java new file mode 100644 index 000000000..7aab05c7b --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureBindingTargetCache_UnitTest.java @@ -0,0 +1,88 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@GLCoreTest +public class GLSM_TextureBindingTargetCache_UnitTest { + + private static void drainErrors() { + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + } + + @Test + void flattenedCacheTracksNon2DTargets() { + drainErrors(); + final int t3d = GL11.glGenTextures(); + final int t2d = GL11.glGenTextures(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE3); + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, t3d); + assertEquals(t3d, GLStateManager.getBoundTextureForServerState(3), "cache must track a 3D bind"); + assertEquals(t3d, GL11.glGetInteger(GL12.GL_TEXTURE_BINDING_3D), "3D bind must reach the driver"); + + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, t2d); + assertEquals(t2d, GLStateManager.getBoundTextureForServerState(3), "cache must track the 2D bind after a 3D bind"); + assertEquals(t2d, GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D)); + + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, t3d); + assertEquals(t3d, GLStateManager.getBoundTextureForServerState(3), "cache must track the 3D re-bind"); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); + } finally { + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, 0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDeleteTextures(t3d); + GLStateManager.glDeleteTextures(t2d); + drainErrors(); + } + } + + @Test + void popAttribRestoresRecordedTarget() { + drainErrors(); + final int t3d = GL11.glGenTextures(); + final int t2d = GL11.glGenTextures(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, t3d); + + GLStateManager.glPushAttrib(GL11.GL_TEXTURE_BIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, t2d); + GLStateManager.glPopAttrib(); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "restore must not re-bind a 3D texture as 2D"); + assertEquals(t3d, GLStateManager.getBoundTextureForServerState(2), "cache must restore the pre-push binding"); + assertEquals(t3d, GL11.glGetInteger(GL12.GL_TEXTURE_BINDING_3D), "restore must use the recorded target"); + } finally { + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, 0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDeleteTextures(t3d); + GLStateManager.glDeleteTextures(t2d); + drainErrors(); + } + } + + @Test + void unbindIsNotElidedAcrossTargets() { + drainErrors(); + final int t2d = GL11.glGenTextures(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE4); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, t2d); + GLStateManager.glBindTexture(GL12.GL_TEXTURE_3D, 0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + assertEquals(0, GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D), "2D unbind after a 3D unbind must reach the driver"); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); + } finally { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDeleteTextures(t2d); + drainErrors(); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java index d1f80ca89..ed402192d 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java @@ -10,7 +10,6 @@ import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL21; import org.lwjgl.opengl.GL30; -import java.lang.reflect.Field; import java.nio.ByteBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -129,24 +128,22 @@ public class GLSM_TextureInfoCache_UnitTest { assertNotNull(info); // Disable caching (simulate SharedDrawable context) - Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete"); - splashCompleteField.setAccessible(true); - boolean originalSplash = splashCompleteField.getBoolean(null); + boolean originalSplash = SplashWindow.isSplashComplete(); Thread originalHolder = GLStateManager.getDrawableGLHolder(); try { - splashCompleteField.setBoolean(null, false); + SplashWindow.setSplashComplete(false); GLStateManager.setDrawableGLHolder(null); // Current thread != null, so caching disabled assertFalse(GLStateManager.isCachingEnabled()); GLStateManager.glDeleteTextures(texId); - splashCompleteField.setBoolean(null, true); + SplashWindow.setSplashComplete(true); // Cache entry should be gone - we should get a fresh object assertNotSame(info, TextureInfoCache.INSTANCE.getInfo(texId)); } finally { - splashCompleteField.setBoolean(null, originalSplash); + SplashWindow.setSplashComplete(originalSplash); GLStateManager.setDrawableGLHolder(originalHolder); GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java index 41794e12b..8b05d1a8a 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_VAO_UnitTest.java @@ -193,7 +193,7 @@ public class GLSM_VAO_UnitTest { private static void glBindVertexArray(int array) { if (array == 0) array = GLStateManager.getDefaultVAO(); - GLStateManager.boundVAO = array; + GLStateManager.ctx().boundVAO = array; VAOManager.onBindVertexArrayPre(array); UniversalVAO.bindVertexArray(array); } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ImmediateModeThreadIsolationTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ImmediateModeThreadIsolationTest.java index 738332050..3c7efea70 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ImmediateModeThreadIsolationTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ImmediateModeThreadIsolationTest.java @@ -7,7 +7,6 @@ import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -111,14 +110,12 @@ class ImmediateModeThreadIsolationTest { void drawLockGatesOnSplashComplete() throws Exception { assertFalse(GLStateManager.acquireDrawLock(), "post-splash acquire must be a no-op"); - final Field f = GLStateManager.class.getDeclaredField("splashComplete"); - f.setAccessible(true); - f.set(null, false); + SplashWindow.setSplashComplete(false); try { assertTrue(GLStateManager.acquireDrawLock(), "during splash the lock must engage"); GLStateManager.releaseDrawLock(); } finally { - f.set(null, true); + SplashWindow.setSplashComplete(true); } } } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SplashWindow.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SplashWindow.java new file mode 100644 index 000000000..878af0dcf --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SplashWindow.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; + +final class SplashWindow { + + private SplashWindow() {} + + static boolean isSplashComplete() { + return Reflect.getStatic(GLStateManager.class, "splashComplete"); + } + + static void setSplashComplete(boolean value) { + Reflect.setStatic(GLStateManager.class, "splashComplete", value); + } + + static void enter() { + setSplashComplete(false); + GLStateManager.setDrawableGLHolder(new Thread("fake-splash-renderer")); + } + + static void leave() { + GLStateManager.setDrawableGLHolder(Thread.currentThread()); + setSplashComplete(true); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java index d87dd2661..cc8018881 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm; +import org.lwjgl.opengl.GL11; import org.junit.jupiter.api.Test; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL13; @@ -91,7 +92,7 @@ class VertexAttribDefaultBridgeTest { GLStateManager.flushDeferredVertexAttribs(false, false, false, false); int listId = GLStateManager.glGenLists(1); - GLStateManager.glNewList(listId, org.lwjgl.opengl.GL11.GL_COMPILE); + GLStateManager.glNewList(listId, GL11.GL_COMPILE); // Color during COMPILE should NOT reach changeColor (early return) GLStateManager.glColor4f(0.9f, 0.8f, 0.7f, 0.6f); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/architecture/DeletePathConventionTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/architecture/DeletePathConventionTest.java deleted file mode 100644 index 319e698a8..000000000 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/architecture/DeletePathConventionTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.architecture; - -import org.junit.jupiter.api.Test; - -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.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class DeletePathConventionTest { - - private static final Pattern FORBIDDEN = Pattern.compile("\\bRENDER_BACKEND\\s*\\.\\s*delete[A-Z][A-Za-z]*\\b"); - private static final String ALLOWLIST_MARKER = "// glsm-allow-direct-delete:"; - - /** Only this file is allowed to call RENDER_BACKEND.delete* — it is the cache-invalidation layer. */ - private static final String GATEKEEPER_FILE_NAME = "GLStateManager.java"; - - @Test - void glsmMainSources_onlyCallBackendDeleteFromGLStateManager() throws IOException { - final Path root = locateGlsmMainRoot(); - final List violations = new ArrayList<>(); - - try (Stream paths = Files.walk(root)) { - paths.filter(Files::isRegularFile) - .filter(p -> p.toString().endsWith(".java")) - .filter(p -> !p.getFileName().toString().equals(GATEKEEPER_FILE_NAME)) - .forEach(p -> scanFile(p, violations)); - } - - assertTrue(violations.isEmpty(), - () -> "Direct RENDER_BACKEND.delete*(...) call found outside " + GATEKEEPER_FILE_NAME + ".\n" - + "Use GLStateManager.glDelete*() instead\n" - + "Violations:\n " + String.join("\n ", violations)); - } - - private static void scanFile(Path file, List violations) { - final List lines; - try { - lines = Files.readAllLines(file, StandardCharsets.UTF_8); - } catch (IOException e) { - violations.add(file + ": I/O error reading file: " + e.getMessage()); - return; - } - for (int i = 0; i < lines.size(); i++) { - final String line = lines.get(i); - final Matcher m = FORBIDDEN.matcher(line); - if (!m.find()) continue; - if (line.contains(ALLOWLIST_MARKER)) continue; - violations.add(file + ":" + (i + 1) + " " + line.trim()); - } - } - - private static Path locateGlsmMainRoot() { - final String[] candidates = { - "src/main/java/com/gtnewhorizons/angelica/glsm", - "glsm/src/main/java/com/gtnewhorizons/angelica/glsm", - }; - for (String c : candidates) { - final Path p = Paths.get(c).toAbsolutePath(); - if (Files.isDirectory(p)) return p; - } - throw new IllegalStateException("Could not find glsm main sources — cwd=" + Paths.get("").toAbsolutePath()); - } -} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java new file mode 100644 index 000000000..8707b19e1 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL31; + +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +@GLCoreTest +class FFPUniformBlockLayoutGLTest { + + @Test + void driverOffsetsMatchJavaConstants() { + final VertexKey vk = VertexKey.fromState(false, false, false, false, 0); + final FragmentKey fk = FragmentKey.fromState(); + final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk), null); + try { + final int programId = program.getProgramId(); + final int blockIndex = GL31.glGetUniformBlockIndex(programId, FFPUniformBlock.BLOCK_NAME); + assertNotEquals(GL31.GL_INVALID_INDEX, blockIndex, "block must be active"); + + final int blockSize = GL31.glGetActiveUniformBlocki(programId, blockIndex, GL31.GL_UNIFORM_BLOCK_DATA_SIZE); + assertEquals(FFPUniformBlock.SIZE, blockSize, "std140 block data size"); + + final Object2IntMap expected = FFPUniformBlock.MEMBER_OFFSETS; + final CharSequence[] names = expected.keySet().toArray(new CharSequence[0]); + final IntBuffer indices = BufferUtils.createIntBuffer(names.length); + GL31.glGetUniformIndices(programId, names, indices); + final IntBuffer offsets = BufferUtils.createIntBuffer(names.length); + GL31.glGetActiveUniforms(programId, indices, GL31.GL_UNIFORM_OFFSET, offsets); + + for (int i = 0; i < names.length; i++) { + final String name = names[i].toString(); + assertNotEquals(GL31.GL_INVALID_INDEX, indices.get(i), name + " must be an active block member"); + assertEquals(expected.getInt(name), offsets.get(i), "std140 offset of " + name); + } + } finally { + program.destroy(); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java new file mode 100644 index 000000000..1e3558b00 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryStack.stackPush; + +@Tag("lwjgl3") +class FFPUniformBlockSpirvLayoutTest { + + @Test + void vertexStageBlockMatchesJavaLayout() { + final String glsl = "#version 460 core\n" + FFPUniformBlock.GLSL_DECL + "void main() { gl_Position = u_MVPMatrix * vec4(0.0, 0.0, 0.0, 1.0); }\n"; + assertBlockLayout(glsl, Shaderc.shaderc_vertex_shader); + } + + @Test + void fragmentStageBlockMatchesJavaLayout() { + final FragmentKey fk = FragmentKey.fromPacked(new long[]{0L}, 1); + assertBlockLayout(FragmentShaderGenerator.generate(fk), Shaderc.shaderc_fragment_shader); + } + + private static void assertBlockLayout(String glsl, int shaderKind) { + final SpirvCompiler.Result result = SpirvCompiler.compile(glsl, shaderKind, "ffp-layout-test", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(result.spirv(), () -> "SPIR-V compile failed: " + result.error() + "\n" + glsl); + try { + reflectAndCompare(result.spirv()); + } finally { + MemoryUtil.memFree(result.spirv()); + } + } + + private static void reflectAndCompare(ByteBuffer spirv) { + try (var stack = stackPush()) { + final PointerBuffer pCtx = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create(pCtx)); + final long ctx = pCtx.get(0); + try { + final IntBuffer words = spirv.asIntBuffer(); + final PointerBuffer pIR = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_parse_spirv(ctx, words, words.remaining(), pIR)); + final PointerBuffer pCompiler = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pIR.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler)); + final long compiler = pCompiler.get(0); + + final PointerBuffer pResources = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_compiler_create_shader_resources(compiler, pResources)); + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_resources_get_resource_list_for_type(pResources.get(0), Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, pList, pCount)); + assertEquals(1, (int) pCount.get(0), "expected exactly one UBO (the FFP block)"); + + final SpvcReflectedResource ubo = SpvcReflectedResource.create(pList.get(0), 1).get(0); + assertEquals(0, Spvc.spvc_compiler_get_decoration(compiler, ubo.id(), Spv.SpvDecorationBinding), "FFP block must auto-bind to binding 0 (SDL reflection keys on it)"); + + final long typeHandle = Spvc.spvc_compiler_get_type_handle(compiler, ubo.base_type_id()); + final PointerBuffer pSize = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_compiler_get_declared_struct_size(compiler, typeHandle, pSize)); + assertEquals(FFPUniformBlock.SIZE, (int) pSize.get(0), "declared block size vs Java layout"); + + final int memberCount = Spvc.spvc_type_get_num_member_types(typeHandle); + assertEquals(FFPUniformBlock.MEMBER_OFFSETS.size(), memberCount, "member count vs Java layout"); + final IntBuffer pOffset = stack.ints(0); + for (int i = 0; i < memberCount; i++) { + final String name = Spvc.spvc_compiler_get_member_name(compiler, ubo.base_type_id(), i); + assertNotNull(name); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_compiler_type_struct_member_offset(compiler, typeHandle, i, pOffset)); + final String key = FFPUniformBlock.MEMBER_OFFSETS.containsKey(name) ? name : name + "[0]"; + assertTrue(FFPUniformBlock.MEMBER_OFFSETS.containsKey(key), () -> "Java layout missing member " + name); + assertEquals(FFPUniformBlock.MEMBER_OFFSETS.getInt(key), pOffset.get(0), "offset of " + name); + } + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java new file mode 100644 index 000000000..e91e5fd68 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@GLCoreTest +class FFPUniformValuesTest { + + private static final float EPS = 1e-6f; + + @Test + void uploadedValuesMatchState() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f); + + GLStateManager.glColor4f(0.25f, 0.5f, 0.75f, 1.0f); + + GLStateManager.enableFog(); + GLStateManager.glFogi(GL11.GL_FOG_MODE, GL11.GL_LINEAR); + GLStateManager.glFogf(GL11.GL_FOG_START, 10.0f); + GLStateManager.glFogf(GL11.GL_FOG_END, 20.0f); + final FloatBuffer fogColor = BufferUtils.createFloatBuffer(4); + fogColor.put(0.1f).put(0.2f).put(0.3f).put(0.4f).flip(); + GLStateManager.glFog(GL11.GL_FOG_COLOR, fogColor); + + GLStateManager.enableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.35f); + + final VertexKey vk = VertexKey.fromState(false, false, false, false, 0); + final FragmentKey fk = FragmentKey.fromState(); + final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk), null); + final Uniforms uniforms = new Uniforms(); + try { + GL20.glUseProgram(program.getProgramId()); + uniforms.upload(); + + final ByteBuffer block = uniforms.getStaging(); + + assertEquals(1.0f, block.getFloat(FFPUniformBlock.MODEL_VIEW_MATRIX + 12 * 4), EPS, "modelView tx"); + assertEquals(2.0f, block.getFloat(FFPUniformBlock.MODEL_VIEW_MATRIX + 13 * 4), EPS, "modelView ty"); + assertEquals(3.0f, block.getFloat(FFPUniformBlock.MODEL_VIEW_MATRIX + 14 * 4), EPS, "modelView tz"); + + assertEquals(1.0f, block.getFloat(FFPUniformBlock.MVP_MATRIX + 12 * 4), EPS, "mvp tx"); + assertEquals(2.0f, block.getFloat(FFPUniformBlock.MVP_MATRIX + 13 * 4), EPS, "mvp ty"); + assertEquals(3.0f, block.getFloat(FFPUniformBlock.MVP_MATRIX + 14 * 4), EPS, "mvp tz"); + + assertEquals(0.25f, block.getFloat(FFPUniformBlock.CURRENT_COLOR), EPS, "color r"); + assertEquals(0.5f, block.getFloat(FFPUniformBlock.CURRENT_COLOR + 4), EPS, "color g"); + assertEquals(0.75f, block.getFloat(FFPUniformBlock.CURRENT_COLOR + 8), EPS, "color b"); + assertEquals(1.0f, block.getFloat(FFPUniformBlock.CURRENT_COLOR + 12), EPS, "color a"); + + assertEquals(0.35f, block.getFloat(FFPUniformBlock.ALPHA_REF), EPS, "alpha ref"); + + assertEquals(-0.1f, block.getFloat(FFPUniformBlock.FOG_PARAMS), EPS, "fog -1/range"); + assertEquals(2.0f, block.getFloat(FFPUniformBlock.FOG_PARAMS + 4), EPS, "fog end/range"); + + assertEquals(0.1f, block.getFloat(FFPUniformBlock.FOG_COLOR), EPS, "fog color r"); + assertEquals(0.2f, block.getFloat(FFPUniformBlock.FOG_COLOR + 4), EPS, "fog color g"); + assertEquals(0.3f, block.getFloat(FFPUniformBlock.FOG_COLOR + 8), EPS, "fog color b"); + assertEquals(0.4f, block.getFloat(FFPUniformBlock.FOG_COLOR + 12), EPS, "fog color a"); + } finally { + GL20.glUseProgram(0); + program.destroy(); + uniforms.destroy(); + + GLStateManager.disableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_ALWAYS, 0.0f); + GLStateManager.disableFog(); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glPopMatrix(); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FfpUniformBlockDedupTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FfpUniformBlockDedupTest.java new file mode 100644 index 000000000..77733c207 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FfpUniformBlockDedupTest.java @@ -0,0 +1,173 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; + +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +@GLCoreTest +class FfpUniformBlockDedupTest { + + private static int boundRangeStart() { + return GL30.glGetInteger(GL31.GL_UNIFORM_BUFFER_START, FFPUniformBlock.BINDING_POINT); + } + + private static FloatBuffer floats(float... values) { + final FloatBuffer buf = BufferUtils.createFloatBuffer(values.length); + buf.put(values).flip(); + return buf; + } + + private static DoubleBuffer doubles(double... values) { + final DoubleBuffer buf = BufferUtils.createDoubleBuffer(values.length); + buf.put(values).flip(); + return buf; + } + + private static void resetState() { + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glLineWidth(1.0f); + GLStateManager.glAlphaFunc(GL11.GL_ALWAYS, 0.0f); + GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f); + GLStateManager.glTexCoord2f(0.0f, 0.0f); + GLSMConfig.lastBrightnessX = 0.0f; + GLSMConfig.lastBrightnessY = 0.0f; + GLStateManager.glFog(GL11.GL_FOG_COLOR, floats(0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 1.0f); + GLStateManager.glTexEnv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR, floats(0.0f, 0.0f, 0.0f, 0.0f)); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, floats(1.0f, 1.0f, 1.0f, 1.0f)); + GLStateManager.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, 0.0f); + GLStateManager.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, floats(1.0f, 0.0f, 0.0f, 0.0f)); + GLStateManager.glClipPlane(GL11.GL_CLIP_PLANE0, doubles(0.0, 0.0, 0.0, 0.0)); + GLStateManager.glLineStipple(1, (short) 0xFFFF); + GLStateManager.glViewport(0, 0, 854, 480); + } + + @Test + void identicalContentSkipsTheWriteAndTheRebind() { + resetState(); + final Uniforms uniforms = new Uniforms(); + try { + uniforms.upload(); + assertEquals(1, uniforms.blockWrites, "first upload always writes"); + final int firstOffset = boundRangeStart(); + + GLStateManager.glLoadIdentity(); + uniforms.upload(); + assertEquals(1, uniforms.blockWrites, "a dirty generation with unchanged bytes must not write"); + assertEquals(1, uniforms.blockSkips, "and must be counted as a skip"); + assertEquals(firstOffset, boundRangeStart(), "the skipped write must not advance the ring or rebind"); + + GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); + uniforms.upload(); + assertEquals(2, uniforms.blockWrites, "a changed matrix must write"); + assertEquals(1, uniforms.blockSkips, "a write is not a skip"); + assertNotEquals(firstOffset, boundRangeStart(), "a write takes a fresh ring range and rebinds"); + } finally { + uniforms.destroy(); + resetState(); + } + } + + @Test + void anUnboundInstanceWritesEvenWhenTheContentMatches() { + resetState(); + final Uniforms first = new Uniforms(); + final Uniforms second = new Uniforms(); + try { + first.upload(); + first.upload(); + assertEquals(1, first.blockWrites); + + second.upload(); + assertEquals(1, second.blockWrites, "a never-bound instance must write regardless of content"); + } finally { + first.destroy(); + second.destroy(); + resetState(); + } + } + + @TestFactory + List everyStagingCategoryForcesAWrite() { + final List tests = new ArrayList<>(); + addCategory(tests, "modelViewMatrix", () -> GLStateManager.glTranslatef(0.0f, 3.0f, 0.0f)); + addCategory(tests, "projectionMatrix", () -> { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glTranslatef(0.0f, 0.0f, 5.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + }); + addCategory(tests, "normalMatrix", () -> GLStateManager.glRotatef(35.0f, 0.0f, 1.0f, 0.0f)); + addCategory(tests, "textureMatrix", () -> { + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glTranslatef(0.5f, 0.25f, 0.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + }); + addCategory(tests, "lighting", () -> GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, floats(0.3f, 0.6f, 0.9f, 1.0f))); + addCategory(tests, "materialShininess", () -> GLStateManager.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, 42.0f)); + addCategory(tests, "currentColor", () -> GLStateManager.glColor4f(0.25f, 0.5f, 0.75f, 1.0f)); + addCategory(tests, "currentNormal", () -> GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f)); + addCategory(tests, "currentTexCoord", () -> GLStateManager.glTexCoord2f(0.125f, 0.375f)); + addCategory(tests, "lightmapCoord", () -> GLSMConfig.lastBrightnessX = 96.0f); + addCategory(tests, "texGenPlane", () -> GLStateManager.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, floats(0.5f, 0.0f, 0.0f, 0.25f))); + addCategory(tests, "clipPlane", () -> GLStateManager.glClipPlane(GL11.GL_CLIP_PLANE0, doubles(0.0, 1.0, 0.0, 7.0))); + addCategory(tests, "alphaRef", () -> GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.35f)); + addCategory(tests, "fogColor", () -> GLStateManager.glFog(GL11.GL_FOG_COLOR, floats(0.1f, 0.2f, 0.3f, 0.4f))); + addCategory(tests, "fogDensity", () -> GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 0.75f)); + addCategory(tests, "texEnvColor", () -> GLStateManager.glTexEnv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR, floats(0.9f, 0.8f, 0.7f, 0.6f))); + addCategory(tests, "lineWidth", () -> GLStateManager.glLineWidth(3.0f)); + addCategory(tests, "lineStipple", () -> GLStateManager.glLineStipple(2, (short) 0x00FF)); + addCategory(tests, "viewport", () -> GLStateManager.glViewport(0, 0, 640, 480)); + return tests; + } + + private static void addCategory(List tests, String name, Runnable mutate) { + tests.add(DynamicTest.dynamicTest(name, () -> { + resetState(); + final Uniforms uniforms = new Uniforms(); + try { + uniforms.upload(); + uniforms.upload(); + final int writesBefore = uniforms.blockWrites; + final int settledOffset = boundRangeStart(); + + mutate.run(); + uniforms.upload(); + assertEquals(writesBefore + 1, uniforms.blockWrites, name + ": a changed member must write"); + assertNotEquals(settledOffset, boundRangeStart(), name + ": a write must rebind to a fresh range"); + + final int skipsBefore = uniforms.blockSkips; + final int writtenOffset = boundRangeStart(); + uniforms.upload(); + assertEquals(writesBefore + 1, uniforms.blockWrites, name + ": re-uploading unchanged bytes must not write"); + assertEquals(writtenOffset, boundRangeStart(), name + ": and must not rebind"); + if (uniforms.blockSkips != skipsBefore) { + assertEquals(skipsBefore + 1, uniforms.blockSkips, name + ": at most one skip per upload"); + } + } finally { + uniforms.destroy(); + resetState(); + } + })); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java new file mode 100644 index 000000000..46014fd04 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java @@ -0,0 +1,271 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.COLOR_BIT; +import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.NORMAL_BIT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class InstancedFFPDrawGLTest { + + private static final int TEMPLATE_STRIDE = 32; + private static final int INSTANCE_STRIDE = InstancedAttribs.STRIDE; + + private int vao, templateVbo, instanceVbo; + + @AfterEach + void cleanup() { + GLStateManager.instancedFfpDrawActive = false; + final ShaderManager sm = ShaderManager.getInstance(); + if (sm.isActive()) sm.deactivate(); + sm.disable(); + GLStateManager.glBindVertexArray(0); + if (templateVbo != 0) { GLStateManager.glDeleteBuffers(templateVbo); templateVbo = 0; } + if (instanceVbo != 0) { GLStateManager.glDeleteBuffers(instanceVbo); instanceVbo = 0; } + if (vao != 0) { GLStateManager.glDeleteVertexArrays(vao); vao = 0; } + } + + @Test + void vertexKeyCarriesInstancedBit() { + GLStateManager.instancedFfpDrawActive = false; + final long plain = VertexKey.packFromState(true, true, false, false, 0); + GLStateManager.instancedFfpDrawActive = true; + final long instanced = VertexKey.packFromState(true, true, false, false, 0); + GLStateManager.instancedFfpDrawActive = false; + + assertFalse(VertexKey.fromPacked(plain).instancedDraw()); + assertTrue(VertexKey.fromPacked(instanced).instancedDraw()); + assertEquals(1, Long.bitCount(plain ^ instanced), "only the instanced bit may differ"); + } + + @Test + void instancedSourceUsesInstanceAttribs() { + GLStateManager.instancedFfpDrawActive = true; + final VertexKey key = VertexKey.fromState(true, true, false, false, 0b10); + GLStateManager.instancedFfpDrawActive = false; + + final String source = VertexShaderGenerator.generate(key); + assertTrue(source.contains("a_InstCol0"), "instance matrix attribs declared"); + assertTrue(source.contains("mat4 instMV"), "instance matrix used as modelview"); + assertTrue(source.contains("a_InstColor"), "instance color multiplier used"); + assertTrue(source.contains("a_InstLightmap"), "instance lightmap coord used"); + assertFalse(source.contains("u_MVPMatrix * pos4"), "uniform MVP transform unused in instanced variant"); + } + + @Test + void twoInstancesDrawWithDistinctTransformsAndColors() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + + buildTemplate(); + buildInstances(); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + + GLStateManager.instancedFfpDrawActive = true; + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + GLStateManager.instancedFfpDrawActive = false; + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced draw must not raise a GL error"); + + final int[] left = readPixel(200, 300); + final int[] right = readPixel(600, 300); + assertTrue(left[0] > 200 && left[1] < 50, "left instance red, got " + left[0] + "," + left[1] + "," + left[2]); + assertTrue(right[1] > 200 && right[0] < 50, "right instance green, got " + right[0] + "," + right[1] + "," + right[2]); + } + + @Test + void instancedAlphaTestDiscardsLowAlphaInstance() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + + buildTemplate(); + buildInstancesWithAlpha(); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + GLStateManager.enableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1f); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + + GLStateManager.instancedFfpDrawActive = true; + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + GLStateManager.instancedFfpDrawActive = false; + GLStateManager.disableAlphaTest(); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); + final int[] left = readPixel(200, 300); + final int[] right = readPixel(600, 300); + assertTrue(left[0] > 200, "opaque instance drawn, got " + left[0]); + assertTrue(right[0] < 20 && right[1] < 20, "alpha 0.05 instance discarded, got " + right[0] + "," + right[1]); + } + + @Test + void equalDepthOverlayBlendsOnlyOverBase() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.enableDepthTest(); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.disableCull(); + + buildTemplate(); + buildInstances(); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + + GLStateManager.instancedFfpDrawActive = true; + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + + GLStateManager.glDepthFunc(GL11.GL_EQUAL); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GLStateManager.glColor4f(1f, 1f, 1f, 1f); + rewriteInstanceColors(0x800000FF, 0x8000FF00); + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + GLStateManager.instancedFfpDrawActive = false; + + GLStateManager.disableBlend(); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.disableDepthTest(); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); + final int[] left = readPixel(200, 300); + final int[] background = readPixel(400, 550); + assertTrue(left[0] > 200, "overlay blended over base, got " + left[0]); + assertTrue(background[0] < 20 && background[1] < 20, "overlay must not draw off-base, got " + background[0]); + } + + private void rewriteInstanceColors(int leftABGR, int rightABGR) { + final ByteBuffer patch = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); + putInstance(patch, -0.5f, leftABGR); + putInstance(patch, 0.5f, rightABGR); + patch.flip(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, patch, GL15.GL_STATIC_DRAW); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + private void buildInstancesWithAlpha() { + final ByteBuffer instances = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); + putInstance(instances, -0.5f, 0xFF0000FF); + putInstance(instances, 0.5f, 0x0D0000FF); + instances.flip(); + + instanceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, instances, GL15.GL_STATIC_DRAW); + pointAndEnableInstanceAttribs(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + private void buildTemplate() { + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + + final ByteBuffer template = BufferUtils.createByteBuffer(3 * TEMPLATE_STRIDE); + putVertex(template, -0.4f, -0.4f); + putVertex(template, 0.4f, -0.4f); + putVertex(template, 0.0f, 0.4f); + template.flip(); + + templateVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, templateVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, template, GL15.GL_STATIC_DRAW); + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, TEMPLATE_STRIDE, 0L); + GLStateManager.glEnableVertexAttribArray(1); + GLStateManager.glVertexAttribPointer(1, 4, GL11.GL_UNSIGNED_BYTE, true, TEMPLATE_STRIDE, 20L); + GLStateManager.glEnableVertexAttribArray(4); + GLStateManager.glVertexAttribPointer(4, 3, GL11.GL_BYTE, true, TEMPLATE_STRIDE, 24L); + VAOManager.setCurrentVertexFlags(COLOR_BIT | NORMAL_BIT); + } + + private void putVertex(ByteBuffer buf, float x, float y) { + final int base = buf.position(); + buf.putFloat(base, x).putFloat(base + 4, y).putFloat(base + 8, 0f); + buf.putInt(base + 20, 0xFFFFFFFF); + buf.putInt(base + 24, 0x00007F00); + buf.position(base + TEMPLATE_STRIDE); + } + + private void buildInstances() { + final ByteBuffer instances = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); + putInstance(instances, -0.5f, 0xFF0000FF); + putInstance(instances, 0.5f, 0xFF00FF00); + instances.flip(); + + instanceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, instances, GL15.GL_STATIC_DRAW); + pointAndEnableInstanceAttribs(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + private static void pointAndEnableInstanceAttribs() { + for (int c = 0; c < 4; c++) { + final int loc = InstancedAttribs.LOC_MATRIX_COL0 + c; + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribPointer(loc, 4, GL11.GL_FLOAT, false, INSTANCE_STRIDE, c * 16L); + GLStateManager.glVertexAttribDivisor(loc, 1); + } + GLStateManager.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR); + GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, INSTANCE_STRIDE, InstancedAttribs.OFFSET_COLOR); + GLStateManager.glVertexAttribDivisor(InstancedAttribs.LOC_COLOR, 1); + GLStateManager.glEnableVertexAttribArray(InstancedAttribs.LOC_LIGHTMAP); + GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, INSTANCE_STRIDE, InstancedAttribs.OFFSET_LIGHTMAP); + GLStateManager.glVertexAttribDivisor(InstancedAttribs.LOC_LIGHTMAP, 1); + } + + private void putInstance(ByteBuffer buf, float translateX, int colorABGR) { + final int base = buf.position(); + buf.putFloat(base, 1f).putFloat(base + 20, 1f).putFloat(base + 40, 1f).putFloat(base + 60, 1f); + buf.putFloat(base + 48, translateX); + buf.putInt(base + InstancedAttribs.OFFSET_COLOR, colorABGR); + buf.putFloat(base + InstancedAttribs.OFFSET_LIGHTMAP, 240f); + buf.putFloat(base + InstancedAttribs.OFFSET_LIGHTMAP + 4, 240f); + buf.position(base + INSTANCE_STRIDE); + } + + private static int[] readPixel(int x, int y) { + final ByteBuffer pixel = BufferUtils.createByteBuffer(4); + GL11.glReadPixels(x, y, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); + return new int[] { pixel.get(0) & 0xFF, pixel.get(1) & 0xFF, pixel.get(2) & 0xFF }; + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java index fb15051be..d045ddac2 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java @@ -19,7 +19,7 @@ class ProgramUniformTrackingTest { } @Test - void matrixTrackingIsPerProgram() { + void programSwitchWritesNothingStateChangeWritesOnce() { final Uniforms uniforms = new Uniforms(); final Program a = buildProgram(true); final Program b = buildProgram(false); @@ -28,35 +28,63 @@ class ProgramUniformTrackingTest { GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); GLStateManager.glPushMatrix(); GLStateManager.glLoadIdentity(); - GLStateManager.glTranslatef(1.0F, 2.0F, 3.0F); - final int genA = GLStateManager.mvGeneration; + GL20.glUseProgram(a.getProgramId()); - uniforms.upload(a); - assertEquals(genA, a.uploadState.mvGen, "A records the mv generation it uploaded"); + uniforms.upload(); + final int afterFirst = uniforms.blockWrites; + + GL20.glUseProgram(b.getProgramId()); + uniforms.upload(); + GL20.glUseProgram(a.getProgramId()); + uniforms.upload(); + assertEquals(afterFirst, uniforms.blockWrites, "program switches with unchanged state write nothing"); GLStateManager.glTranslatef(4.0F, 0.0F, 0.0F); - final int genB = GLStateManager.mvGeneration; - assertNotEquals(genA, genB); - GL20.glUseProgram(b.getProgramId()); - uniforms.upload(b); - assertEquals(genB, b.uploadState.mvGen, "B records the new mv generation"); - assertEquals(genA, a.uploadState.mvGen, "A is unchanged -- tracking is per-program, not global"); + uniforms.upload(); + assertEquals(afterFirst + 1, uniforms.blockWrites, "a gen bump writes exactly one block"); - // Return to A with the modelview still at genB: A is stale -> re-uploads and catches up. - GL20.glUseProgram(a.getProgramId()); - uniforms.upload(a); - assertEquals(genB, a.uploadState.mvGen, "A re-uploads on return and catches up to genB"); - - // Re-upload A with no change: gate (mvGeneration == A.mvGen) is satisfied -> skip. - uniforms.upload(a); - assertEquals(genB, a.uploadState.mvGen, "A already current -> skipped"); + uniforms.upload(); + assertEquals(afterFirst + 1, uniforms.blockWrites, "clean draw writes nothing"); GLStateManager.glPopMatrix(); } finally { GL20.glUseProgram(0); a.destroy(); b.destroy(); + uniforms.destroy(); + } + } + + @Test + void pushPopScopeWithoutNetChangeWritesNothing() { + final Uniforms uniforms = new Uniforms(); + final Program a = buildProgram(true); + try { + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + + GL20.glUseProgram(a.getProgramId()); + uniforms.upload(); + final int base = uniforms.blockWrites; + + GLStateManager.glPushAttrib(GL11.GL_TRANSFORM_BIT); + GLStateManager.glPopAttrib(); + uniforms.upload(); + assertEquals(base, uniforms.blockWrites, "push/pop with no change inside writes nothing"); + + GLStateManager.glPushAttrib(GL11.GL_TRANSFORM_BIT); + GLStateManager.glTranslatef(7.0F, 0.0F, 0.0F); + GLStateManager.glPopAttrib(); + uniforms.upload(); + assertEquals(base + 1, uniforms.blockWrites, "pop after change stages once"); + + GLStateManager.glPopMatrix(); + } finally { + GL20.glUseProgram(0); + a.destroy(); + uniforms.destroy(); } } } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/IndexedDrawDeleteSafetyTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/IndexedDrawDeleteSafetyTest.java index 60811a3bc..bc4d2bbf6 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/IndexedDrawDeleteSafetyTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/IndexedDrawDeleteSafetyTest.java @@ -101,7 +101,7 @@ class IndexedDrawDeleteSafetyTest extends DisplayListTestFixture { } @Test - void activeProgram_clearedOnDelete() { + void activeProgram_retainedAfterDelete_perGlSpec() { final int prog = linkMinimalProgram(); while (GL11.glGetError() != GL11.GL_NO_ERROR) {} @@ -110,9 +110,10 @@ class IndexedDrawDeleteSafetyTest extends DisplayListTestFixture { GLStateManager.glDeleteProgram(prog); - assertEquals(0, GLStateManager.getActiveProgram(), "activeProgram not cleared when the active program was deleted"); + assertEquals(prog, GLStateManager.getActiveProgram(), "activeProgram must remain set after delete (GL spec: deletion deferred until unbind)"); GLStateManager.glUseProgram(0); + assertEquals(0, GLStateManager.getActiveProgram(), "activeProgram clears once the deleted program is unbound"); while (GL11.glGetError() != GL11.GL_NO_ERROR) {} } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java index 79c85d903..396bfafa3 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/RecordingDataStructuresTest.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.glsm.GLCompatTest; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLCompatTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/support/DisplayListTestFixture.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/support/DisplayListTestFixture.java index 1680f84d5..04fa57cda 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/support/DisplayListTestFixture.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/recording/support/DisplayListTestFixture.java @@ -4,6 +4,7 @@ import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLCompatTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; import com.gtnewhorizons.angelica.glsm.recording.commands.BatchedIndexedDrawCmd; import com.gtnewhorizons.angelica.glsm.recording.commands.IndexedDrawBatch; @@ -99,12 +100,7 @@ public abstract class DisplayListTestFixture { } protected final int uploadEbo(int indexType, int... values) { - final int bytesPer = switch (indexType) { - case GL11.GL_UNSIGNED_BYTE -> 1; - case GL11.GL_UNSIGNED_SHORT -> 2; - case GL11.GL_UNSIGNED_INT -> 4; - default -> throw new IllegalArgumentException("unsupported indexType 0x" + Integer.toHexString(indexType)); - }; + final int bytesPer = GLTypes.sizeBytes(indexType); final int ebo = newBuffer(); final ByteBuffer data = MemoryUtilities.memAlloc(values.length * bytesPer).order(ByteOrder.nativeOrder()); for (int v : values) { diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirectorTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirectorTest.java index 3a7d1ab91..360e3d0bf 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirectorTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/redirect/GLSMRedirectorTest.java @@ -1,26 +1,79 @@ package com.gtnewhorizons.angelica.glsm.redirect; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.config.SystemProperties.UnmappedGLMode; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; +import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class GLSMRedirectorTest { private static final String GLSM = GLSMRedirector.getTargetClassName(); + @SuppressWarnings("unchecked") + private static Set seenSet(String field) { + try { + final Field f = GLSMRedirector.class.getDeclaredField(field); + f.setAccessible(true); + return (Set) f.get(null); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + + private static Set unmappedSeen() { return seenSet("UNMAPPED_SEEN"); } + private static Set debugSeen() { return seenSet("DEBUG_SEEN"); } + + @BeforeEach + void reset() { + unmappedSeen().clear(); + debugSeen().clear(); + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.WARN); + } + + private static ClassNode makeClassWithMethodCall(String owner, String name, String desc) { + final ClassNode cn = new ClassNode(); + cn.version = Opcodes.V1_8; + cn.access = Opcodes.ACC_PUBLIC; + cn.name = "com/example/TestClass"; + cn.superName = "java/lang/Object"; + cn.methods = new ArrayList<>(); + + final MethodNode mn = new MethodNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "test", "()V", null, null); + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, owner, name, desc, false)); + mn.instructions.add(new InsnNode(Opcodes.RETURN)); + cn.methods.add(mn); + + return cn; + } + + private static MethodInsnNode firstCall(ClassNode cn) { + for (AbstractInsnNode node : cn.methods.get(0).instructions.toArray()) { + if (node instanceof MethodInsnNode) return (MethodInsnNode) node; + } + return null; + } + private static final Handle LAMBDA_METAFACTORY = new Handle( Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", @@ -109,6 +162,194 @@ class GLSMRedirectorTest { assertFalse(changed); final Handle result = getResultHandle(cn); assertEquals("org/lwjgl/opengl/GL11", result.getOwner()); + assertTrue(unmappedSeen().contains("org/lwjgl/opengl/GL11.glNonexistent()V")); + } + + @Test + void unmappedMethodCallIsRecordedAndNotRedirected() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/ARBSparseTexture", "glTexPageCommitmentARB", "()V"); + + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertFalse(changed); + assertEquals("org/lwjgl/opengl/ARBSparseTexture", firstCall(cn).owner); + assertTrue(unmappedSeen().contains("org/lwjgl/opengl/ARBSparseTexture.glTexPageCommitmentARB()V")); + } + + @Test + void debugLabelIsRedirectedNotReported() { + assertRedirected("org/lwjgl/opengl/KHRDebug", "glPushDebugGroup", "(IILjava/lang/CharSequence;)V", "glPushDebugGroup"); + assertRedirected("org/lwjgl/opengl/GL43C", "glObjectLabel", "(IILjava/lang/CharSequence;)V", "glObjectLabel"); + assertTrue(debugSeen().isEmpty()); + } + + @Test + void nonAwareDebugCallbackIsRedirectedNotPassedThrough() { + assertRedirected("org/lwjgl/opengl/GL43", "glDebugMessageCallback", "(Lorg/lwjgl/opengl/KHRDebugCallback;)V", "glDebugMessageCallback"); + assertTrue(debugSeen().isEmpty()); + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void debugOwnerAndWrongDescriptorArePassthrough() { + makeAndTransform("org/lwjgl/opengl/AMDDebugOutput", "glDebugMessageEnableAMD", "(IILjava/nio/IntBuffer;Z)V"); + makeAndTransform("org/lwjgl/opengl/KHRDebug", "glObjectLabel", "(IIILjava/nio/ByteBuffer;)V"); + assertTrue(unmappedSeen().isEmpty()); + assertTrue(debugSeen().contains("org/lwjgl/opengl/AMDDebugOutput.glDebugMessageEnableAMD(IILjava/nio/IntBuffer;Z)V")); + assertTrue(debugSeen().contains("org/lwjgl/opengl/KHRDebug.glObjectLabel(IIILjava/nio/ByteBuffer;)V")); + } + + @Test + void failModeDoesNotThrowOnDebugPassthrough() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.FAIL); + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL43C", "glDebugMessageCallback", "(Lorg/lwjgl/opengl/GLDebugMessageCallbackI;J)V"); + new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + assertTrue(debugSeen().contains("org/lwjgl/opengl/GL43C.glDebugMessageCallback(Lorg/lwjgl/opengl/GLDebugMessageCallbackI;J)V")); + } + + private static void makeAndTransform(String owner, String name, String desc) { + new GLSMRedirector().transformClassNode("com.example.TestClass", makeClassWithMethodCall(owner, name, desc)); + } + + @Test + void nonGlNamedCallIsNotRecorded() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/DisplayMode", "", "(II)V"); + + new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void failModeThrowsOnUnmapped() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.FAIL); + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/ARBSparseTexture", "glTexPageCommitmentARB", "()V"); + + assertThrows(IllegalStateException.class, () -> new GLSMRedirector().transformClassNode("com.example.TestClass", cn)); + } + + @Test + void offModeSuppressesRecording() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.OFF); + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/ARBSparseTexture", "glTexPageCommitmentARB", "()V"); + + new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void newlyMappedFramebufferAliasIsRedirected() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/EXTFramebufferObject", "glBindFramebufferEXT", "(II)V"); + + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertTrue(changed); + assertEquals(GLSM, firstCall(cn).owner); + assertEquals("glBindFramebuffer", firstCall(cn).name); + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void newlyMappedReadPixelsIsRedirected() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL11", "glReadPixels", "(IIIIIILjava/nio/IntBuffer;)V"); + + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertTrue(changed); + assertEquals(GLSM, firstCall(cn).owner); + assertEquals("glReadPixels", firstCall(cn).name); + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void newlyMappedOcclusionQueryAliasIsRedirected() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/ARBOcclusionQuery", "glGenQueriesARB", "(Ljava/nio/IntBuffer;)V"); + + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + + assertTrue(changed); + assertEquals(GLSM, firstCall(cn).owner); + assertEquals("glGenQueries", firstCall(cn).name); + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void indexedGettersHaveRealTargets() throws Exception { + final Class glsm = Class.forName(GLSM.replace('/', '.'), false, getClass().getClassLoader()); + assertDoesNotThrow(() -> glsm.getDeclaredMethod("glGetInteger", int.class, int.class), "LWJGL2 GL30.glGetInteger(pname, index) redirects here"); + assertDoesNotThrow(() -> glsm.getDeclaredMethod("glGetIntegeri", int.class, int.class), "LWJGL3 GL31C.glGetIntegeri(pname, index) redirects here"); + assertDoesNotThrow(() -> glsm.getDeclaredMethod("glGetIntegeri_v", int.class, int.class, java.nio.IntBuffer.class)); + assertDoesNotThrow(() -> glsm.getDeclaredMethod("glGetBooleani_v", int.class, int.class, java.nio.ByteBuffer.class)); + } + + @Test + void indexedGettersAreRedirected() { + assertRedirected("org/lwjgl/opengl/GL30", "glGetInteger", "(II)I", "glGetInteger"); + assertRedirected("org/lwjgl/opengl/GL31C", "glGetIntegeri", "(II)I", "glGetIntegeri"); + assertRedirected("org/lwjgl/opengl/GL30", "glGetIntegeri_v", "(IILjava/nio/IntBuffer;)V", "glGetIntegeri_v"); + assertRedirected("org/lwjgl/opengl/GL30", "glGetBooleani_v", "(IILjava/nio/ByteBuffer;)V", "glGetBooleani_v"); + } + + private void assertRedirected(String owner, String name, String desc, String expectedName) { + final ClassNode cn = makeClassWithMethodCall(owner, name, desc); + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + assertTrue(changed, owner + "." + name + " should redirect"); + assertEquals(GLSM, firstCall(cn).owner); + assertEquals(expectedName, firstCall(cn).name); + assertTrue(unmappedSeen().isEmpty(), owner + "." + name + " should not be recorded"); + } + + @Test + void descKeyedSyncRedirectsOnlyLongForm() { + assertRedirected("org/lwjgl/opengl/GL32C", "glFenceSync", "(II)J", "glFenceSync"); + assertRedirected("org/lwjgl/opengl/GL32C", "glDeleteSync", "(J)V", "glDeleteSync"); + assertRedirected("org/lwjgl/opengl/GL15C", "nglMapBuffer", "(II)J", "nglMapBuffer"); + + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL32", "glFenceSync", "(II)Lorg/lwjgl/opengl/GLSync;"); + final boolean changed = new GLSMRedirector().transformClassNode("com.example.TestClass", cn); + assertFalse(changed); + assertEquals("org/lwjgl/opengl/GL32", firstCall(cn).owner); + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void glSyncObjectFormsAreNotReported() { + final String[][] cases = { + {"org/lwjgl/opengl/GL32", "glClientWaitSync", "(Lorg/lwjgl/opengl/GLSync;IJ)I"}, + {"org/lwjgl/opengl/ARBSync", "glWaitSync", "(Lorg/lwjgl/opengl/GLSync;IJ)V"}, + {"org/lwjgl/opengl/ARBSync", "glDeleteSync", "(Lorg/lwjgl/opengl/GLSync;)V"}, + }; + for (String[] c : cases) { + final ClassNode cn = makeClassWithMethodCall(c[0], c[1], c[2]); + assertFalse(new GLSMRedirector().transformClassNode("com.example.TestClass", cn)); + } + assertTrue(unmappedSeen().isEmpty()); + } + + @Test + void phase2NameKeyedGapsRedirect() { + assertRedirected("org/lwjgl/opengl/GL33C", "glQueryCounter", "(II)V", "glQueryCounter"); + assertRedirected("org/lwjgl/opengl/GL33C", "glGetQueryObjectui64", "(II)J", "glGetQueryObjectui64"); + assertRedirected("org/lwjgl/opengl/GL30C", "glBindFragDataLocation", "(IILjava/lang/CharSequence;)V", "glBindFragDataLocation"); + assertRedirected("org/lwjgl/opengl/GL11C", "glGetIntegerv", "(I[I)V", "glGetInteger"); + assertRedirected("org/lwjgl/opengl/GL20C", "glUniform4fv", "(I[F)V", "glUniform4"); + assertRedirected("org/lwjgl/opengl/GL20C", "glUniform4fv", "(ILjava/nio/FloatBuffer;)V", "glUniform4"); + } + + @Test + void phase1CeleritasGapsRedirect() { + assertRedirected("org/lwjgl/opengl/EXTGpuShader4", "glVertexAttribIPointerEXT", "(IIIIJ)V", "glVertexAttribIPointer"); + assertRedirected("org/lwjgl/opengl/EXTGPUShader4", "glVertexAttribIPointerEXT", "(IIIIJ)V", "glVertexAttribIPointer"); + assertRedirected("org/lwjgl/opengl/ARBUniformBufferObject", "glGetUniformBlockIndex", "(ILjava/lang/CharSequence;)I", "glGetUniformBlockIndex"); + assertRedirected("org/lwjgl/opengl/GL30C", "glBindBufferBase", "(III)V", "glBindBufferBase"); + assertRedirected("org/lwjgl/opengl/GL31C", "glUniformBlockBinding", "(III)V", "glUniformBlockBinding"); + assertRedirected("org/lwjgl/opengl/GL32C", "glDrawElementsBaseVertex", "(IIIJI)V", "glDrawElementsBaseVertex"); + assertRedirected("org/lwjgl/opengl/GL43C", "glMultiDrawElementsIndirect", "(IIJII)V", "glMultiDrawElementsIndirect"); + assertRedirected("org/lwjgl/opengl/GL20C", "glUniform1fv", "(ILjava/nio/FloatBuffer;)V", "glUniform1"); + assertRedirected("org/lwjgl/opengl/GL11", "glLoadMatrixf", "(Ljava/nio/FloatBuffer;)V", "glLoadMatrix"); + assertRedirected("org/lwjgl/opengl/ARBVertexArrayObject", "glGenVertexArrays", "()I", "glGenVertexArrays"); + assertRedirected("org/lwjgl/opengl/APPLEVertexArrayObject", "glGenVertexArraysAPPLE", "()I", "glGenVertexArrays"); } @Test @@ -125,6 +366,142 @@ class GLSMRedirectorTest { assertEquals("(III)V", result.getDesc()); } + private static final String AWARE_SHIM = "com/gtnewhorizons/angelica/sdlgpu/compat/AwareGLDebugShim"; + private static final String CALLBACK_I = "Lorg/lwjgl/opengl/GLDebugMessageCallbackI;"; + + @Test + void awareCallerStillHasPlainGlCallsRedirected() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL11", "glPopMatrix", "()V"); + + assertTrue(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true)); + + assertEquals(GLSM, firstCall(cn).owner); + assertEquals("glPopMatrix", firstCall(cn).name); + } + + @Test + void awareDebugMessageCallbackTargetsTheAwareShim() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL43", "glDebugMessageCallback", "(" + CALLBACK_I + "J)V"); + + assertTrue(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true)); + + assertEquals(AWARE_SHIM, firstCall(cn).owner, "GLStateManager cannot carry an org.lwjgl-typed descriptor for an aware caller"); + assertEquals("glDebugMessageCallback", firstCall(cn).name); + } + + @Test + void nonAwareDebugMessageCallbackTargetsGLStateManager() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/KHRDebug", "glDebugMessageCallback", "(Lorg/lwjgl/opengl/KHRDebugCallback;)V"); + + assertTrue(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, false)); + + assertEquals(GLSM, firstCall(cn).owner); + } + + @Test + void awareGLUtilSetupDebugMessageCallbackIsRedirected() { + for (String desc : new String[]{"()Lorg/lwjgl/system/Callback;", "(Ljava/io/PrintStream;)Lorg/lwjgl/system/Callback;"}) { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GLUtil", "setupDebugMessageCallback", desc); + + assertTrue(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true), desc); + + assertEquals(AWARE_SHIM, firstCall(cn).owner, desc); + } + } + + @Test + void getDebugMessageLogReachesGLStateManager() { + final String buffers = "Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/IntBuffer;Ljava/nio/ByteBuffer;"; + for (String desc : new String[]{"(I" + buffers + ")I"}) { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL43", "glGetDebugMessageLog", desc); + + assertTrue(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, false), desc); + + assertEquals(GLSM, firstCall(cn).owner, desc); + assertEquals(desc, firstCall(cn).desc, "descriptor must be preserved so the right overload is hit"); + } + } + + @Test + void awareUnroutableCallIsReported() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL32C", "glSomethingExotic", "(" + CALLBACK_I + ")V"); + + new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true); + + assertTrue(unmappedSeen().stream().anyMatch(s -> s.startsWith("aware ") && s.contains("glSomethingExotic")), () -> "expected an aware-unroutable report, got " + unmappedSeen()); + } + + @Test + void awareUnroutableCallFailsFastWhenRequested() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.STRICT); + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL32C", "glSomethingExotic", "(" + CALLBACK_I + ")V"); + + assertThrows(IllegalStateException.class, () -> new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true)); + } + + @Test + void nonAwareCallerNeverTargetsTheAwareShim() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL43", "glDebugMessageCallback", "(" + CALLBACK_I + "J)V"); + + new GLSMRedirector().transformClassNode("com.example.TestClass", cn, false); + + assertFalse(AWARE_SHIM.equals(firstCall(cn).owner)); + } + + /** Crashed the game: it carries an LWJGL type but is only a ThreadLocal read plus a null check. */ + @Test + void awareGetCapabilitiesIsNeitherRedirectedNorReported() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL", "getCapabilities", "()Lorg/lwjgl/opengl/GLCapabilities;"); + + assertFalse(new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true)); + + assertEquals("org/lwjgl/opengl/GL", firstCall(cn).owner); + assertTrue(unmappedSeen().isEmpty(), () -> "must not be reported: " + unmappedSeen()); + } + + @Test + void awareGetCapabilitiesDoesNotFailFastEvenInStrictMode() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.STRICT); + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL", "getCapabilities", "()Lorg/lwjgl/opengl/GLCapabilities;"); + + assertDoesNotThrow(() -> new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true)); + } + + @Test + void awareSafeLwjglTypedMembersAreNotReported() { + final String[][] safe = { + {"org/lwjgl/opengl/GL", "setCapabilities", "(Lorg/lwjgl/opengl/GLCapabilities;)V"}, + {"org/lwjgl/opengl/GL", "getFunctionProvider", "()Lorg/lwjgl/system/FunctionProvider;"}, + {"org/lwjgl/opengl/GLCapabilities", "getAddressBuffer", "()Lorg/lwjgl/PointerBuffer;"}, + {"org/lwjgl/opengl/GLDebugMessageCallback", "create", "(Lorg/lwjgl/opengl/GLDebugMessageCallbackI;)Lorg/lwjgl/opengl/GLDebugMessageCallback;"}, + }; + for (String[] m : safe) { + unmappedSeen().clear(); + final ClassNode cn = makeClassWithMethodCall(m[0], m[1], m[2]); + new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true); + assertTrue(unmappedSeen().isEmpty(), () -> m[0] + "." + m[1] + " must not be reported"); + } + } + + @Test + void awareDispatchingMembersOnTheGLClassAreStillReported() { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL", "createCapabilities", "(Z)Lorg/lwjgl/opengl/GLCapabilities;"); + + new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true); + + assertTrue(unmappedSeen().stream().anyMatch(s -> s.startsWith("aware ") && s.contains("createCapabilities")), () -> "expected a report, got " + unmappedSeen()); + } + + @Test + void awareUnroutableFailFastIsNotOneShot() { + Reflect.setStaticFinal(SystemProperties.class, "UNMAPPED_GL", UnmappedGLMode.class, UnmappedGLMode.STRICT); + for (int i = 0; i < 2; i++) { + final ClassNode cn = makeClassWithMethodCall("org/lwjgl/opengl/GL32C", "glSomethingExotic", "(" + CALLBACK_I + ")V"); + final int attempt = i; + assertThrows(IllegalStateException.class, () -> new GLSMRedirector().transformClassNode("com.example.TestClass", cn, true), () -> "attempt " + attempt + " must still fail"); + } + } + @Test void transformedClassProducesValidBytecode() { final Handle impl = new Handle(Opcodes.H_INVOKESTATIC, "org/lwjgl/opengl/GL11", "glPopMatrix", "()V", false); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslatorTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslatorTest.java new file mode 100644 index 000000000..fb92f0835 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/shader/SpirvShaderTranslatorTest.java @@ -0,0 +1,413 @@ +package com.gtnewhorizons.angelica.glsm.shader; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL32; + +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SpirvShaderTranslatorTest { + + @Test + void selectionBoxVs_producesNamedLooseUniforms() { + final String src = """ + #version 330 core + uniform mat4 u_MVP; + uniform vec3 u_Min; + uniform vec3 u_Max; + const vec3 edges[24] = vec3[24]( + vec3(0,0,0), vec3(1,0,0), vec3(1,0,0), vec3(1,0,1), + vec3(1,0,1), vec3(0,0,1), vec3(0,0,1), vec3(0,0,0), + vec3(0,1,0), vec3(1,1,0), vec3(1,1,0), vec3(1,1,1), + vec3(1,1,1), vec3(0,1,1), vec3(0,1,1), vec3(0,1,0), + vec3(0,0,0), vec3(0,1,0), vec3(1,0,0), vec3(1,1,0), + vec3(1,0,1), vec3(1,1,1), vec3(0,0,1), vec3(0,1,1) + ); + void main() { + vec3 pos = mix(u_Min, u_Max, edges[gl_VertexID]); + gl_Position = u_MVP * vec4(pos, 1.0); + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_VERTEX_SHADER, "selection_box.vert"); + dumpOnFailure("selection_box.vert", src, es); + + assertNotNull(es); + assertTrue(es.startsWith("#version 320 es")); + assertContainsDecl(es, "mat4", "u_MVP"); + assertContainsDecl(es, "vec3", "u_Min"); + assertContainsDecl(es, "vec3", "u_Max"); + assertFalse(es.contains("_RESERVED_IDENTIFIER_FIXUP"), "uniforms must not be wrapped in spvc's default-block struct"); + } + + @Test + void selectionBoxFs_producesNamedUniformAndLocationedFragOutput() { + final String src = """ + #version 330 core + uniform vec4 u_Color; + out vec4 fragColor; + void main() { + fragColor = u_Color; + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "selection_box.frag"); + dumpOnFailure("selection_box.frag", src, es); + + assertNotNull(es); + assertContainsDecl(es, "vec4", "u_Color"); + assertTrue(es.contains("layout(location = 0)") || es.contains("layout(location=0)"), "fragment output must have layout(location=0)"); + } + + @Test + void celeritasChunk_impliedUvecVecPromotion_becomesExplicit() { + final String src = """ + #version 330 core + uniform mat4 u_ModelViewProjectionMatrix; + uvec3 unpack(uint p) { + return uvec3(p) >> uvec3(5u,0u,2u) & uvec3(7u,3u,7u); + } + vec3 translation(uint p) { + return unpack(p) * vec3(16.0); + } + void main() { + gl_Position = u_ModelViewProjectionMatrix * vec4(translation(0u), 1.0); + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_VERTEX_SHADER, "chunk.vert"); + dumpOnFailure("chunk.vert", src, es); + + assertNotNull(es); + assertFalse(es.contains("unpack(p) * vec3"), "uvec3 * vec3 must be made explicit by the SPIR-V round-trip"); + } + + @Test + void globalInitReferencingUniforms_survivesRoundTrip() { + final String src = """ + #version 330 core + struct Fog { vec4 color; float density; }; + uniform vec4 fogColor; + uniform float fogDensity; + Fog fog = Fog(fogColor, fogDensity); + void main() { + gl_Position = vec4(fog.density) + fog.color; + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_VERTEX_SHADER, "botania_fog.vert"); + dumpOnFailure("botania_fog.vert", src, es); + + assertNotNull(es); + assertFalse(es.contains("Fog fog = Fog(fogColor, fogDensity);"), "global init must be hoisted / inlined by the SPIR-V round-trip"); + } + + @Test + void uniformBool_roundTripsAsBool_notUint() { + final String src = """ + #version 330 core + uniform bool u_FogEnabled; + in vec4 color; + out vec4 fragColor; + void main() { + vec4 c = color; + if (u_FogEnabled) { + c.a *= 0.5; + } + fragColor = c; + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "cloud.frag"); + dumpOnFailure("cloud.frag (bool uniform)", src, es); + + assertNotNull(es); + assertContainsDecl(es, "bool", "u_FogEnabled"); + assertFalse(es.contains("uniform uint u_FogEnabled") || es.contains("uniform highp uint u_FogEnabled") || es.contains("uniform mediump uint u_FogEnabled"), + "emitted uniform must not be `uint` - `glUniform1i` only accepts int/bool uniforms"); + } + + @Test + void uniformBoolWithInitializer_roundTripsAsBool() { + final String src = """ + #version 330 core + uniform bool isRightHanded = true; + uniform bool heavyFog = false; + uniform bool firstPersonCamera = true; + in vec4 color; + out vec4 fragColor; + void main() { + float alpha = 1.0; + if (isRightHanded) alpha *= 0.9; + if (heavyFog) alpha *= 0.8; + if (firstPersonCamera) alpha *= 0.95; + fragColor = vec4(color.rgb, color.a * alpha); + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "iris_common_bool_init.frag"); + dumpOnFailure("iris_common_bool_init.frag", src, es); + + assertNotNull(es); + assertContainsDecl(es, "bool", "isRightHanded"); + assertContainsDecl(es, "bool", "heavyFog"); + assertContainsDecl(es, "bool", "firstPersonCamera"); + assertFalse(es.contains("uniform uint isRightHanded") || es.contains("uniform highp uint isRightHanded") || es.contains("uniform mediump uint isRightHanded"), + "isRightHanded must not be emitted as uint\n\n" + es); + } + + @Test + void varyingLocations_strippedFromVsOutAndFsIn_keptOnAttributesAndMrtOutputs() { + final String vs = """ + #version 330 core + layout(location = 0) in vec3 a_Position; + layout(location = 1) in vec4 a_Color; + uniform mat4 u_MVP; + out vec4 v_Color; + out vec2 v_TexCoord; + void main() { + v_Color = a_Color; + v_TexCoord = a_Position.xy; + gl_Position = u_MVP * vec4(a_Position, 1.0); + } + """; + final String fs = """ + #version 330 core + in vec2 v_TexCoord; + in vec4 v_Color; + uniform sampler2D u_Tex; + out vec4 fragColor; + void main() { + fragColor = v_Color * texture(u_Tex, v_TexCoord); + } + """; + + final String esVs = SpirvShaderTranslator.glslToGlslEs(vs, GL20.GL_VERTEX_SHADER, "strip.vert"); + final String esFs = SpirvShaderTranslator.glslToGlslEs(fs, GL20.GL_FRAGMENT_SHADER, "strip.frag"); + dumpOnFailure("strip.vert", vs, esVs); + dumpOnFailure("strip.frag", fs, esFs); + + assertNotNull(esVs); + assertNotNull(esFs); + + assertFalse(hasLayoutLocation(esVs, "v_Color")); + assertFalse(hasLayoutLocation(esVs, "v_TexCoord")); + assertFalse(hasLayoutLocation(esFs, "v_Color")); + assertFalse(hasLayoutLocation(esFs, "v_TexCoord")); + assertTrue(hasLayoutLocation(esVs, "a_Position")); + assertTrue(hasLayoutLocation(esVs, "a_Color")); + assertTrue(hasLayoutLocation(esFs, "fragColor")); + } + + @Test + void varyingLocations_strippedFromGeometryShaderInAndOut() { + final String gs = """ + #version 330 core + layout(triangles) in; + layout(triangle_strip, max_vertices = 3) out; + in vec4 v_Color[]; + in vec2 v_TexCoord[]; + out vec4 g_Color; + out vec2 g_TexCoord; + void main() { + for (int i = 0; i < 3; i++) { + gl_Position = gl_in[i].gl_Position; + g_Color = v_Color[i]; + g_TexCoord = v_TexCoord[i]; + EmitVertex(); + } + EndPrimitive(); + } + """; + + final String esGs = SpirvShaderTranslator.glslToGlslEs(gs, GL32.GL_GEOMETRY_SHADER, "passthrough.geom"); + dumpOnFailure("passthrough.geom", gs, esGs); + + assertNotNull(esGs); + assertFalse(hasLayoutLocation(esGs, "v_Color")); + assertFalse(hasLayoutLocation(esGs, "v_TexCoord")); + assertFalse(hasLayoutLocation(esGs, "g_Color")); + assertFalse(hasLayoutLocation(esGs, "g_TexCoord")); + } + + @Test + void vsInputs_preserveExplicitLayouts_stripAutoAssignedOnes() { + final String vs = """ + #version 330 core + layout(location = 0) in vec4 iris_Vertex; + layout(location = 1) in vec4 iris_Color; + layout(location = 2) in vec4 iris_MultiTexCoord0; + layout(location = 3) in vec4 iris_MultiTexCoord1; + layout(location = 4) in vec3 iris_Normal; + in vec4 mc_Entity; + in vec4 mc_midTexCoord; + in vec4 at_midBlock; + uniform mat4 iris_MVP; + out vec4 v_Color; + void main() { + v_Color = iris_Color + mc_Entity + at_midBlock + mc_midTexCoord; + gl_Position = iris_MVP * iris_Vertex; + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(vs, GL20.GL_VERTEX_SHADER, "gbuffers_terrain.vert"); + dumpOnFailure("gbuffers_terrain.vert", vs, es); + + assertNotNull(es); + // Explicit iris_* layouts preserved. + assertTrue(hasLayoutLocation(es, "iris_Vertex"), "iris_Vertex must keep its explicit layout"); + assertTrue(hasLayoutLocation(es, "iris_Color"), "iris_Color must keep its explicit layout"); + assertTrue(hasLayoutLocation(es, "iris_MultiTexCoord0"), "iris_MultiTexCoord0 must keep its explicit layout"); + assertTrue(hasLayoutLocation(es, "iris_MultiTexCoord1"), "iris_MultiTexCoord1 must keep its explicit layout"); + assertTrue(hasLayoutLocation(es, "iris_Normal"), "iris_Normal must keep its explicit layout"); + + assertFalse(hasLayoutLocation(es, "mc_Entity"), "mc_Entity layout must be stripped"); + assertFalse(hasLayoutLocation(es, "mc_midTexCoord"), "mc_midTexCoord layout must be stripped"); + assertFalse(hasLayoutLocation(es, "at_midBlock"), "at_midBlock layout must be stripped"); + } + + private static boolean hasLayoutLocation(String source, String name) { + final Pattern p = Pattern.compile( + "layout\\s*\\(\\s*location\\s*=\\s*\\d+\\s*\\)[^;]*?\\b" + + Pattern.quote(name) + "\\s*;"); + return p.matcher(source).find(); + } + + @Test + void vulkanReservedSamplerAsIdentifier_isRenamedBeforeShaderc() { + final String src = """ + #version 330 core + uniform sampler2D sampler; + in vec2 texCoord; + out vec4 fragColor; + void main() { + fragColor = texture(sampler, texCoord); + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "fontFilter.frag"); + dumpOnFailure("fontFilter.frag", src, es); + + assertNotNull(es); + assertTrue(es.contains("angelica_sampler_renamed")); + assertTrue(es.contains("sampler2D"), "sampler2D type must not be touched by the rename"); + } + + @Test + void uniformBool_multiDeclarator_allRestored() { + final String src = """ + #version 330 core + uniform bool a, b, c; + in vec4 color; + out vec4 fragColor; + void main() { + float alpha = 1.0; + if (a) alpha *= 0.9; + if (b) alpha *= 0.8; + if (c) alpha *= 0.7; + fragColor = vec4(color.rgb, color.a * alpha); + } + """; + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "multi_bool.frag"); + dumpOnFailure("multi_bool.frag", src, es); + + assertNotNull(es); + assertContainsDecl(es, "bool", "a"); + assertContainsDecl(es, "bool", "b"); + assertContainsDecl(es, "bool", "c"); + assertFalse(es.contains("uniform uint") || es.contains("uniform highp uint") || es.contains("uniform mediump uint"), + "no bool uniform should leak through as uint"); + } + + @Test + void uniformBool_compoundExpression_bothBranchesRewritten() { + final String src = """ + #version 330 core + uniform bool a; + uniform bool b; + in vec4 color; + out vec4 fragColor; + void main() { + vec4 c = color; + if (a && b) { c.a *= 0.5; } + fragColor = c; + } + """; + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "compound_bool.frag"); + dumpOnFailure("compound_bool.frag", src, es); + + assertNotNull(es); + assertFalse(es.contains("!= 0u"), "no bool use site should still compare against 0u"); + assertFalse(es.contains("uniform uint"), "bool uniforms must not leak as uint"); + } + + @Test + void uniformBool_throughDefaultBlock_restoresWithoutLeakingMemberSyntax() { + final String src = """ + #version 330 core + uniform bool u_Enabled; + uniform float u_Scale; + in vec4 color; + out vec4 fragColor; + void main() { + vec4 c = color; + if (u_Enabled) c.rgb *= u_Scale; + fragColor = c; + } + """; + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "bool_through_block.frag"); + dumpOnFailure("bool_through_block.frag", src, es); + + assertNotNull(es); + assertContainsDecl(es, "bool", "u_Enabled"); + assertFalse(es.contains("uniform uint") || es.contains("uniform highp uint") || es.contains("uniform mediump uint"), "bool uniform must be restored, not left as uint"); + assertFalse(es.contains("_RESERVED_IDENTIFIER_FIXUP_"), "default block struct must be unwrapped"); + + assertFalse(es.matches("(?s).*_[0-9]+\\.u_Enabled.*"), "no _NN.u_Enabled member access should leak into the emitted source"); + assertFalse(es.contains("!= 0u"), "no bool use-site should still be comparing against 0u"); + } + + @Test + void readonlyImage3D_staysAnImageUnderGLES() { + final String src = """ + #version 420 core + layout(r32ui) readonly uniform uimage3D voxel_img; + layout(location = 0) out vec4 fragColor; + void main() { + uint v = imageLoad(voxel_img, ivec3(1, 2, 3)).x; + fragColor = vec4(float(v)); + } + """; + + final String es = SpirvShaderTranslator.glslToGlslEs(src, GL20.GL_FRAGMENT_SHADER, "readonly_image.frag"); + dumpOnFailure("readonly_image.frag", src, es); + + assertNotNull(es); + assertTrue(es.startsWith("#version 320 es")); + assertTrue(es.contains("uimage3D"), "a read-only image must stay an image on GLES; SDL_GPU's separate-texture rewrite must not leak here\n\n" + es); + assertTrue(es.contains("imageLoad"), "the image must still be read with imageLoad\n\n" + es); + assertFalse(es.contains("usampler3D"), "rewriting to a sampler would silently unbind it - glBindImageTexture feeds an image unit, not a sampler\n\n" + es); + assertFalse(es.contains("texelFetch"), "texelFetch implies the sampler rewrite leaked into the GLES path\n\n" + es); + assertFalse(es.contains("GL_EXT_samplerless_texture_functions"), "the samplerless extension is an SDL_GPU concern and is not valid to inject here\n\n" + es); + } + + private static void assertContainsDecl(String source, String type, String name) { + final String needle1 = "uniform " + type + " " + name; + final String needle2 = "uniform highp " + type + " " + name; + final String needle3 = "uniform mediump " + type + " " + name; + assertTrue(source.contains(needle1) || source.contains(needle2) || source.contains(needle3), "expected top-level `uniform " + type + " " + name + "` in emitted GLSL ES"); + } + + private static void dumpOnFailure(String name, String src, String es) { + System.err.println("=== " + name + " ==="); + System.err.println("--- source ---"); + System.err.println(src); + System.err.println("--- emitted ---"); + System.err.println(es == null ? "(null - translator failed)" : es); + System.err.println("================"); + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBufferTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBufferTest.java index b6878ff66..c3deab62c 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBufferTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingBufferTest.java @@ -15,6 +15,8 @@ import java.nio.ByteBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @GLCompatTest @@ -55,7 +57,8 @@ class StreamingBufferTest { void persistent_uploadAlignment() { Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); - PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096); + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(4096); + assertNotNull(buf); try { ByteBuffer data = memAlloc(128); fillPattern(data); @@ -74,7 +77,8 @@ class StreamingBufferTest { void persistent_dataIntegrity() { Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); - PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096); + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(4096); + assertNotNull(buf); try { ByteBuffer data = memAlloc(128); for (int i = 0; i < 128; i++) data.put((byte) i); @@ -101,7 +105,8 @@ class StreamingBufferTest { Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); // Small ring: 1024 bytes. stride=16, alignUnit=64. - PersistentStreamingBuffer buf = new PersistentStreamingBuffer(1024); + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(1024); + assertNotNull(buf); try { int stride = 16; @@ -142,28 +147,24 @@ class StreamingBufferTest { void persistent_fenceReclaim() { Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); - PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096); + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(4096); + assertNotNull(buf); try { ByteBuffer data = memAlloc(1024); fillPattern(data); data.flip(); buf.upload(data, 32); + assertEquals(4096 - 1024, buf.getRemaining(), "upload consumes its bytes"); buf.postDraw(); - int remainingAfterUpload = buf.getRemaining(); - - GL11.glFinish(); // ensure fence completion - - // New upload triggers reclaim of first upload's bytes data.position(0).limit(512); buf.upload(data, 32); - - // After reclaim, remaining should be higher than before reclaim (minus new upload) - assertTrue(buf.getRemaining() > remainingAfterUpload, - "Remaining should increase after fence reclaim (minus new upload cost)"); - buf.postDraw(); + + GL11.glFinish(); + buf.postDraw(); + assertEquals(4096, buf.getRemaining(), "all fenced regions reclaimed after completion"); memFree(data); } finally { buf.destroy(); @@ -175,7 +176,8 @@ class StreamingBufferTest { Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); // Tiny ring: 256 bytes - PersistentStreamingBuffer buf = new PersistentStreamingBuffer(256); + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(256); + assertNotNull(buf); try { ByteBuffer data = memAlloc(512); fillPattern(data); @@ -189,6 +191,34 @@ class StreamingBufferTest { } } + + @Test + void persistent_createOrNullHonorsForceOrphan() { + assertNull(PersistentStreamingBuffer.createOrNull(1024, true)); + } + + @Test + void persistent_exhaustionReclaimsPendingWithoutPostDraw() { + Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required"); + + PersistentStreamingBuffer buf = PersistentStreamingBuffer.createOrNull(1024); + assertNotNull(buf); + try { + ByteBuffer data = memAlloc(512); + fillPattern(data); + data.flip(); + + assertTrue(buf.upload(data, 32) >= 0); + data.position(0).limit(512); + assertTrue(buf.upload(data, 32) >= 0); + data.position(0).limit(512); + assertTrue(buf.upload(data, 32) >= 0, "ring must self-fence and reclaim without postDraw"); + memFree(data); + } finally { + buf.destroy(); + } + } + // --- Utilities --- private static void fillPattern(ByteBuffer buf) { diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingDrawVAOBindingTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingDrawVAOBindingTest.java new file mode 100644 index 000000000..05fd5ac75 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingDrawVAOBindingTest.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizons.angelica.glsm.GLCompatTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +@GLCompatTest +public class StreamingDrawVAOBindingTest { + + private static final int FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT | VertexFlags.BRIGHTNESS_BIT; + + private static ByteBuffer triangle() { + final int vertexSize = DefaultVertexFormat.ALL_FORMATS[FLAGS].getVertexSize(); + final ByteBuffer buf = memAlloc(vertexSize * 3); + for (int i = 0; i < buf.capacity(); i++) buf.put(i, (byte) 0); + buf.position(0).limit(buf.capacity()); + return buf; + } + + @Test + void consecutiveDrawsKeepOneVaoBound() { + final ByteBuffer data = triangle(); + try { + TessellatorStreamingDrawer.drawPacked(data, GL11.GL_TRIANGLES, FLAGS, 3); + final int afterFirst = GLStateManager.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING); + assertNotEquals(0, afterFirst, "a streaming draw must leave its own VAO bound, not VAO 0"); + + data.position(0).limit(data.capacity()); + TessellatorStreamingDrawer.drawPacked(data, GL11.GL_TRIANGLES, FLAGS, 3); + final int afterSecond = GLStateManager.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING); + assertEquals(afterFirst, afterSecond, "the same format must reuse the same VAO across draws"); + + assertEquals(afterSecond, GL11.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING), "GLSM's cached binding must match the driver's"); + } finally { + memFree(data); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBufferTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBufferTest.java new file mode 100644 index 000000000..87c374f1c --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/UniformRingBufferTest.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL31; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class UniformRingBufferTest { + + private static final int BLOCK = 64; + private static final int CAPACITY = 1024; // 4 regions at 256-byte stride + + private static void fill(ByteBuffer src, int seed) { + for (int i = 0; i < BLOCK; i++) { + src.put(i, (byte) (seed + i)); + } + } + + private static void assertBlockAt(UniformRingBuffer ring, int offset, int seed) { + final ByteBuffer readback = memAlloc(BLOCK); + try { + GL15.glBindBuffer(GL31.GL_UNIFORM_BUFFER, ring.getBufferId()); + GL15.glGetBufferSubData(GL31.GL_UNIFORM_BUFFER, offset, readback); + GL15.glBindBuffer(GL31.GL_UNIFORM_BUFFER, 0); + for (int i = 0; i < BLOCK; i++) { + assertEquals((byte) (seed + i), readback.get(i), "byte " + i + " at offset " + offset); + } + } finally { + memFree(readback); + } + } + + @Test + void offsetsAdvanceByStrideAndWrap() { + final ByteBuffer src = memAlloc(BLOCK); + final UniformRingBuffer ring = new UniformRingBuffer(CAPACITY, BLOCK); + try { + assertEquals(256, ring.getStride(), "stride rounds the block up to UBO offset alignment"); + fill(src, 7); + assertEquals(0, ring.writeBlock(src)); + assertEquals(256, ring.writeBlock(src)); + assertEquals(512, ring.writeBlock(src)); + assertEquals(768, ring.writeBlock(src)); + assertEquals(0, ring.writeBlock(src), "fifth write wraps to the start"); + assertEquals(1, ring.getWraps()); + if (ring.isPersistent()) { + assertTrue(ring.getFencesIssued() > 0, "small ring must self-fence before wrapping"); + } + assertBlockAt(ring, 0, 7); + ring.endFrame(); + } finally { + ring.destroy(); + memFree(src); + } + } + + @Test + void orphanFallbackAdvancesAndWraps() { + final ByteBuffer src = memAlloc(BLOCK); + UniformRingBuffer ring = null; + try { + ring = new UniformRingBuffer(CAPACITY, BLOCK, true); + assertEquals(false, ring.isPersistent(), "forceOrphan must select the orphan path"); + fill(src, 11); + assertEquals(0, ring.writeBlock(src)); + fill(src, 42); + assertEquals(256, ring.writeBlock(src)); + assertEquals(BLOCK, src.remaining(), "writeBlock must not leave the staging buffer resized"); + assertBlockAt(ring, 0, 11); + assertBlockAt(ring, 256, 42); + assertEquals(512, ring.writeBlock(src)); + assertEquals(768, ring.writeBlock(src)); + assertEquals(0, ring.writeBlock(src), "orphan wrap restarts at zero"); + assertEquals(1, ring.getWraps()); + assertBlockAt(ring, 0, 42); + ring.endFrame(); + } finally { + if (ring != null) ring.destroy(); + memFree(src); + } + } +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/util/GLBit.java b/glsm/src/test/java/com/gtnewhorizons/angelica/util/GLBit.java index d3c1aa7b5..668f24f84 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/util/GLBit.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/util/GLBit.java @@ -1,41 +1,3 @@ package com.gtnewhorizons.angelica.util; -import java.util.Objects; - -public final class GLBit { - - private final int glEnum; - private final String name; - private final boolean initial; - - public GLBit(int glEnum, String name, boolean initial) { - this.name = name; - this.glEnum = glEnum; - this.initial = initial; - } - - public String name() {return name;} - - public int glEnum() {return glEnum;} - - public boolean initial() {return initial;} - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != this.getClass()) return false; - GLBit that = (GLBit) obj; - return Objects.equals(this.name, that.name) && this.glEnum == that.glEnum && this.initial == that.initial; - } - - @Override - public int hashCode() { - return Objects.hash(name, glEnum, initial); - } - - @Override - public String toString() { - return "GLBit[" + "name=" + name + ", " + "glEnum=" + glEnum + ", " + "initial=" + initial + ']'; - } - -} +public record GLBit(int glEnum, String name, boolean initial) {} diff --git a/glsm/src/test/resources/log4j2.xml b/glsm/src/test/resources/log4j2.xml new file mode 100644 index 000000000..c7749e5cf --- /dev/null +++ b/glsm/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLCompatTest.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLCompatTest.java similarity index 100% rename from glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLCompatTest.java rename to glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLCompatTest.java diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLCoreTest.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLCoreTest.java similarity index 100% rename from glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLCoreTest.java rename to glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLCoreTest.java diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java similarity index 87% rename from glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java rename to glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java index b5aded947..9f7c97b16 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMCoreExtension.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica.glsm; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMInitConfig; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; @@ -15,7 +17,7 @@ import org.lwjgl.opengl.PixelFormat; import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL; /** - * 3.3 core-profile context extension + * 3.3 core forward-compatible context. FFP emulation stays enabled, so per-test isolation only deactivates it. */ public class GLSMCoreExtension implements BeforeAllCallback, BeforeEachCallback, ExtensionContext.Store.CloseableResource { @@ -39,8 +41,7 @@ public class GLSMCoreExtension implements BeforeAllCallback, BeforeEachCallback, GLSMExtension.setMainThread(Thread.currentThread()); GLStateManager.initialize(GLSMInitConfig.builder().displaySize(800, 600).build()); GLStateManager.setRunningSplash(false); - GLStateManager.markSplashComplete(); - GLStateManager.BYPASS_CACHE = false; + GLStateManager.markSplashComplete("test"); GLSMExtension.glVendor = GL11.glGetString(GL11.GL_VENDOR); GLSMExtension.glRenderer = GL11.glGetString(GL11.GL_RENDERER); @@ -64,6 +65,10 @@ public class GLSMCoreExtension implements BeforeAllCallback, BeforeEachCallback, @Override public void beforeEach(ExtensionContext context) { while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + final ShaderManager ffp = ShaderManager.getInstance(); + if (ffp.isActive()) { + ffp.deactivate(); + } } @Override diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java similarity index 87% rename from glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java rename to glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java index bc9ddf619..e9cd6c206 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLSMExtension.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica.glsm; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMInitConfig; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; @@ -19,6 +21,7 @@ import sun.misc.Unsafe; import java.lang.reflect.Field; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL; public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ExecutionCondition, ExtensionContext.Store.CloseableResource { @@ -64,7 +67,9 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft if (started) return; try { displayMode = new DisplayMode(800, 600); - final GLSMInitConfig config = GLSMInitConfig.builder().displaySize(displayMode.getWidth(), displayMode.getHeight()).build(); + final GLSMInitConfig config = GLSMInitConfig.builder() + .displaySize(displayMode.getWidth(), displayMode.getHeight()) + .build(); setMainThread(Thread.currentThread()); latchRenderSystemOnCoreContext(config); @@ -76,8 +81,7 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft GLStateManager.initialize(config); GLStateManager.setRunningSplash(false); - GLStateManager.markSplashComplete(); - GLStateManager.BYPASS_CACHE = false; + GLStateManager.markSplashComplete("test"); context.getRoot().getStore(GLOBAL).put("GLSMExtension", this); glVendor = GL11.glGetString(GL11.GL_VENDOR); glRenderer = GL11.glGetString(GL11.GL_RENDERER); @@ -89,7 +93,8 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft final int profileMask = GL11.glGetInteger(GL32.GL_CONTEXT_PROFILE_MASK); if ((profileMask & GL32.GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) == 0) { - throw new IllegalStateException("Expected a GL compatibility context, got profile mask 0x" + Integer.toHexString(profileMask) + " (" + glVersion + ")"); + throw new IllegalStateException("Expected a GL compatibility context, got profile mask 0x" + + Integer.toHexString(profileMask) + " (" + glVersion + ")"); } started = true; } catch (LWJGLException | RuntimeException | Error e) { @@ -98,7 +103,6 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft } } - private static void latchRenderSystemOnCoreContext(GLSMInitConfig config) throws LWJGLException { Display.setDisplayModeAndFullscreen(displayMode); Display.setResizable(false); @@ -113,17 +117,6 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft } } - private static void forceBoundVAO(int value) { - try { - final Field f = GLStateManager.class.getDeclaredField("boundVAO"); - final Object base = theUnsafe.staticFieldBase(f); - final long offset = theUnsafe.staticFieldOffset(f); - theUnsafe.putInt(base, offset, value); - } catch (NoSuchFieldException e) { - throw new RuntimeException("Failed to force boundVAO", e); - } - } - static void setMainThread(Thread thread) { try { final Field f = GLStateManager.class.getDeclaredField("MainThread"); @@ -144,9 +137,15 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft public void beforeEach(ExtensionContext context) throws Exception { while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + final ShaderManager ffp = ShaderManager.getInstance(); + if (ffp.isActive()) { + ffp.deactivate(); + } + ffp.disable(); + // Force-sync VAO binding. Tests may unbind via raw GL, desynchronizing GLSM's cache. // Invalidate the cache so glBindVertexArray(0) actually issues the GL call. - forceBoundVAO(-1); + GLStateManager.ctx().boundVAO = -1; GLStateManager.glBindVertexArray(0); GL11.glMatrixMode(GL11.GL_MODELVIEW); @@ -168,6 +167,16 @@ public class GLSMExtension implements BeforeAllCallback, BeforeEachCallback, Aft @Override public void afterEach(ExtensionContext context) throws Exception { + boolean leakedRecorder = false; + for (int i = 0; i < 64 && DisplayListManager.isRecording(); i++) { + leakedRecorder = true; + DisplayListManager.glEndList(); + } + if (leakedRecorder) { + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + fail("Test leaked an open display-list recorder! Missing glEndList."); + } + final int error = GL11.glGetError(); assertEquals(GL11.GL_NO_ERROR, error, () -> "GL Error: 0x" + Integer.toHexString(error)); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLTestTags.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLTestTags.java similarity index 100% rename from glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLTestTags.java rename to glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/GLTestTags.java diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java new file mode 100644 index 000000000..876931dda --- /dev/null +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java @@ -0,0 +1,113 @@ +package com.gtnewhorizons.angelica.glsm.testutil; + +import com.gtnewhorizon.gtnhlib.reflect.Fields; +import com.gtnewhorizon.gtnhlib.reflect.Fields.LookupType; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public final class Reflect { + + private Reflect() {} + + public static Field field(Class owner, String name) { + for (Class c = owner; c != null; c = c.getSuperclass()) { + try { + final Field f = c.getDeclaredField(name); + f.setAccessible(true); + return f; + } catch (NoSuchFieldException ignored) { + } + } + throw new AssertionError("no field " + name + " on " + owner.getName() + " or its supertypes"); + } + + @SuppressWarnings("unchecked") + public static T get(Object target, String name) { + try { + return (T) field(target.getClass(), name).get(target); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + + @SuppressWarnings("unchecked") + public static T getStatic(Class owner, String name) { + try { + return (T) field(owner, name).get(null); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + + public static void set(Object target, String name, Object value) { + try { + field(target.getClass(), name).set(target, value); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + + public static void setStatic(Class owner, String name, Object value) { + try { + field(owner, name).set(null, value); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + + public static void setStaticFinal(Class owner, String name, Class type, F value) { + Fields.ofClass(owner).getField(LookupType.DECLARED_IN_HIERARCHY, name, type).setValue(null, value); + } + + public static void setDeclared(Class owner, Object target, String name, Object value) { + try { + field(owner, name).set(target, value); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + + @SuppressWarnings("unchecked") + public static T invoke(Object target, String name, Class[] signature, Object... args) { + try { + final Method m = resolve(target.getClass(), name, signature); + return (T) m.invoke(target, args); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + @SuppressWarnings("unchecked") + public static T invokeStatic(Class owner, String name, Class[] signature, Object... args) { + try { + return (T) resolve(owner, name, signature).invoke(null, args); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + @SuppressWarnings("unchecked") + public static T construct(Class owner) { + try { + final Constructor ctor = owner.getDeclaredConstructor(); + ctor.setAccessible(true); + return (T) ctor.newInstance(); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + private static Method resolve(Class owner, String name, Class[] signature) throws NoSuchMethodException { + for (Class c = owner; c != null; c = c.getSuperclass()) { + try { + final Method m = c.getDeclaredMethod(name, signature); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException ignored) { + } + } + throw new NoSuchMethodException(name + " on " + owner.getName() + " or its supertypes"); + } +} diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/TestPaths.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/TestPaths.java new file mode 100644 index 000000000..313d8cefc --- /dev/null +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/TestPaths.java @@ -0,0 +1,36 @@ +package com.gtnewhorizons.angelica.glsm.testutil; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public final class TestPaths { + + private TestPaths() {} + + public static Path repoRoot() { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null) { + if (Files.isRegularFile(dir.resolve("settings.gradle.kts"))) return dir; + dir = dir.getParent(); + } + throw new IllegalStateException("could not find repo root from " + Paths.get("").toAbsolutePath()); + } + + public static Path resolve(String repoRelative) { + return repoRoot().resolve(repoRelative); + } + + public static String readString(String repoRelative) { + final Path p = resolve(repoRelative); + if (!Files.isRegularFile(p)) throw new IllegalStateException("missing file: " + p); + try { + return Files.readString(p, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 000000000..d9dcb5870 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,77 @@ +[versions] +# Frozen to match what MC 1.7.10 / Forge ship. Do not bump. +lwjgl2 = "2.9.4-nightly-20150209" +guava = "18.0" +log4j = "2.0-beta9" +asmCompile = "5.0.3" +# End Frozen + +lwjgl3 = "3.4.2-20260602.093430-9" +lwjgl3ify = "3.0.31" + +celeritas = "2.5.9-GTNH" +gtnhlib = "0.11.36" +eventbus = "7.0-beta.15" +glslTransformLib = "0.2.0-33.g3ec381e" +antlr4Runtime = "4.13.2" +jcpp = "1.4.14" +tracy = "0.13.1" +retroFuturaBootstrap = "1.1.0" + +lombok = "1.18.46" +jetbrainsAnnotations = "26.0.2" +fastutil = "8.5.18" +joml = "1.10.8" +commonsLang3 = "3.17.0" +jvmDowngrader = "1.3.5" +junit = "5.14.1" +asmTest = "9.7" +mockito = "3.12.4" +archunit = "1.4.1" +ant = "1.8.2" + +[libraries] +celeritas-common = { module = "org.embeddedt.celeritas:celeritas-common", version.ref = "celeritas" } +celeritas-lwjgl2-service = { module = "org.embeddedt.celeritas:celeritas-lwjgl2-service", version.ref = "celeritas" } +eventbus = { module = "net.minecraftforge:eventbus", version.ref = "eventbus" } +glsl-transformation-lib = { module = "org.taumc:glsl-transformation-lib", version.ref = "glslTransformLib" } +antlr4-runtime = { module = "org.antlr:antlr4-runtime", version.ref = "antlr4Runtime" } +jcpp = { module = "org.anarres:jcpp", version.ref = "jcpp" } +lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } +annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrainsAnnotations" } +log4j-api = { module = "org.apache.logging.log4j:log4j-api", version.ref = "log4j" } +log4j-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "log4j" } +guava = { module = "com.google.guava:guava", version.ref = "guava" } +fastutil = { module = "it.unimi.dsi:fastutil", version.ref = "fastutil" } +joml = { module = "org.joml:joml", version.ref = "joml" } +commons-lang3 = { module = "org.apache.commons:commons-lang3", version.ref = "commonsLang3" } +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } + +# Versions come from junit-bom via platform() +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } +junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api" } +junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" } +junit-platform-engine = { module = "org.junit.platform:junit-platform-engine" } +junit-platform-reporting = { module = "org.junit.platform:junit-platform-reporting" } + +mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockito" } +archunit-junit5 = { module = "com.tngtech.archunit:archunit-junit5", version.ref = "archunit" } +ant = { module = "org.apache.ant:ant", version.ref = "ant" } +asm-tree-compile = { module = "org.ow2.asm:asm-tree", version.ref = "asmCompile" } +asm-tree-test = { module = "org.ow2.asm:asm-tree", version.ref = "asmTest" } +lwjgl2 = { module = "org.lwjgl.lwjgl:lwjgl", version.ref = "lwjgl2" } +lwjgl2-util = { module = "org.lwjgl.lwjgl:lwjgl_util", version.ref = "lwjgl2" } +lwjgl3 = { module = "org.lwjgl:lwjgl", version.ref = "lwjgl3" } +lwjgl3-opengl = { module = "org.lwjgl:lwjgl-opengl", version.ref = "lwjgl3" } +lwjgl3-sdl = { module = "org.lwjgl:lwjgl-sdl", version.ref = "lwjgl3" } +lwjgl3-spvc = { module = "org.lwjgl:lwjgl-spvc", version.ref = "lwjgl3" } +lwjgl3-shaderc = { module = "org.lwjgl:lwjgl-shaderc", version.ref = "lwjgl3" } + +# Consumed with an explicit :dev / :universal / :downgraded-8 classifier at the call site. +gtnhlib = { module = "com.github.GTNewHorizons:GTNHLib", version.ref = "gtnhlib" } +lwjgl3ify = { module = "com.github.GTNewHorizons:lwjgl3ify", version.ref = "lwjgl3ify" } +retrofuturabootstrap = { module = "com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap", version.ref = "retroFuturaBootstrap" } +jvmdowngrader-java-api = { module = "xyz.wagyourtail.jvmdowngrader:jvmdowngrader-java-api", version.ref = "jvmDowngrader" } + +[bundles] +lwjgl3-sdlgpu = ["lwjgl3", "lwjgl3-sdl", "lwjgl3-spvc", "lwjgl3-shaderc"] diff --git a/gradle/lwjgl-natives.settings.gradle.kts b/gradle/lwjgl-natives.settings.gradle.kts new file mode 100644 index 000000000..a29abc21e --- /dev/null +++ b/gradle/lwjgl-natives.settings.gradle.kts @@ -0,0 +1,19 @@ +// Applied from each build's settings file. Injects lwjglNatives +val osName = System.getProperty("os.name").lowercase() +val osArch = System.getProperty("os.arch").lowercase() + +val natives = when { + osName.contains("linux") && osArch.contains("aarch64") -> "natives-linux-arm64" + osName.contains("linux") -> "natives-linux" + osName.contains("windows") && osArch.contains("aarch64") -> "natives-windows-arm64" + osName.contains("windows") -> "natives-windows" + osName.contains("mac") && osArch.contains("aarch64") -> "natives-macos-arm64" + osName.contains("mac") -> "natives-macos" + else -> "natives-linux" +} + +gradle.rootProject { + allprojects { + extra["lwjglNatives"] = natives + } +} diff --git a/lwjgl3-backend/build.gradle.kts b/lwjgl3-backend/build.gradle.kts index 9d3d46221..661eabfd3 100644 --- a/lwjgl3-backend/build.gradle.kts +++ b/lwjgl3-backend/build.gradle.kts @@ -26,7 +26,7 @@ configurations { } } -val lwjglVersion = "3.4.2-SNAPSHOT" +val lwjglNatives: String by extra repositories { mavenLocal() @@ -60,30 +60,18 @@ repositories { dependencies { api(project(":glsm")) - compileOnly("com.github.GTNewHorizons:lwjgl3ify:3.0.31:dev") { isTransitive = false } - compileOnly("org.embeddedt.celeritas:celeritas-common:2.5.8-GTNH") { isTransitive = false } - - val osName = System.getProperty("os.name").lowercase() - val osArch = System.getProperty("os.arch").lowercase() - val lwjglNatives = when { - osName.contains("linux") && osArch.contains("aarch64") -> "natives-linux-arm64" - osName.contains("linux") -> "natives-linux" - osName.contains("windows") && osArch.contains("aarch64") -> "natives-windows-arm64" - osName.contains("windows") -> "natives-windows" - osName.contains("mac") && osArch.contains("aarch64") -> "natives-macos-arm64" - osName.contains("mac") -> "natives-macos" - else -> "natives-linux" - } + compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false } + compileOnly(libs.celeritas.common) { isTransitive = false } // LWJGL3 - implementation("org.lwjgl:lwjgl:${lwjglVersion}") - implementation("org.lwjgl:lwjgl-opengl:${lwjglVersion}") - compileOnly("org.lwjgl:lwjgl-sdl:${lwjglVersion}") - runtimeOnly("org.lwjgl:lwjgl:$lwjglVersion:$lwjglNatives") - runtimeOnly("org.lwjgl:lwjgl-opengl:$lwjglVersion:$lwjglNatives") + implementation(libs.lwjgl3) + implementation(libs.lwjgl3.opengl) + compileOnly(libs.lwjgl3.sdl) + runtimeOnly(libs.lwjgl3) { artifact { classifier = lwjglNatives } } + runtimeOnly(libs.lwjgl3.opengl) { artifact { classifier = lwjglNatives } } - compileOnly("org.apache.logging.log4j:log4j-api:2.0-beta9") - compileOnly("org.jetbrains:annotations:26.0.2") + compileOnly(libs.log4j.api) + compileOnly(libs.annotations) } tasks.named("jar") { diff --git a/lwjgl3-backend/src/main/java/com/gtnewhorizons/angelica/lwjgl3/Lwjgl3GLRenderBackend.java b/lwjgl3-backend/src/main/java/com/gtnewhorizons/angelica/lwjgl3/Lwjgl3GLRenderBackend.java index 164ef9b4b..8da92b3e8 100644 --- a/lwjgl3-backend/src/main/java/com/gtnewhorizons/angelica/lwjgl3/Lwjgl3GLRenderBackend.java +++ b/lwjgl3-backend/src/main/java/com/gtnewhorizons/angelica/lwjgl3/Lwjgl3GLRenderBackend.java @@ -1,8 +1,13 @@ package com.gtnewhorizons.angelica.lwjgl3; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLESCaps; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.glsm.backend.DebugMessageHandler; import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.ARBClearTexture; import org.lwjgl.opengl.EXTDirectStateAccess; import org.lwjgl.opengl.GL; @@ -21,13 +26,21 @@ import org.lwjgl.opengl.GL42C; import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL44C; import org.lwjgl.opengl.GL45C; +import org.lwjgl.opengl.GL46C; +import org.lwjgl.opengl.ARBPolygonOffsetClamp; +import org.lwjgl.opengl.EXTPolygonOffsetClamp; +import org.lwjgl.opengl.EXTShaderImageLoadStore; import org.lwjgl.opengl.GLCapabilities; import org.lwjgl.opengl.GLDebugMessageCallback; import org.lwjgl.sdl.SDL_DropEvent; import org.lwjgl.sdl.SDL_EventFilter; import org.lwjgl.sdl.SDLEvents; +import org.lwjgl.sdl.SDLVideo; +import org.lwjgl.system.JNI; import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; @@ -46,6 +59,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; */ @Lwjgl3Aware public final class Lwjgl3GLRenderBackend extends RenderBackend { + private static final Logger LOGGER = LogManager.getLogger("Lwjgl3GLRenderBackend"); + private GLCapabilities caps; private GLDebugMessageCallback debugCallback; private boolean debugOutputActive; @@ -57,8 +72,15 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void init() { caps = GL.getCapabilities(); + if (RenderSystem.isGLES()) { + pfnClearDepthf = GL.getFunctionProvider().getFunctionAddress("glClearDepthf"); + pfnDepthRangef = GL.getFunctionProvider().getFunctionAddress("glDepthRangef"); + } } + private long pfnClearDepthf; + private long pfnDepthRangef; + @Override public void shutdown() { stopFileDrop(); @@ -131,35 +153,60 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { } } + @Override + public boolean isCurrent() { + try { + return GL.getCapabilities() != null; + } catch (IllegalStateException e) { + return false; + } + } + @Override public int getPriority() { return 50; } @Override public int getMinGLSLVersion() {return 330;} + @Override + public void setVSyncEnabled(boolean enabled) {SDLVideo.SDL_GL_SetSwapInterval(enabled ? 1 : 0);} + + @Override + public boolean isAnisotropicSupported() { + return caps != null && caps.GL_EXT_texture_filter_anisotropic; + } + @Override public void flush() {GL11C.glFlush();} @Override public void finish() {GL11C.glFinish();} + private static boolean capAllowed(int cap) { + return GLESCaps.isCapAllowed(cap, RenderSystem.isGLES(), RenderSystem.hasClipCullDistance()); + } + @Override public void enable(int cap) { + if (!capAllowed(cap)) return; GL11C.glEnable(cap); } @Override public void enablei(int cap, int index) { + if (!capAllowed(cap)) return; GL30C.glEnablei(cap, index); } @Override public void disable(int cap) { + if (!capAllowed(cap)) return; GL11C.glDisable(cap); } @Override public void disablei(int cap, int index) { + if (!capAllowed(cap)) return; GL30C.glDisablei(cap, index); } @@ -220,6 +267,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void polygonMode(int face, int mode) { + if (RenderSystem.isGLES()) return; GL11C.glPolygonMode(face, mode); } @@ -228,6 +276,21 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { GL11C.glPolygonOffset(factor, units); } + @Override + public void polygonOffsetClamp(float factor, float units, float clamp) { + if (caps == null) { + super.polygonOffsetClamp(factor, units, clamp); + } else if (caps.OpenGL46) { + GL46C.glPolygonOffsetClamp(factor, units, clamp); + } else if (caps.GL_ARB_polygon_offset_clamp) { + ARBPolygonOffsetClamp.glPolygonOffsetClamp(factor, units, clamp); + } else if (caps.GL_EXT_polygon_offset_clamp) { + EXTPolygonOffsetClamp.glPolygonOffsetClampEXT(factor, units, clamp); + } else { + super.polygonOffsetClamp(factor, units, clamp); + } + } + @Override public void stencilFunc(int func, int ref, int mask) { GL11C.glStencilFunc(func, ref, mask); @@ -265,6 +328,10 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void depthRange(double nearVal, double farVal) { + if (RenderSystem.isGLES()) { + JNI.callV((float) nearVal, (float) farVal, pfnDepthRangef); + return; + } GL11C.glDepthRange(nearVal, farVal); } @@ -280,6 +347,10 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void clearDepth(double depth) { + if (RenderSystem.isGLES()) { + JNI.callV((float) depth, pfnClearDepthf); + return; + } GL11C.glClearDepth(depth); } @@ -300,11 +371,13 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void pointSize(float size) { + if (RenderSystem.isGLES()) return; GL11C.glPointSize(size); } @Override public void logicOp(int opcode) { + if (RenderSystem.isGLES()) return; GL11C.glLogicOp(opcode); } @@ -340,7 +413,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void drawElements(int mode, int count, int type, ByteBuffer indices) { - GL11C.glDrawElements(mode, count, type, org.lwjgl.system.MemoryUtil.memAddress(indices)); + GL11C.glDrawElements(mode, count, type, MemoryUtil.memAddress(indices)); } @Override @@ -355,6 +428,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void provokingVertex(int provokeMode) { + if (RenderSystem.isGLES()) return; GL32C.glProvokingVertex(provokeMode); } @@ -971,6 +1045,32 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { GL30C.glBindBufferBase(target, index, buffer); } + @Override + public void bindBufferRange(int target, int index, int buffer, long offset, long size) { + GL30C.glBindBufferRange(target, index, buffer, offset, size); + } + + @Override + public int getUniformBlockIndex(int program, CharSequence name) { + return GL31C.glGetUniformBlockIndex(program, name); + } + + @Override + public void uniformBlockBinding(int program, int blockIndex, int binding) { + GL31C.glUniformBlockBinding(program, blockIndex, binding); + } + + @Override + public int getIndexedBufferBinding(int target, int index) { + final int pname = (target == GL43C.GL_SHADER_STORAGE_BUFFER) ? GL43C.GL_SHADER_STORAGE_BUFFER_BINDING : GL31C.GL_UNIFORM_BUFFER_BINDING; + return GL31C.glGetIntegeri(pname, index); + } + + @Override + public int getIntegerIndexed(int pname, int index) { + return GL31C.glGetIntegeri(pname, index); + } + @Override public void bufferData(int target, long size, int usage) { GL15C.glBufferData(target, size, usage); @@ -1063,29 +1163,67 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void getBufferSubData(int target, long offset, ByteBuffer data) { + if (RenderSystem.isGLES()) { getBufferSubDataES(target, offset, data); return; } GL15C.glGetBufferSubData(target, offset, data); } @Override public void getBufferSubData(int target, long offset, ShortBuffer data) { + if (RenderSystem.isGLES()) { getBufferSubDataES(target, offset, data); return; } GL15C.glGetBufferSubData(target, offset, data); } @Override public void getBufferSubData(int target, long offset, IntBuffer data) { + if (RenderSystem.isGLES()) { getBufferSubDataES(target, offset, data); return; } GL15C.glGetBufferSubData(target, offset, data); } @Override public void getBufferSubData(int target, long offset, FloatBuffer data) { + if (RenderSystem.isGLES()) { getBufferSubDataES(target, offset, data); return; } GL15C.glGetBufferSubData(target, offset, data); } @Override public void getBufferSubData(int target, long offset, DoubleBuffer data) { + if (RenderSystem.isGLES()) { getBufferSubDataES(target, offset, data); return; } GL15C.glGetBufferSubData(target, offset, data); } + private static void getBufferSubDataES(int target, long offset, Buffer dst) { + final int elementBytes; + if (dst instanceof ByteBuffer) elementBytes = 1; + else if (dst instanceof ShortBuffer) elementBytes = 2; + else if (dst instanceof IntBuffer || dst instanceof FloatBuffer) elementBytes = 4; + else if (dst instanceof DoubleBuffer) elementBytes = 8; + else throw new IllegalArgumentException("unsupported buffer: " + dst.getClass().getName()); + + final long length = (long) dst.remaining() * elementBytes; + final ByteBuffer mapped = GL30C.glMapBufferRange(target, offset, length, GL30C.GL_MAP_READ_BIT); + if (mapped == null) { + LOGGER.warn("glMapBufferRange returned null in getBufferSubDataES (target=0x{}, offset={}, length={})", Integer.toHexString(target), offset, length); + return; + } + try { + if (dst.isDirect()) { + MemoryUtil.memCopy(MemoryUtil.memAddress(mapped), MemoryUtil.memAddress(dst), length); + } else { + switch (dst) { + case ByteBuffer bb -> bb.duplicate().put(mapped.duplicate()); + case ShortBuffer sb -> sb.duplicate().put(mapped.asShortBuffer()); + case IntBuffer ib -> ib.duplicate().put(mapped.asIntBuffer()); + case FloatBuffer fb -> fb.duplicate().put(mapped.asFloatBuffer()); + case DoubleBuffer db -> db.duplicate().put(mapped.asDoubleBuffer()); + default -> { + } + } + } + } finally { + GL30C.glUnmapBuffer(target); + } + } + @Override public int getBufferParameteri(int target, int pname) { return GL15C.glGetBufferParameteri(target, pname); @@ -1096,6 +1234,16 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { return GL15C.glIsBuffer(buffer); } + @Override + public boolean isTexture(int texture) { + return GL11C.glIsTexture(texture); + } + + @Override public boolean isFramebuffer(int framebuffer) { return GL30C.glIsFramebuffer(framebuffer); } + @Override public boolean isRenderbuffer(int renderbuffer) { return GL30C.glIsRenderbuffer(renderbuffer); } + @Override public boolean isSampler(int sampler) { return GL33C.glIsSampler(sampler); } + @Override public boolean isQuery(int query) { return GL15C.glIsQuery(query); } + @Override public ByteBuffer mapBufferRange(int target, long offset, long length, int access) { return GL30C.glMapBufferRange(target, offset, length, access); @@ -1106,6 +1254,11 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { GL30C.glFlushMappedBufferRange(target, offset, length); } + @Override + public long mapBufferRangeAddress(int target, long offset, long length, int access) { + return GL30C.nglMapBufferRange(target, offset, length, access); + } + @Override public int genVertexArrays() { return GL30C.glGenVertexArrays(); @@ -1133,7 +1286,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void vertexAttribPointer(int index, int size, int type, boolean normalized, int stride, ByteBuffer pointer) { - GL20C.glVertexAttribPointer(index, size, type, normalized, stride, org.lwjgl.system.MemoryUtil.memAddress(pointer)); + GL20C.glVertexAttribPointer(index, size, type, normalized, stride, MemoryUtil.memAddress(pointer)); } @Override @@ -1143,7 +1296,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void vertexAttribIPointer(int index, int size, int type, int stride, ByteBuffer pointer) { - GL30C.glVertexAttribIPointer(index, size, type, stride, org.lwjgl.system.MemoryUtil.memAddress(pointer)); + GL30C.glVertexAttribIPointer(index, size, type, stride, MemoryUtil.memAddress(pointer)); } @Override @@ -1321,6 +1474,11 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { return GL45C.glGetTextureParameteri(texture, pname); } + @Override + public float getTextureParameterf(int texture, int target, int pname) { + return GL45C.glGetTextureParameterf(texture, pname); + } + @Override public int getTextureLevelParameteri(int texture, int level, int pname) { return GL45C.glGetTextureLevelParameteri(texture, level, pname); @@ -1386,6 +1544,59 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { GL32C.glDeleteSync(sync); } + @Override + public boolean supportsGpuProfiling() { + if (!caps.OpenGL33 && !caps.GL_ARB_timer_query) return false; + return GL15C.glGetQueryi(GL33C.GL_TIMESTAMP, GL15C.GL_QUERY_COUNTER_BITS) > 0; + } + + @Override + public int genQuery() { + return GL15C.glGenQueries(); + } + + @Override + public void deleteQuery(int query) { + GL15C.glDeleteQueries(query); + } + + @Override + public void queryCounter(int query) { + GL33C.glQueryCounter(query, GL33C.GL_TIMESTAMP); + } + + @Override + public boolean isQueryResultAvailable(int query) { + return GL15C.glGetQueryObjecti(query, GL15C.GL_QUERY_RESULT_AVAILABLE) != 0; + } + + @Override + public long getQueryResult64(int query) { + return GL33C.glGetQueryObjectui64(query, GL15C.GL_QUERY_RESULT); + } + + @Override + public long getGpuTimestamp() { + return GL32C.glGetInteger64(GL33C.GL_TIMESTAMP); + } + + @Override public void genQueries(IntBuffer ids) { GL15C.glGenQueries(ids); } + @Override public int genQueries() { return GL15C.glGenQueries(); } + @Override public void deleteQueries(int id) { GL15C.glDeleteQueries(id); } + @Override public void beginQuery(int target, int id) { GL15C.glBeginQuery(target, id); } + @Override public void endQuery(int target) { GL15C.glEndQuery(target); } + @Override public void getQueryObjectui(int id, int pname, IntBuffer params) { GL15C.glGetQueryObjectuiv(id, pname, params); } + @Override public int getQueryObjecti(int id, int pname) { return GL15C.glGetQueryObjecti(id, pname); } + + @Override public void waitSync(long sync, int flags, long timeout) { GL32C.glWaitSync(sync, flags, timeout); } + @Override public int getSynci(long sync, int pname, IntBuffer length) { return GL32C.glGetSynci(sync, pname, length); } + @Override public void queryCounter(int id, int target) { GL33C.glQueryCounter(id, target); } + @Override public long getQueryObjectui64(int id, int pname) { return GL33C.glGetQueryObjectui64(id, pname); } + @Override public void uniform3fv(int location, float[] values) { GL20C.glUniform3fv(location, values); } + @Override public void uniform4fv(int location, float[] values) { GL20C.glUniform4fv(location, values); } + @Override public void getInteger(int pname, int[] params) { GL11C.glGetIntegerv(pname, params); } + @Override public void bindFragDataLocation(int program, int colorNumber, CharSequence name) { GL30C.glBindFragDataLocation(program, colorNumber, name); } + @Override public void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, ByteBuffer data) { GL43C.glClearBufferSubData(target, internalFormat, offset, size, format, type, data); @@ -1402,7 +1613,13 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { @Override public void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { - GL42C.glBindImageTexture(unit, texture, level, layered, layer, access, format); + if (GLStateManager.capabilities.OpenGL42 || GLStateManager.capabilities.GL_ARB_shader_image_load_store) { + GL42C.glBindImageTexture(unit, texture, level, layered, layer, access, format); + } else if (GLStateManager.capabilities.GL_EXT_shader_image_load_store) { + EXTShaderImageLoadStore.glBindImageTextureEXT(unit, texture, level, layered, layer, access, format); + } else { + GLStateManager.warnOnce("bindImageTexture", "glBindImageTexture ignored: no image load/store support"); + } } @Override @@ -1496,4 +1713,89 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend { GL43C.glDebugMessageInsert(source, type, id, severity, message); } + @Override + public void debugMessageControl(int source, int type, int severity, IntBuffer ids, boolean enabled) { + GL43C.glDebugMessageControl(source, type, severity, ids, enabled); + } + + @Override + public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { + GL14C.glMultiDrawArrays(mode, firsts, counts); + } + + @Override + public void primitiveRestartIndex(int index) { + GL31C.glPrimitiveRestartIndex(index); + } + + @Override + public void pointParameterf(int pname, float param) { + GL14C.glPointParameterf(pname, param); + } + + @Override + public void pointParameteri(int pname, int param) { + GL14C.glPointParameteri(pname, param); + } + + @Override + public void getActiveAttrib(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) { + final String nameStr = GL20C.glGetActiveAttrib(program, index, size, type); + if (name != null && nameStr != null) { + final byte[] bytes = nameStr.getBytes(StandardCharsets.UTF_8); + final int n = Math.min(bytes.length, name.remaining()); + name.put(bytes, 0, n); + if (length != null && length.remaining() > 0) length.put(0, n); + } + } + + @Override + public String getActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) { + try (MemoryStack stack = MemoryStack.stackPush()) { + final IntBuffer size = stack.callocInt(1); + final IntBuffer type = stack.callocInt(1); + final String name = GL20C.glGetActiveAttrib(program, index, size, type); + if (sizeType != null && sizeType.remaining() >= 2) { + sizeType.put(0, size.get(0)); + sizeType.put(1, type.get(0)); + } + return name; + } + } + + @Override + public int genRenderbuffers() { + return GL30C.glGenRenderbuffers(); + } + + @Override + public void deleteRenderbuffers(int renderbuffer) { + GL30C.glDeleteRenderbuffers(renderbuffer); + } + + @Override + public void bindRenderbuffer(int target, int renderbuffer) { + GL30C.glBindRenderbuffer(target, renderbuffer); + } + + @Override + public void renderbufferStorage(int target, int internalformat, int width, int height) { + GL30C.glRenderbufferStorage(target, internalformat, width, height); + } + + @Override + public void renderbufferStorageMultisample(int target, int samples, int internalformat, int width, int height) { + GL30C.glRenderbufferStorageMultisample(target, samples, internalformat, width, height); + } + + @Override + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer) { + GL30C.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + } + + @Override + public void clearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) { + GL43C.glClearBufferData(target, internalformat, format, type, data); + } + } diff --git a/scripts/flyby-capture.sh b/scripts/flyby-capture.sh new file mode 100755 index 000000000..084bfdcab --- /dev/null +++ b/scripts/flyby-capture.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Run a flyby benchmark under using tracy-capture +# +# * Launches the game with the flyby properties set and tracy-capture +# * Game waits for the tracy connection, runs the route, returns to the original coordinates and exits. +# * tracy-capture finalizes +# +# Usage: scripts/flyby-capture.sh [route] [length] +# route - straight | pan | circuit | static +# length - Units: blocks (straight), blocks per leg (circuit), degrees (pan), ticks (static). +# +# FLYBY_SPEED - blocks per tick. (0.5 ~= creative flight). +# +# Requires tracy-capture on PATH (TRACY_CAPTURE=/path/to/tracy-capture). +# Launch the game to the main menu and load your benchmark save; the run starts once the world is up. +# +# Ensure the chunks in the route have been generated before capturing + +set -euo pipefail + +OUT="${1:?usage: flyby-capture.sh [route] [length]}" +ROUTE="${2:-straight}" +LENGTH="${3:-0}" +WARMUP="${FLYBY_WARMUP:-400}" +TRACY_CAPTURE="${TRACY_CAPTURE:-tracy-capture}" + +if ! command -v "$TRACY_CAPTURE" >/dev/null 2>&1 && [ ! -x "$TRACY_CAPTURE" ]; then + cat >&2 <<'EOF' +error: tracy-capture not found. + +Build and launch with: TRACY_CAPTURE=/path/to/tracy/capture/build/tracy-capture scripts/flyby-capture.sh ... +EOF + exit 1 +fi + +if [ -e "$OUT" ]; then + echo "error: $OUT already exists; refusing to overwrite a capture" >&2 + exit 1 +fi + +echo "==> starting capture -> $OUT" +if [ -n "${CAPTURE_SECONDS:-}" ]; then + "$TRACY_CAPTURE" -o "$OUT" -s "$CAPTURE_SECONDS" & +else + "$TRACY_CAPTURE" -o "$OUT" & +fi +CAPTURE_PID=$! + +cleanup() { + if kill -0 "$CAPTURE_PID" 2>/dev/null; then + echo "==> stopping capture" + kill -INT "$CAPTURE_PID" 2>/dev/null || true + wait "$CAPTURE_PID" 2>/dev/null || true + fi +} +trap cleanup EXIT + +echo "==> launching game (route=$ROUTE warmup=$WARMUP length=${LENGTH:-default})" +echo " load your benchmark save once the main menu appears" + +./gradlew runClient25 --console=plain \ + -Dangelica.flyby.route="$ROUTE" \ + -Dangelica.flyby.length="$LENGTH" \ + -Dangelica.flyby.speed="${FLYBY_SPEED:-0}" \ + -Dangelica.flyby.warmupTicks="$WARMUP" \ + -Dangelica.flyby.waitForTracy=true \ + -Dangelica.flyby.exitWhenDone=true + +echo "==> game exited, finalising capture" +cleanup +trap - EXIT + +if [ -s "$OUT" ]; then + echo "==> wrote $OUT ($(du -h "$OUT" | cut -f1))" +else + echo "error: $OUT is empty - did the game connect to Tracy?" >&2 + exit 1 +fi diff --git a/sdl-gpu/build.gradle.kts b/sdl-gpu/build.gradle.kts new file mode 100644 index 000000000..b0a52592b --- /dev/null +++ b/sdl-gpu/build.gradle.kts @@ -0,0 +1,123 @@ +plugins { + `java-library` + `maven-publish` +} + +version = rootProject.version + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(25)) + withSourcesJar() +} + +val rfgObfAttr = Attribute.of("com.gtnewhorizons.retrofuturagradle.obfuscation", String::class.java) +val rfgTransformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean::class.javaObjectType) + +configurations { + listOf("apiElements", "runtimeElements").forEach { name -> + named(name) { + attributes { + attribute(rfgObfAttr, "mcp") + attribute(rfgTransformedAttr, true) + } + } + } +} + +val lwjglNatives: String by extra + +repositories { + mavenLocal() + maven { + name = "Mojang" + url = uri("https://libraries.minecraft.net") + } + maven { + name = "GTNH Maven" + url = uri("https://nexus.gtnewhorizons.com/repository/public/") + } + maven { + name = "Forge" + url = uri("https://maven.minecraftforge.net/") + } + maven { + name = "taumc" + url = uri("https://maven.taumc.org/releases") + } + maven { + name = "Sonatype Snapshots" + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } + maven { + name = "Maven Central Snapshots" + url = uri("https://central.sonatype.com/repository/maven-snapshots/") + } + mavenCentral() +} + +dependencies { + api(project(":glsm")) + + compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false } + compileOnly(libs.celeritas.common) { isTransitive = false } + + // GL enum constants (compileOnly -- no runtime GL dependency) + compileOnly(libs.lwjgl3.opengl) + + // LWJGL3 core + SDL3 GPU + SPIRV-Cross + shaderc + implementation(libs.bundles.lwjgl3.sdlgpu) + libs.bundles.lwjgl3.sdlgpu.get().forEach { + runtimeOnly(it) { artifact { classifier = lwjglNatives } } + } + + compileOnly(libs.log4j.api) + compileOnly(libs.annotations) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(testFixtures(project(":glsm"))) + testImplementation(libs.lwjgl3.opengl) + // GL. loads liblwjgl_opengl.so. Test scope only: a root-level runtimeOnly collides with lwjgl3Bindings. + testRuntimeOnly(libs.lwjgl3.opengl) { artifact { classifier = lwjglNatives } } + testRuntimeOnly(libs.junit.platform.launcher) + testRuntimeOnly(libs.log4j.core) + testRuntimeOnly(libs.fastutil) +} + +tasks.test { + useJUnitPlatform() + if (System.getProperty("os.name").startsWith("Mac")) { + jvmArgs("-XstartOnFirstThread") + } +} + +tasks.named("jar") { + manifest { + attributes( + "Lwjgl3ify-Aware" to "true" + ) + } +} + +publishing { + publications { + create("mavenJava") { + groupId = "com.gtnewhorizons.angelica" + artifactId = "sdl-gpu" + version = rootProject.version.toString() + from(components["java"]) + } + } + repositories { + if (System.getenv("MAVEN_USER") != null) { + maven { + name = "GTNHMaven" + url = uri(rootProject.findProperty("mavenPublishUrl")?.toString() ?: "https://nexus.gtnewhorizons.com/repository/releases/") + credentials { + username = System.getenv("MAVEN_USER") + password = System.getenv("MAVEN_PASSWORD") + } + } + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUDisplayBridge.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUDisplayBridge.java new file mode 100644 index 000000000..b20c4f584 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUDisplayBridge.java @@ -0,0 +1,61 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.sdlgpu.device.SDLDrawable; +import org.lwjglx.opengl.Display; +import org.lwjglx.opengl.Drawable; +import org.lwjglx.opengl.DrawableGL; +import org.lwjglx.opengl.SharedDrawable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; + +public final class SDLGPUDisplayBridge { + private SDLGPUDisplayBridge() {} + + private static volatile boolean drawableInstalled; + + private static final VarHandle DISPLAY_DRAWABLE_FIELD; + private static final VarHandle SHARED_DRAWABLE_WRAPPED_FIELD; + static { + final VarHandle displayDrawableField; + final VarHandle sharedDrawableWrappedField; + try { + displayDrawableField = MethodHandles.privateLookupIn(Display.class, MethodHandles.lookup()).findStaticVarHandle(Display.class, "drawable", DrawableGL.class); + sharedDrawableWrappedField = MethodHandles.privateLookupIn(SharedDrawable.class, MethodHandles.lookup()).findVarHandle(SharedDrawable.class, "drawable", Drawable.class); + } catch (IllegalAccessException | NoSuchFieldException e) { + throw new ExceptionInInitializerError(e); + } + DISPLAY_DRAWABLE_FIELD = displayDrawableField; + SHARED_DRAWABLE_WRAPPED_FIELD = sharedDrawableWrappedField; + } + + public static void ensureDrawableInstalled() { + if (drawableInstalled) return; + if (!SDLGPUGate.isActive()) return; + if (DISPLAY_DRAWABLE_FIELD.get() == null) { + DISPLAY_DRAWABLE_FIELD.set(new SDLDrawable()); + } + drawableInstalled = true; + } + + public static void present() { + if (SDLGPUGate.isActive()) { + BackendManager.RENDER_BACKEND.handleSwapBuffers(); + } + } + + public static void releaseRenderThread() { + if (SDLGPUGate.isActive()) { + BackendManager.RENDER_BACKEND.onRenderThreadReleased(Thread.currentThread()); + } + } + + public static boolean isSdlDrawable(SharedDrawable sd) { + return sd != null && SHARED_DRAWABLE_WRAPPED_FIELD.get(sd) instanceof SDLDrawable; + } + + public static boolean isSdlSharedDrawable(Object drawable) { + return drawable instanceof SharedDrawable && isSdlDrawable((SharedDrawable) drawable); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUGate.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUGate.java new file mode 100644 index 000000000..9acfa03ce --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUGate.java @@ -0,0 +1,60 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import static org.lwjgl.sdl.SDLVideo.SDL_PROP_WINDOW_CREATE_METAL_BOOLEAN; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import org.lwjgl.sdl.SDLProperties; +import org.lwjgl.system.Platform; +import org.lwjglx.Sys; +import org.lwjglx.opengl.ContextAttribs; +import org.lwjglx.opengl.Display; +import org.lwjglx.opengl.PixelFormat; + +import me.eigenraven.lwjgl3ify.api.DisplayEvents; +import me.eigenraven.lwjgl3ify.api.DisplayWindowContext; +import me.eigenraven.lwjgl3ify.api.SwapchainInvalidatingChange; + +import java.util.function.Consumer; + +public final class SDLGPUGate { + + private SDLGPUGate() {} + + private static volatile boolean fatalInit; + + public static void markFatalInit() { fatalInit = true; } + + public static boolean isFatalInit() { return fatalInit; } + + public static boolean isSDLGPUAvailable() { + return SDLGPUGate.class.getClassLoader().getResource("org/lwjgl/sdl/SDLGPU.class") != null; + } + + public static boolean isActive() { + if (!isSDLGPUAvailable()) return false; + final RenderBackend rb = BackendManager.RENDER_BACKEND; + return rb instanceof SDLGPURenderBackend; + } + + public static Consumer sdlGpuPreWindowCreateCallback() { + if (Platform.get() != Platform.MACOSX) return null; + return ctx -> Sys.checkSdl(SDLProperties.SDL_SetBooleanProperty(ctx.props(), SDL_PROP_WINDOW_CREATE_METAL_BOOLEAN, true)); + } + + public static Consumer sdlGpuPostWindowCreateCallback(boolean debug) { + return ctx -> BackendManager.RENDER_BACKEND.onPostWindowCreate(ctx.window(), debug); + } + + public static Consumer sdlGpuPreSwapchainInvalidatingCallback() { + return change -> BackendManager.RENDER_BACKEND.onPreSwapchainInvalidatingChange(change); + } + + public static void createSDLGPUDisplay(Object format, Object attribs, boolean debug) { + DisplayEvents.setCreateGLContext(false); + final Consumer pre = sdlGpuPreWindowCreateCallback(); // null on non-Mac + if (pre != null) DisplayEvents.addPreWindowCreateListener(pre); + DisplayEvents.addPostWindowCreateListener(sdlGpuPostWindowCreateCallback(debug)); + Display.create((PixelFormat) format, (ContextAttribs) attribs, /*sharedWindow*/ 0L); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPULWJGLService.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPULWJGLService.java new file mode 100644 index 000000000..83eb10a3b --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPULWJGLService.java @@ -0,0 +1,255 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.sdlgpu.device.MemoryStackWrapper; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import com.mitchej123.lwjgl.DebugMessageHandler; +import com.mitchej123.lwjgl.GLExtension; +import com.mitchej123.lwjgl.LWJGLService; +import com.mitchej123.lwjgl.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.util.Arrays; + +/** SDL GPU implementation of {@link LWJGLService} for Celeritas */ +public final class SDLGPULWJGLService extends LWJGLService { + @Override public int getPriority() { + if (SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable()) { + return 200; + } + return Integer.MIN_VALUE; + } + + @Override public boolean isOpenGLVersionSupported(int major, int minor) { + return major < 4 || (major == 4 && minor <= 6); + } + + @Override public boolean isExtensionSupported(GLExtension extension) { + return switch (extension) { + case ARB_buffer_storage, + ARB_map_buffer_range, + ARB_copy_buffer, + ARB_multi_draw_indirect, + ARB_draw_elements_base_vertex, + ARB_sync, + ARB_uniform_buffer_object, + ARB_vertex_array_object, + ARB_shader_storage_buffer_object, + ARB_instanced_arrays, + KHR_debug + -> true; + case ARB_timer_query, + ARB_debug_output, + AMD_debug_output, + ARB_compatibility, + ARB_direct_state_access, + ARB_texture_storage, + ARB_base_instance + -> false; + }; + } + + @Override public int getPointerSize() { return 8; } // 64-bit + + @Override public int glGenBuffers() { return BackendManager.RENDER_BACKEND.genBuffers(); } + @Override public void glDeleteBuffers(int buffer) { BackendManager.RENDER_BACKEND.deleteBuffers(buffer); } + @Override public void glBindBuffer(int target, int buffer) { GLStateManager.glBindBuffer(target, buffer); } + @Override public void glBufferData(int target, long size, int usage) { BackendManager.RENDER_BACKEND.bufferData(target, size, usage); } + @Override public void glBufferData(int target, ByteBuffer data, int usage) { BackendManager.RENDER_BACKEND.bufferData(target, data, usage); } + @Override public void glBufferData(int target, long size, long data, int usage) { + if (data != 0) { + BackendManager.RENDER_BACKEND.bufferData(target, MemoryUtil.memByteBuffer(data, (int) size), usage); + } else { + BackendManager.RENDER_BACKEND.bufferData(target, size, usage); + } + } + @Override public void glBufferSubData(int target, long offset, ByteBuffer data) { BackendManager.RENDER_BACKEND.bufferSubData(target, offset, data); } + @Override public void glBufferSubData(int target, long offset, long size, long data) { + BackendManager.RENDER_BACKEND.bufferSubData(target, offset, MemoryUtil.memByteBuffer(data, (int) size)); + } + @Override public void glBufferStorage(int target, long size, int flags) { BackendManager.RENDER_BACKEND.bufferStorage(target, size, flags); } + @Override public ByteBuffer glMapBufferRange(int target, long offset, long length, int flags) { return BackendManager.RENDER_BACKEND.mapBufferRange(target, offset, length, flags); } + @Override public long nglMapBuffer(int target, int access) { return 0; } + @Override public ByteBuffer glMapBuffer(int target, int access) { return BackendManager.RENDER_BACKEND.mapBuffer(target, access); } + @Override public void glUnmapBuffer(int target) { BackendManager.RENDER_BACKEND.unmapBuffer(target); } + @Override public void glFlushMappedBufferRange(int target, long offset, long length) { BackendManager.RENDER_BACKEND.flushMappedBufferRange(target, offset, length); } + @Override public void glCopyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size) { BackendManager.RENDER_BACKEND.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); } + @Override public void glBindBufferBase(int target, int index, int buffer) { BackendManager.RENDER_BACKEND.bindBufferBase(target, index, buffer); } + + @Override public int glGenVertexArrays() { return GLStateManager.glGenVertexArrays(); } + @Override public void glDeleteVertexArrays(int array) { GLStateManager.glDeleteVertexArrays(array); } + @Override public void glBindVertexArray(int array) { GLStateManager.glBindVertexArray(array); } + @Override public void glVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, long pointer) { GLStateManager.glVertexAttribPointer(index, size, type, normalized, stride, pointer); } + @Override public void glVertexAttribIPointer(int index, int size, int type, int stride, long pointer) { GLStateManager.glVertexAttribIPointer(index, size, type, stride, pointer); } + @Override public void glEnableVertexAttribArray(int index) { GLStateManager.glEnableVertexAttribArray(index); } + @Override public void glVertexAttribDivisor(int index, int divisor) { GLStateManager.glVertexAttribDivisor(index, divisor); } + + @Override public int glCreateShader(int type) { return BackendManager.RENDER_BACKEND.createShader(type); } + @Override public void glShaderSource(int shader, CharSequence source) { BackendManager.RENDER_BACKEND.shaderSource(shader, source); } + @Override public void glShaderSourceSafe(int shader, CharSequence source) { BackendManager.RENDER_BACKEND.shaderSource(shader, source); } + @Override public void glCompileShader(int shader) { BackendManager.RENDER_BACKEND.compileShader(shader); } + @Override public String glGetShaderInfoLog(int shader, int maxLength) { return BackendManager.RENDER_BACKEND.getShaderInfoLog(shader, maxLength); } + @Override public int glGetShaderi(int shader, int pname) { return BackendManager.RENDER_BACKEND.getShaderi(shader, pname); } + @Override public void glDeleteShader(int shader) { BackendManager.RENDER_BACKEND.deleteShader(shader); } + + @Override public int glCreateProgram() { return BackendManager.RENDER_BACKEND.createProgram(); } + @Override public void glAttachShader(int program, int shader) { BackendManager.RENDER_BACKEND.attachShader(program, shader); } + @Override public void glLinkProgram(int program) { BackendManager.RENDER_BACKEND.linkProgram(program); } + @Override public String glGetProgramInfoLog(int program, int maxLength) { return BackendManager.RENDER_BACKEND.getProgramInfoLog(program, maxLength); } + @Override public int glGetProgrami(int program, int pname) { return BackendManager.RENDER_BACKEND.getProgrami(program, pname); } + @Override public void glUseProgram(int program) { GLStateManager.glUseProgram(program); } + @Override public void glDeleteProgram(int program) { BackendManager.RENDER_BACKEND.deleteProgram(program); } + @Override public void glBindAttribLocation(int program, int index, CharSequence name) { BackendManager.RENDER_BACKEND.bindAttribLocation(program, index, name); } + @Override public void glBindFragDataLocation(int program, int colorNumber, CharSequence name) {} + + @Override public int glGetUniformLocation(int program, CharSequence name) { return BackendManager.RENDER_BACKEND.getUniformLocation(program, name); } + @Override public int glGetUniformBlockIndex(int program, CharSequence name) { return -1; /* TODO */ } + @Override public void glUniformBlockBinding(int program, int blockIndex, int blockBinding) { /* TODO */ } + @Override public void glUniform1f(int location, float v0) { BackendManager.RENDER_BACKEND.uniform1f(location, v0); } + @Override public void glUniform1i(int location, int v0) { BackendManager.RENDER_BACKEND.uniform1i(location, v0); } + @Override public void glUniform1fv(int location, FloatBuffer value) { BackendManager.RENDER_BACKEND.uniform1fv(location, value); } + @Override public void glUniform2i(int location, int v0, int v1) { BackendManager.RENDER_BACKEND.uniform2i(location, v0, v1); } + @Override public void glUniform3f(int location, float v0, float v1, float v2) { BackendManager.RENDER_BACKEND.uniform3f(location, v0, v1, v2); } + @Override public void glUniform3fv(int location, FloatBuffer value) { BackendManager.RENDER_BACKEND.uniform3(location, value); } + @Override public void glUniform3fv(int location, float[] value) { + try (var stack = MemoryStack.stackPush()) { + final FloatBuffer buf = stack.floats(value); + BackendManager.RENDER_BACKEND.uniform3(location, buf); + } + } + @Override public void glUniform4fv(int location, FloatBuffer value) { BackendManager.RENDER_BACKEND.uniform4(location, value); } + @Override public void glUniform4fv(int location, float[] value) { + try (var stack = MemoryStack.stackPush()) { + final FloatBuffer buf = stack.floats(value); + BackendManager.RENDER_BACKEND.uniform4(location, buf); + } + } + @Override public void glUniformMatrix3fv(int location, boolean transpose, FloatBuffer value) { BackendManager.RENDER_BACKEND.uniformMatrix3(location, transpose, value); } + @Override public void glUniformMatrix4fv(int location, boolean transpose, FloatBuffer value) { BackendManager.RENDER_BACKEND.uniformMatrix4(location, transpose, value); } + + @Override public void glDrawElementsBaseVertex(int mode, int count, int type, long indices, int basevertex) { BackendManager.RENDER_BACKEND.drawElementsBaseVertex(mode, count, type, indices, basevertex); } + @Override public void glMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { BackendManager.RENDER_BACKEND.multiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex); } + @Override public void glMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { BackendManager.RENDER_BACKEND.multiDrawElementsIndirect(mode, type, indirect, drawcount, stride); } + + @Override public long glFenceSync(int condition, int flags) { return BackendManager.RENDER_BACKEND.fenceSync(condition, flags); } + @Override public int glClientWaitSync(long sync, int flags, long timeout) { return BackendManager.RENDER_BACKEND.clientWaitSync(sync, flags, timeout); } + @Override public int glGetSynci(long sync, int pname, IntBuffer length) { + if (length != null && length.remaining() > 0) length.put(0, 1); + return ((SDLGPURenderBackend) BackendManager.RENDER_BACKEND).getSyncStatus(sync); + } + @Override public void glWaitSync(long sync, int flags, long timeout) { + ((SDLGPURenderBackend) BackendManager.RENDER_BACKEND).waitSync(sync, flags, timeout); + } + @Override public void glDeleteSync(long sync) { BackendManager.RENDER_BACKEND.deleteSync(sync); } + + private long[] queryTimestamps = new long[64]; + + private void ensureQueryCapacity(int id) { + if (id >= queryTimestamps.length) { + queryTimestamps = Arrays.copyOf(queryTimestamps, Math.max(id + 1, queryTimestamps.length * 2)); + } + } + + @Override public int glGenQueries() { return BackendManager.RENDER_BACKEND.genQueries(); } + @Override public void glDeleteQueries(int query) { } + @Override public void glQueryCounter(int id, int target) { + ensureQueryCapacity(id); + queryTimestamps[id] = System.nanoTime(); + } + @Override public long glGetQueryObjectui64(int id, int pname) { + if (id >= 0 && id < queryTimestamps.length) return queryTimestamps[id]; + return 0; + } + + @Override public int setupDebugCallback(DebugMessageHandler handler) { return 0; } + @Override public void disableDebugCallback() { } + @Override public void glObjectLabel(int identifier, int name, CharSequence label) { BackendManager.RENDER_BACKEND.objectLabel(identifier, name, label); } + @Override public void glPushDebugGroup(int source, int id, CharSequence message) { BackendManager.RENDER_BACKEND.pushDebugGroup(source, id, message); } + @Override public void glPopDebugGroup() { BackendManager.RENDER_BACKEND.popDebugGroup(); } + + @Override public int glGenTextures() { return BackendManager.RENDER_BACKEND.genTextures(); } + @Override public void glGenTextures(int[] textures) { + for (int i = 0; i < textures.length; i++) textures[i] = BackendManager.RENDER_BACKEND.genTextures(); + } + @Override public void glDeleteTextures(int texture) { BackendManager.RENDER_BACKEND.deleteTextures(texture); } + @Override public void glDeleteTextures(int[] textures) { + for (int t : textures) BackendManager.RENDER_BACKEND.deleteTextures(t); + } + @Override public void glBindTexture(int target, int texture) { GLStateManager.glBindTexture(target, texture); } + @Override public void glActiveTexture(int texture) { GLStateManager.glActiveTexture(texture); } + @Override public int glGetTexLevelParameteri(int target, int level, int pname) { return BackendManager.RENDER_BACKEND.getTexLevelParameteri(target, level, pname); } + @Override public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { BackendManager.RENDER_BACKEND.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } + @Override public void glPixelStorei(int pname, int param) { BackendManager.RENDER_BACKEND.pixelStorei(pname, param); } + + @Override public int glGenFramebuffers() { return BackendManager.RENDER_BACKEND.genFramebuffers(); } + @Override public void glDeleteFramebuffers(int framebuffer) { BackendManager.RENDER_BACKEND.deleteFramebuffers(framebuffer); } + @Override public void glBindFramebuffer(int target, int framebuffer) { GLStateManager.glBindFramebuffer(target, framebuffer); } + @Override public int glCheckFramebufferStatus(int target) { return BackendManager.RENDER_BACKEND.checkFramebufferStatus(target); } + @Override public void glFramebufferTexture2D(int target, int attachment, int textarget, int texture, int level) { BackendManager.RENDER_BACKEND.framebufferTexture2D(target, attachment, textarget, texture, level); } + + @Override public void glEnable(int cap) { GLStateManager.glEnable(cap); } + @Override public void glDisable(int cap) { GLStateManager.glDisable(cap); } + @Override public void glBlendFunc(int sfactor, int dfactor) { GLStateManager.glBlendFunc(sfactor, dfactor); } + @Override public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { GLStateManager.tryBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } + @Override public void glDepthFunc(int func) { GLStateManager.glDepthFunc(func); } + @Override public void glDepthMask(boolean flag) { GLStateManager.glDepthMask(flag); } + @Override public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { GLStateManager.glColorMask(red, green, blue, alpha); } + @Override public void glViewport(int x, int y, int width, int height) { GLStateManager.glViewport(x, y, width, height); } + @Override public void glClear(int mask) { BackendManager.RENDER_BACKEND.clear(mask); } + @Override public void glClearColor(float red, float green, float blue, float alpha) { BackendManager.RENDER_BACKEND.clearColor(red, green, blue, alpha); } + @Override public int glGetError() { return BackendManager.RENDER_BACKEND.getError(); } + + @Override public void glMatrixMode(int mode) { /* Handled by GLSM FFP emulation */ } + @Override public void glLoadMatrixf(FloatBuffer m) { /* Handled by GLSM FFP emulation */ } + + @Override public int glGetInteger(int pname) { return BackendManager.RENDER_BACKEND.getInteger(pname); } + @Override public void glGetIntegerv(int pname, int[] params) { + if (params.length > 0) params[0] = BackendManager.RENDER_BACKEND.getInteger(pname); + } + @Override public boolean glGetBoolean(int pname) { return BackendManager.RENDER_BACKEND.getBoolean(pname); } + @Override public String glGetString(int pname) { return BackendManager.RENDER_BACKEND.getString(pname); } + @Override public int glGetAttribLocation(int program, CharSequence name) { return BackendManager.RENDER_BACKEND.getAttribLocation(program, name); } + + @Override public MemoryStack stackPush() { + return new MemoryStackWrapper(org.lwjgl.system.MemoryStack.stackPush()); + } + + @Override public long nmemAlloc(long size) { return MemoryUtil.nmemAlloc(size); } + @Override public long nmemCalloc(long count, long size) { return MemoryUtil.nmemCalloc(count, size); } + @Override public long nmemAlignedAlloc(long alignment, long size) { return MemoryUtil.nmemAlignedAlloc(alignment, size); } + @Override public long nmemRealloc(long ptr, long size) { return MemoryUtil.nmemRealloc(ptr, size); } + @Override public void nmemFree(long ptr) { MemoryUtil.nmemFree(ptr); } + @Override public void nmemAlignedFree(long ptr) { MemoryUtil.nmemAlignedFree(ptr); } + + @Override public ByteBuffer memAlloc(int size) { return MemoryUtil.memAlloc(size); } + @Override public ByteBuffer memCalloc(int size) { return MemoryUtil.memCalloc(size); } + @Override public ByteBuffer memRealloc(ByteBuffer buffer, int size) { return MemoryUtil.memRealloc(buffer, size); } + @Override public void memFree(Buffer buffer) { MemoryUtil.memFree(buffer); } + @Override public ByteBuffer memByteBuffer(long address, int capacity) { return MemoryUtil.memByteBuffer(address, capacity); } + @Override public long memAddress(Buffer buffer) { return MemoryUtil.memAddress(buffer); } + @Override public long memAddress(Buffer buffer, int position) { return MemoryUtil.memAddress((ByteBuffer) buffer, position); } + + @Override public void memSet(long address, int value, long bytes) { MemoryUtil.memSet(address, value, bytes); } + @Override public void memCopy(long src, long dst, long bytes) { MemoryUtil.memCopy(src, dst, bytes); } + + @Override public void memPutByte(long address, byte value) { MemoryAccess.putByte(address, value); } + @Override public void memPutShort(long address, short value) { MemoryAccess.putShort(address, value); } + @Override public void memPutInt(long address, int value) { MemoryAccess.putInt(address, value); } + @Override public void memPutFloat(long address, float value) { MemoryAccess.putFloat(address, value); } + @Override public void memPutLong(long address, long value) { MemoryAccess.putLong(address, value); } + @Override public void memPutAddress(long address, long value) { MemoryAccess.putAddress(address, value); } + + @Override public byte memGetByte(long address) { return MemoryAccess.getByte(address); } + @Override public short memGetShort(long address) { return MemoryAccess.getShort(address); } + @Override public int memGetInt(long address) { return MemoryAccess.getInt(address); } + @Override public float memGetFloat(long address) { return MemoryAccess.getFloat(address); } + @Override public long memGetLong(long address) { return MemoryAccess.getLong(address); } + @Override public long memGetAddress(long address) { return MemoryAccess.getAddress(address); } + @Override public ByteBuffer memSlice(ByteBuffer buffer, int offset, int capacity) { return memByteBuffer(memAddress(buffer) + offset, capacity); } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java new file mode 100644 index 000000000..1776cbd87 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java @@ -0,0 +1,3683 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.sdlgpu.compute.VoxelizationDispatcher; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.CaptureGate; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; +import com.gtnewhorizons.angelica.sdlgpu.compute.ComputeBinder; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.device.SDLDrawable; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FenceTracker; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.FrameState; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.DrawDispatch; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineApplier; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.VertexAttribs; +import com.gtnewhorizons.angelica.sdlgpu.resource.BufferParams; +import com.gtnewhorizons.angelica.sdlgpu.resource.FBOClearTracker; +import com.gtnewhorizons.angelica.sdlgpu.resource.FboState; +import com.gtnewhorizons.angelica.sdlgpu.resource.FormatMap; +import com.gtnewhorizons.angelica.sdlgpu.resource.Image3DClear; +import com.gtnewhorizons.angelica.sdlgpu.resource.PersistentBufferSync; +import com.gtnewhorizons.angelica.sdlgpu.resource.PersistentMapping; +import com.gtnewhorizons.angelica.sdlgpu.resource.PixelOps; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.ReadbackShadows; +import com.gtnewhorizons.angelica.sdlgpu.resource.TextureOps; +import com.gtnewhorizons.angelica.sdlgpu.resource.TextureSamplerState; +import com.gtnewhorizons.angelica.sdlgpu.resource.TransferThread; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerBinder; +import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageBufferBinder; +import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageTextureBinder; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.splash.SplashDispatcher; +import com.gtnewhorizons.angelica.sdlgpu.splash.SplashOffscreenTarget; +import com.gtnewhorizons.angelica.sdlgpu.util.DebugLabels; +import com.gtnewhorizons.angelica.sdlgpu.util.DebugMessageRelay; + +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; +import org.lwjgl.opengl.GL44; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; + +import java.nio.ByteBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; + +import org.lwjgl.sdl.SDLGPU; +import org.lwjgl.sdl.SDLSurface; +import org.lwjgl.sdl.SDL_GPUBlitInfo; +import org.lwjgl.sdl.SDL_GPUBufferLocation; +import org.lwjgl.sdl.SDL_GPUTextureLocation; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.Pointer; +import org.lwjglx.opengl.Display; + +import me.eigenraven.lwjgl3ify.api.DisplayEvents; +import com.gtnewhorizons.angelica.sdlgpu.compat.Lwjgl3GLCapabilitiesShim; +import me.eigenraven.lwjgl3ify.api.GLCapabilitiesOverride; +import me.eigenraven.lwjgl3ify.api.SwapchainInvalidatingChange; + +import static org.lwjgl.sdl.SDLGPU.*; + +/** SDL GPU implementation of {@link RenderBackend}. */ +public class SDLGPURenderBackend extends RenderBackend { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final Tracy.ZoneId Z_SDL_INDIRECT_DRAW = Tracy.zoneId("sdlIndirectDraw", Tracy.COLOR_TERRAIN); + + private final Device device = new Device(); + private final FrameManager frameManager = new FrameManager(device); + private final ResourceManager resourceManager = new ResourceManager(device, frameManager); + private final Image3DClear image3DClear = new Image3DClear(); + private final ShaderManager shaderManager = new ShaderManager(device); + private final PipelineStore pipelineStore = new PipelineStore(device); + + private String cachedRenderer; + private String cachedVendor; + private String cachedVersion; + private String cachedExtensions = ""; + private int[] cachedSwapchainFormatArray; + + private DebugLabels debugLabels; + + + private final FenceTracker fenceTracker = new FenceTracker(device, frameManager); + private final FBOClearTracker fboClearTracker = new FBOClearTracker(frameManager, resourceManager, shaderManager); + private final SamplerBinder samplerBinder = new SamplerBinder(device, resourceManager, shaderManager); + private final StorageTextureBinder storageTextureBinder = new StorageTextureBinder(resourceManager, shaderManager); + private final StorageBufferBinder storageBufferBinder = new StorageBufferBinder(resourceManager, shaderManager); + private final ComputeBinder computeBinder = new ComputeBinder(frameManager, resourceManager, shaderManager, samplerBinder); + private final VoxelizationDispatcher voxelizationDispatcher = + new VoxelizationDispatcher(computeBinder); + private final VertexAttribs vertexAttribs = new VertexAttribs(); + private final TextureOps textureOps = new TextureOps(device, frameManager, resourceManager, fboClearTracker); + private final ReadbackShadows readbackShadows = new ReadbackShadows(device); + private final PersistentBufferSync persistentSync = new PersistentBufferSync(frameManager, resourceManager, + new PersistentBufferSync.UploadSink() { + @Override public void enqueue(TransferThread.DeferredUpload upload) { enqueueUpload(upload); } + @Override public long nextSeq() { return TransferThread.nextSeq(); } + }); + private final PipelineApplier pipelineApplier = new PipelineApplier(frameManager, resourceManager, shaderManager, pipelineStore, fboClearTracker, persistentSync, samplerBinder, storageTextureBinder, storageBufferBinder); + private final DrawDispatch drawDispatch = new DrawDispatch(device, frameManager, resourceManager, pipelineApplier, this::enqueuePreCopied); + + private final IntOpenHashSet missingProgramWarned = new IntOpenHashSet(); + + private boolean droppedCopyWarned; + private boolean droppedSsboWriteWarned; + private final DeferredCopyOp deferredCopyOp = new DeferredCopyOp(); + + private TransferThread transferThread; + + private volatile boolean shutdown; + + private SplashOffscreenTarget splashTarget; + + private static final CopyOnWriteArrayList registeredStates = new CopyOnWriteArrayList<>(); + private static final ThreadLocal tlState = ThreadLocal.withInitial(() -> { + final ContextState st = new ContextState(); + for (int i = 0; i < ContextState.MAX_VERTEX_ATTRIBS; i++) st.attribDefaults[i * 4 + 3] = 1.0f; + st.attribDefaults[4] = 1.0f; st.attribDefaults[5] = 1.0f; + st.attribDefaults[6] = 1.0f; + registeredStates.add(st); + refreshSoleState(); + return st; + }); + + private static volatile ContextState soleState; + + private static void refreshSoleState() { + soleState = registeredStates.size() == 1 ? registeredStates.get(0) : null; + } + + private static ContextState s() { + final ContextState st = soleState; + if (st != null && st.owner == Thread.currentThread()) return st; + return tlState.get(); + } + + private void markAllPipelineInputDirty() { + for (ContextState st : registeredStates) st.pipeline.markInputDirty(); + } + + public static final int CTR_SLOT_WRITES = 0; + public static final int CTR_SLOT_WRITES_ELIDED = 1; + public static final int CTR_SSBO_BINDS = 2; + public static final int CTR_KEY_RECOMPUTES = 3; + public static final int CTR_FAST_PATH_HITS = 4; + public static final int CTR_COUNT = 5; + + public static void takeContextCounters(int[] out) { + Arrays.fill(out, 0); + for (ContextState st : registeredStates) { + out[CTR_SLOT_WRITES] += st.slotWrites; + out[CTR_SLOT_WRITES_ELIDED] += st.slotWritesElided; + out[CTR_SSBO_BINDS] += st.ssboBinds; + out[CTR_KEY_RECOMPUTES] += st.pipeline.keyRecomputes; + out[CTR_FAST_PATH_HITS] += st.pipeline.fastPathHits; + st.slotWrites = 0; + st.slotWritesElided = 0; + st.ssboBinds = 0; + st.pipeline.keyRecomputes = 0; + st.pipeline.fastPathHits = 0; + } + } + + private void releaseUniformStagingAllThreads(ShaderManager.ProgramObject prog) { + for (ContextState st : registeredStates) st.releaseUniformStaging(prog); + } + + + + @Override public void onPersistentBufferWrite(int glId, long offset, long size) { + persistentSync.onPersistentBufferWrite(glId, offset, size); + } + + @Override public void onPostWindowCreate(long window, boolean debug) { + device.claimWindow(window, debug); + buildCachedStrings(); + populateGLCapabilities(); + } + + @Override public void init() { + final boolean lwjglDebugFlag = GLStateManager.getInitConfig() != null && GLStateManager.getInitConfig().isLwjglDebug(); + final boolean enableMarkers = lwjglDebugFlag || CaptureGate.enabledAtStartup(); + debugLabels = new DebugLabels(frameManager, enableMarkers); + if (enableMarkers) { + LOG.info("SDL-GPU debug markers ENABLED (lwjglDebug={}, angelica.debug.markers={}, captureTool={})", lwjglDebugFlag, SystemProperties.DEBUG_MARKERS, CaptureGate.TOOL_ATTACHED); + } + frameManager.setResourceManager(resourceManager); + frameManager.setBeforeEndCopyPassCallback(() -> resourceManager.flushBatchedUploads(frameManager.getCopyPass())); + frameManager.setBeforeSubmitCallback(() -> { + endComputeDispatchBatch(); + textureOps.drainPendingMipGen(); + drainDeferredPersistentRegions(s()); + debugLabels.popAutoDebugGroup(s()); + }); + frameManager.setBeforePendingUploadSubmitCallback(textureOps::drainPendingMipGen); + frameManager.setAfterPresentCallback(() -> { + frameManager.requestFlushOnAllRegisteredFrames(); + resourceManager.drainPendingFreeShadows(); + }); + GLSMHooks.LOADING_CHECKPOINT + .addListener(event -> { + if (Thread.currentThread() == GLStateManager.getMainThread()) { + if (!GLStateManager.isSplashComplete()) { + SplashDispatcher.tryDispatch(this, splashTarget); + } else if (splashTarget != null) { + SplashDispatcher.signalFrameReady(); + SplashDispatcher.tryDispatch(this, splashTarget); + splashTarget.destroy(resourceManager); + splashTarget = null; + SplashDispatcher.reset(); + } + } + if (event.requiresSync) { + frameManager.requestSyncFlushOnAllRegisteredFrames(); + } else { + frameManager.requestFlushOnAllRegisteredFrames(); + } + }); + pipelineApplier.setDeferredUploadSink(this::enqueuePreCopied); + frameManager.setPreRenderPassHook(() -> { + final ContextState st = s(); + pipelineApplier.flushUniformBlocks(st); + if (st.deferUploads) { + drainDeferredPersistentRegions(st); + return; + } + int mask = st.attribDefaultsDirtyMask; + if (st.attribDefaultsRingBase != 0) mask = (1 << ContextState.MAX_VERTEX_ATTRIBS) - 1; + if (mask == 0) return; + final long dummyVBO = resourceManager.getOrCreateDummyVertexBuffer(); + if (dummyVBO == 0) return; + st.attribDefaultsDirtyMask = 0; + final long copyPass = frameManager.ensureCopyPass(); + resourceManager.uploadAttribDefaults(copyPass, st.attribDefaults, mask); + frameManager.endCopyPassIfActive(); + if (st.attribDefaultsRingBase != 0) { + st.attribDefaultsRingBase = 0; + st.bumpAttribStateGen(); + } + }); + DisplayEvents.addPreSwapchainInvalidatingChangeListener(SDLGPUGate.sdlGpuPreSwapchainInvalidatingCallback()); + GLSMConfig.expandVertexFormats = true; + resourceManager.cachePreferredDepthFormats(); + LOG.warn("Swapchain texture format: 0x{} (12=B8G8R8A8_UNORM, 53=B8G8R8A8_SRGB, 4=R8G8B8A8_UNORM)", Integer.toHexString(device.getSwapchainTextureFormat())); + cachedSwapchainFormatArray = new int[]{device.getSwapchainTextureFormat()}; + PipelineCache.setSwapchainFormats(cachedSwapchainFormatArray); + pipelineStore.setBufferHandleResolver(resourceManager::getBufferHandle); + pipelineStore.setVertexVariantResolver(shaderManager::getOrBuildVertexVariant); + resourceManager.setBufferLivenessListener(this::markAllPipelineInputDirty); + shaderManager.setUniformReleaseListener(this::releaseUniformStagingAllThreads); + fenceTracker.setUnresolvedFenceFlush(this::midFrameFenceFlush); + + final int splashW = Math.max(1, Display.getWidth()); + final int splashH = Math.max(1, Display.getHeight()); + final int[] maxDesktop = device.getMaxDesktopSizePixels(); + final int splashTexW = Math.max(splashW, maxDesktop[0]); + final int splashTexH = Math.max(splashH, maxDesktop[1]); + splashTarget = new SplashOffscreenTarget(); + splashTarget.create(device, resourceManager, splashTexW, splashTexH, device.getSwapchainTextureFormat()); + SplashDispatcher.seedDrawnSize(splashW, splashH); + LOG.info("Splash offscreen target {}x{} (window {}x{}, max desktop {}x{})", splashTexW, splashTexH, splashW, splashH, maxDesktop[0], maxDesktop[1]); + + Lwjgl3GLCapabilitiesShim.installOnCurrentThread(advertisedCapabilities()); + + LOG.info("SDLGPURenderBackend initialized: renderer={}, version={}", cachedRenderer, cachedVersion); + } + + private void buildCachedStrings() { + String gpuName = device.getDeviceName(); + String driver = device.getDriverName(); + String version = device.getDriverVersion(); + + StringBuilder renderer = new StringBuilder(gpuName); + renderer.append(" (SDL GPU/").append(driver); + if (!version.isEmpty()) { + renderer.append(", ").append(version); + } + renderer.append(')'); + cachedRenderer = renderer.toString(); + + cachedVersion = "4.6 (Core Profile Equivalent) [SDL GPU/" + driver + "]"; + + String nameLower = gpuName.toLowerCase(Locale.ROOT); + if (nameLower.startsWith("amd") || nameLower.contains("radeon")) { + cachedVendor = "AMD"; + } else if (nameLower.startsWith("nvidia") || nameLower.contains("geforce") || nameLower.contains("quadro")) { + cachedVendor = "NVIDIA Corporation"; + } else if (nameLower.startsWith("intel") || nameLower.contains("intel")) { + cachedVendor = "Intel"; + } else if (nameLower.contains("mesa") || nameLower.contains("llvmpipe")) { + cachedVendor = "Mesa"; + } else { + cachedVendor = "SDL GPU"; + } + } + + private static final String[] ADVERTISED_EXTENSIONS = { + "GL_ARB_framebuffer_object", "GL_ARB_vertex_array_object", "GL_ARB_vertex_buffer_object", + "GL_ARB_vertex_shader", "GL_ARB_fragment_shader", "GL_ARB_shader_objects", + "GL_ARB_shading_language_100", "GL_ARB_texture_non_power_of_two", "GL_ARB_multitexture", + "GL_ARB_sampler_objects", "GL_ARB_uniform_buffer_object", "GL_ARB_map_buffer_range", + "GL_ARB_copy_buffer", "GL_ARB_copy_image", "GL_ARB_blend_func_extended", "GL_ARB_explicit_attrib_location", + "GL_ARB_texture_storage", "GL_ARB_texture_swizzle", "GL_ARB_depth_clamp", + "GL_ARB_seamless_cube_map", "GL_ARB_sync", + "GL_ARB_draw_elements_base_vertex", "GL_ARB_instanced_arrays", "GL_ARB_draw_instanced", + "GL_ARB_provoking_vertex", "GL_ARB_compute_shader", "GL_ARB_shader_storage_buffer_object", + "GL_ARB_shader_image_load_store", "GL_ARB_buffer_storage", "GL_ARB_clear_texture", + "GL_ARB_clear_buffer_object", + "GL_EXT_framebuffer_object", "GL_EXT_framebuffer_blit", "GL_EXT_framebuffer_multisample", + "GL_EXT_framebuffer_sRGB", "GL_EXT_texture_filter_anisotropic", + "GL_EXT_texture_compression_s3tc", "GL_EXT_blend_func_separate", + "GL_EXT_blend_equation_separate", "GL_EXT_texture_sRGB", "GL_EXT_shader_image_load_store", + "GL_EXT_gpu_shader4", "GL_KHR_debug", + }; + + private static final String[] ADVERTISED_VERSIONS = { + "OpenGL11", "OpenGL12", "OpenGL13", "OpenGL14", "OpenGL15", + "OpenGL20", "OpenGL21", + "OpenGL30", "OpenGL31", "OpenGL32", "OpenGL33", + "OpenGL40", "OpenGL41", "OpenGL42", "OpenGL43", "OpenGL44", "OpenGL45", "OpenGL46", + }; + + public static Set advertisedCapabilities() { + final Set caps = new HashSet<>(ADVERTISED_VERSIONS.length + ADVERTISED_EXTENSIONS.length); + Collections.addAll(caps, ADVERTISED_VERSIONS); + Collections.addAll(caps, ADVERTISED_EXTENSIONS); + return caps; + } + + private void populateGLCapabilities() { + final Set caps = advertisedCapabilities(); + GLCapabilitiesOverride.set(caps); + cachedExtensions = String.join(" ", ADVERTISED_EXTENSIONS); + + LOG.info("Populated GL capabilities for SDL GPU backend"); + } + + @Override public void setVSyncEnabled(boolean enabled) { + device.setVSyncEnabled(enabled); + } + + @Override public void shutdown() { + if (shutdown) return; + shutdown = true; + if (splashTarget != null) { + splashTarget.destroy(resourceManager); + splashTarget = null; + } + SplashDispatcher.reset(); + final long dev = device.getDevice(); + if (transferThread != null) { + transferThread.shutdown(); + try { + transferThread.getThread().join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + transferThread = null; + resourceManager.setTransferThread(null); + } + SDL_WaitForGPUIdle(dev); + frameManager.endFrame(); + readbackShadows.dispose(); + fenceTracker.dispose(); + frameManager.releaseAllRegisteredFrames(); + resourceManager.shutdownTexSamplerStates(); + for (ContextState st : registeredStates) { + if (st.fanIndexBuffer != 0) { + resourceManager.releaseBufferHandle(st.fanIndexBuffer); + st.fanIndexBuffer = 0; + } + if (st.vboBindingsAddr != 0) { MemoryUtil.nmemFree(st.vboBindingsAddr); st.vboBindingsAddr = 0; } + if (st.eboBinding != null) { st.eboBinding.free(); st.eboBinding = null; } + if (st.cachedViewport != null) { st.cachedViewport.free(); st.cachedViewport = null; } + if (st.cachedScissor != null) { st.cachedScissor.free(); st.cachedScissor = null; } + if (st.cachedBlendColor != null) { st.cachedBlendColor.free(); st.cachedBlendColor = null; } + st.fragSamplerBindings.free(); + st.vertSamplerBindings.free(); + if (st.mappedStagingBuffer != null) { + MemoryUtil.memFree(st.mappedStagingBuffer); + } + clearMappedState(st); + } + registeredStates.clear(); + soleState = null; + + drawDispatch.clearWarnedState(); + pipelineStore.shutdown(); + shaderManager.shutdown(); + resourceManager.shutdown(); + device.shutdown(); + } + + @Override public boolean isAvailable() { + return SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable(); + } + + @Override public String getName() { + return "SDL GPU (" + (device.getDriverName() != null ? device.getDriverName() : "not initialized") + ")"; + } + + @Override public boolean hasContext() { + return device.getDevice() != 0; + } + + @Override public boolean isCurrent() { + return Thread.currentThread() == GLStateManager.getMainThread(); + } + + @Override public int getPriority() { + return 150; + } + + @Override public boolean isIndirectRequired() { return true; } + @Override public boolean supportsGeometryShaders() { return false; } + @Override public boolean framebufferCompletenessIsMeaningful() { return false; } + @Override public boolean isSDLGPU() { return true; } + + @Override public int getMinGLSLVersion() { + return 460; + } + + @Override public void onRenderThreadReleased(Thread t) { + if (frameManager.isFrameActive()) { + frameManager.endFrame(); + } + frameManager.releaseThreadState(); + registeredStates.remove(tlState.get()); + tlState.remove(); + refreshSoleState(); + } + + @Override public boolean handleMakeCurrent(Object drawable) { + if (!isSDLManagedDrawable(drawable)) return false; + Lwjgl3GLCapabilitiesShim.installOnCurrentThread(advertisedCapabilities()); + if (splashTarget != null && Thread.currentThread() != GLStateManager.getMainThread()) { + s().boundFboId = splashTarget.fboId(); + frameManager.frame().swapchainUnavailable = true; + } + return true; + } + + @Override public boolean handleReleaseContext(Object drawable) { + if (isSDLManagedDrawable(drawable)) { + Lwjgl3GLCapabilitiesShim.clearOnCurrentThread(); + onRenderThreadReleased(Thread.currentThread()); + return true; + } + return false; + } + + private static boolean isSDLManagedDrawable(Object drawable) { + if (drawable == null) return false; + if (drawable instanceof SDLDrawable) return true; + return SDLGPUDisplayBridge.isSdlSharedDrawable(drawable); + } + + @Override public boolean handleSwapBuffers() { + if (splashTarget != null && splashTarget.isFor(s()) && Thread.currentThread() != GLStateManager.getMainThread()) { + endFrameUploadFlush(); + frameManager.endFrame(); + SplashDispatcher.signalFrameReady((int) s().viewportW, (int) s().viewportH); + frameManager.beginFrame(); + beginFrameInit(); + frameManager.frame().swapchainUnavailable = true; + return true; + } + frameManager.presentFrame(); + return true; + } + + public void dispatchSplashBlit(SplashOffscreenTarget target) { + if (shutdown || target == null) return; + onFrameBegin(); + final FrameManager.FrameState f = frameManager.frame(); + if (!frameManager.ensureSwapchainAcquired(f)) { + onFrameEnd(); + return; + } + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + final long drawnSize = SplashDispatcher.getDrawnSize(); + final int srcW = Math.max(1, Math.min((int) (drawnSize >> 32), target.width())); + final int srcH = Math.max(1, Math.min((int) drawnSize, target.height())); + try (var stack = MemoryStack.stackPush()) { + final var info = SDL_GPUBlitInfo.calloc(stack); + info.source(s -> s.texture(target.colorTexture()).x(0).y(0).w(srcW).h(srcH)); + info.destination(d -> d.texture(f.swapchainTexture).x(0).y(0).w(f.swapchainWidth).h(f.swapchainHeight)); + info.filter(SDL_GPU_FILTER_LINEAR); + info.flip_mode(SDLSurface.SDL_FLIP_VERTICAL); + SDL_BlitGPUTexture(f.commandBuffer, info); + } + f.swapchainUsedThisFrame = true; + onFrameEnd(); + } + + @Override public void onFrameBegin() { + if (shutdown) return; + frameManager.beginFrame(); + beginFrameInit(); + } + + private void beginFrameInit() { + if (!frameManager.isFrameActive()) return; + final ContextState st = s(); + if (st.needsSeed) { + st.needsSeed = false; + GLStateManager.replayStateToBackend(); + } + ResourceManager.setSingleThreadedReads(GLStateManager.isSplashComplete()); + st.clearedTexturesThisFrame.clear(); + st.pendingColorTextures.clear(); + st.pendingDepthTextures.clear(); + st.pendingSwapchainClear = false; + st.uniformBlocks[0].flushedThisFrame = false; + st.uniformBlocks[1].flushedThisFrame = false; + st.fanIndexBufferOffset = 0; + st.deferUploads = true; + st.frameHighestEnqueuedSeq = TransferThread.currentSeq(); + st.ringAdvancesThisFrame = 0; + if (transferThread != null) { + transferThread.resetFrameStats(); + } + } + + private void midFrameFenceFlush() { + final ContextState st = s(); + drainDeferredPersistentRegions(st); + pipelineApplier.flushAttribRingChunk(st); + resourceManager.flushUploadArena(); + if (transferThread != null && st.frameHighestEnqueuedSeq > transferThread.getSubmittedSeq()) { + transferThread.awaitSubmittedUpTo(st.frameHighestEnqueuedSeq); + } + frameManager.submitMidFrame(); + fenceTracker.resolvePendingFences(); + } + + private void requestUploadFlush() { + if (transferThread != null) transferThread.requestFlushUpTo(s().frameHighestEnqueuedSeq); + } + + private void endFrameUploadFlushNoWait() { + final ContextState st = s(); + drainDeferredPersistentRegions(st); + pipelineApplier.flushAttribRingChunk(st); + st.deferUploads = false; + resourceManager.flushUploadArena(); + } + + private void drainDeferredPersistentRegions(ContextState st) { + if (!st.deferUploads) return; + st.drawsSincePersistentDrain = 0; + persistentSync.enqueueDirtyPersistentRegions(); + } + + private void awaitUploadFlush() { + final ContextState st = s(); + if (transferThread != null && st.frameHighestEnqueuedSeq > transferThread.getSubmittedSeq()) { + transferThread.awaitSubmittedUpTo(st.frameHighestEnqueuedSeq); + } + } + + private void endFrameUploadFlush() { + endFrameUploadFlushNoWait(); + awaitUploadFlush(); + } + + private static boolean emptyFrameWarned; + + @Override public void onFrameEnd() { + if (shutdown) return; + requestUploadFlush(); + endFrameUploadFlushNoWait(); + + final FrameState f = frameManager.frame(); + if (f.frameActive && !f.swapchainUsedThisFrame) { + if (!emptyFrameWarned) { + emptyFrameWarned = true; + LOG.info("Frame {} ended without drawing to the swapchain; skipping present (further occurrences counted in sdl.emptyFrames)", f.frameNumber); + } + frameManager.markFrameEmpty(f); + } + + awaitUploadFlush(); + frameManager.endFrame(); + fenceTracker.resolvePendingFences(); + resourceManager.flushDeferredReleases(); + resourceManager.recycleGpuBufferPool(frameManager.getFrameNumber()); + } + + @Override public void onPreSwapchainInvalidatingChange(SwapchainInvalidatingChange change) { + endFrameUploadFlush(); + if (frameManager.isFrameActive()) { + frameManager.endFrame(); + } + SDL_WaitForGPUIdle(device.getDevice()); + } + + + private void enqueueUpload(TransferThread.DeferredUpload upload) { + if (shutdown) return; + if (transferThread == null) { + transferThread = new TransferThread(device, resourceManager); + resourceManager.setTransferThread(transferThread); + } + transferThread.enqueue(upload); + s().frameHighestEnqueuedSeq = upload.seq(); + } + + /** Wake the transfer thread once after a batch of enqueueUpload calls. */ + private void wakeTransferThread() { + if (transferThread != null) transferThread.wake(); + } + + private static final int INLINE_UPLOAD_MAX_BYTES = 64 * 1024; + + private void enqueuePreCopied(ByteBuffer data, long dstHandle, long dstOffset, boolean cycle) { + if (data.remaining() <= INLINE_UPLOAD_MAX_BYTES && resourceManager.arenaUpload(data, dstHandle, dstOffset, cycle)) return; + final long dataSize = data.remaining(); + final long xfer = resourceManager.acquireTransferBufferThreadSafe(dataSize); + if (xfer == 0) return; + final long mapSize = resourceManager.getTransferBufferMapSize(dataSize); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped != null) { + final int prevPos = data.position(); + mapped.put(data); + data.position(prevPos); + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + final long seq = TransferThread.nextSeq(); + enqueueUpload(TransferThread.PreCopiedUpload.acquire(xfer, dataSize, dstHandle, dstOffset, seq, cycle)); + wakeTransferThread(); + } + + + @Override public String getTransferDebugInfo() { + return transferThread != null ? transferThread.getDebugInfo() : null; + } + + @Override public void enable(int cap) { setBoolCap(cap, true); } + @Override public void enablei(int cap, int index) { setBoolCapIndexed(cap, index, true); } + @Override public void disable(int cap) { setBoolCap(cap, false); } + @Override public void disablei(int cap, int index) { setBoolCapIndexed(cap, index, false); } + + private void setBoolCapIndexed(int cap, int index, boolean on) { + final ContextState cs = s(); + if (cap == GL11.GL_BLEND) { + if (index < 0 || index >= ContextState.MAX_COLOR_ATTACHMENTS) return; + if (cs.pipeline.blendEnabledPerAttachment[index] != on) { + cs.pipeline.blendEnabledPerAttachment[index] = on; + cs.pipeline.markOutputDirty(); + } + return; + } + setBoolCap(cap, on); + } + + private void setBoolCap(int cap, boolean on) { + final ContextState cs = s(); + switch (cap) { + case GL11.GL_BLEND -> { + boolean changed = false; + for (int i = 0; i < ContextState.MAX_COLOR_ATTACHMENTS; i++) { + if (cs.pipeline.blendEnabledPerAttachment[i] != on) { + cs.pipeline.blendEnabledPerAttachment[i] = on; + changed = true; + } + } + if (changed) cs.pipeline.markOutputDirty(); + } + case GL11.GL_DEPTH_TEST -> { + if (cs.pipeline.depthTestEnabled != on) { cs.pipeline.depthTestEnabled = on; cs.pipeline.markOutputDirty(); } + } + case GL11.GL_CULL_FACE -> { + if (cs.pipeline.cullEnabled != on) { cs.pipeline.cullEnabled = on; cs.pipeline.markOutputDirty(); } + } + case GL11.GL_STENCIL_TEST -> { + if (cs.pipeline.stencilTestEnabled != on) { cs.pipeline.stencilTestEnabled = on; cs.pipeline.markOutputDirty(); } + } + case GL11.GL_SCISSOR_TEST -> { + final ContextState st = cs; + st.scissorEnabled = on; + st.scissorDirty = true; + } + case GL31.GL_PRIMITIVE_RESTART -> cs.primitiveRestartEnabled = on; + } + } + + @Override public void blendFunc(int sfactor, int dfactor) { + blendFuncSeparate(sfactor, dfactor, sfactor, dfactor); + } + + @Override public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + final ContextState cs = s(); + final int sc = FormatMap.mapBlendFactor(srcRGB); + final int dc = FormatMap.mapBlendFactor(dstRGB); + final int sa = FormatMap.mapBlendFactor(srcAlpha); + final int da = FormatMap.mapBlendFactor(dstAlpha); + if (sc == cs.pipeline.srcColorFactor && dc == cs.pipeline.dstColorFactor && sa == cs.pipeline.srcAlphaFactor && da == cs.pipeline.dstAlphaFactor) return; + cs.pipeline.srcColorFactor = sc; + cs.pipeline.dstColorFactor = dc; + cs.pipeline.srcAlphaFactor = sa; + cs.pipeline.dstAlphaFactor = da; + cs.pipeline.markOutputDirty(); + } + + @Override public void blendFuncSeparatei(int buf, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + @Override public void blendEquation(int mode) { + blendEquationSeparate(mode, mode); + } + + @Override public void blendEquationSeparate(int modeRGB, int modeAlpha) { + final ContextState cs = s(); + final int co = FormatMap.mapBlendOp(modeRGB); + final int ao = FormatMap.mapBlendOp(modeAlpha); + if (co == cs.pipeline.colorBlendOp && ao == cs.pipeline.alphaBlendOp) return; + cs.pipeline.colorBlendOp = co; + cs.pipeline.alphaBlendOp = ao; + cs.pipeline.markOutputDirty(); + } + + @Override public void blendColor(float red, float green, float blue, float alpha) { + final ContextState cs = s(); + cs.blendColorR = red; + cs.blendColorG = green; + cs.blendColorB = blue; + cs.blendColorA = alpha; + cs.blendColorDirty = true; + } + + @Override public void depthFunc(int func) { + final ContextState cs = s(); + final int op = FormatMap.mapCompareOp(func); + if (op == cs.pipeline.depthCompareOp) return; + cs.pipeline.depthCompareOp = op; + cs.pipeline.markOutputDirty(); + } + + @Override public void depthMask(boolean flag) { + final ContextState cs = s(); + if (flag == cs.pipeline.depthWriteEnabled) return; + cs.pipeline.depthWriteEnabled = flag; + cs.pipeline.markOutputDirty(); + } + + @Override public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + final ContextState cs = s(); + int mask = 0; + if (red) mask |= SDL_GPU_COLORCOMPONENT_R; + if (green) mask |= SDL_GPU_COLORCOMPONENT_G; + if (blue) mask |= SDL_GPU_COLORCOMPONENT_B; + if (alpha) mask |= SDL_GPU_COLORCOMPONENT_A; + if (mask == cs.pipeline.colorWriteMask) return; + cs.pipeline.colorWriteMask = mask; + cs.pipeline.markOutputDirty(); + } + + @Override public void cullFace(int mode) { + final ContextState cs = s(); + final boolean newCullAll = (mode == GL11.GL_FRONT_AND_BACK); + final int newMode = switch (mode) { + case GL11.GL_BACK -> SDL_GPU_CULLMODE_BACK; + case GL11.GL_FRONT -> SDL_GPU_CULLMODE_FRONT; + case GL11.GL_FRONT_AND_BACK -> SDL_GPU_CULLMODE_BACK; + default -> SDL_GPU_CULLMODE_BACK; + }; + if (newCullAll == cs.pipeline.cullAll && newMode == cs.pipeline.cullFaceMode) return; + cs.pipeline.cullAll = newCullAll; + cs.pipeline.cullFaceMode = newMode; + cs.pipeline.markOutputDirty(); + } + + @Override public void frontFace(int mode) { + final ContextState cs = s(); + final int ff = mode == GL11.GL_CW + ? SDL_GPU_FRONTFACE_CLOCKWISE + : SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + if (ff == cs.pipeline.frontFace) return; + cs.pipeline.frontFace = ff; + cs.pipeline.markOutputDirty(); + } + + @Override public void polygonMode(int face, int mode) { + final ContextState cs = s(); + final int fm = mode == GL11.GL_LINE ? SDL_GPU_FILLMODE_LINE : SDL_GPU_FILLMODE_FILL; + if (fm == cs.pipeline.fillMode) return; + cs.pipeline.fillMode = fm; + cs.pipeline.markOutputDirty(); + } + + @Override public void polygonOffset(float factor, float units) { + polygonOffsetClamp(factor, units, 0.0f); + } + + @Override public void polygonOffsetClamp(float factor, float units, float clamp) { + final ContextState cs = s(); + if (factor == cs.pipeline.depthBiasSlopeFactor && units == cs.pipeline.depthBiasConstant && clamp == cs.pipeline.depthBiasClamp) return; + cs.pipeline.depthBiasSlopeFactor = factor; + cs.pipeline.depthBiasConstant = units; + cs.pipeline.depthBiasClamp = clamp; + cs.pipeline.markOutputDirty(); + } + + @Override public void viewport(int x, int y, int width, int height) { + final ContextState cs = s(); + cs.viewportX = x; cs.viewportY = y; cs.viewportW = width; cs.viewportH = height; + cs.viewportDirty = true; + } + + @Override public void depthRange(double nearVal, double farVal) { + final ContextState cs = s(); + cs.viewportDepthNear = (float) nearVal; + cs.viewportDepthFar = (float) farVal; + cs.viewportDirty = true; + } + + @Override public void scissor(int x, int y, int width, int height) { + final ContextState cs = s(); + cs.scissorX = x; cs.scissorY = y; cs.scissorW = width; cs.scissorH = height; + cs.scissorDirty = true; + } + + @Override public void clearColor(float red, float green, float blue, float alpha) { + final ContextState cs = s(); + cs.clearR = red; cs.clearG = green; cs.clearB = blue; cs.clearA = alpha; + } + + @Override public void clearDepth(double depth) { s().depthClearValue = (float) depth; } + @Override public void clearStencil(int s) {} + + @Override public void clear(int mask) { + final ContextState cs = s(); + if (!frameManager.isFrameActive()) return; + final boolean wantColor = (mask & GL11.GL_COLOR_BUFFER_BIT) != 0; + final boolean wantDepth = (mask & GL11.GL_DEPTH_BUFFER_BIT) != 0; + if (!wantColor && !wantDepth) return; + + final ContextState st = cs; + + // Swapchain path: just record pending state; ensureSwapchainRenderPass consumes it lazily. + if (st.boundFboId == 0) { + if (wantColor) { + st.pendingSwapchainClear = true; + st.pendingSwapchainR = st.clearR; + st.pendingSwapchainG = st.clearG; + st.pendingSwapchainB = st.clearB; + st.pendingSwapchainA = st.clearA; + } + // swapchain has no depth attachment in this backend; ignore wantDepth + return; + } + + final FboState fbo = resourceManager.getFbo(st.boundFboId); + if (fbo == null) return; + + boolean affectsActivePass = false; + final boolean passActive = frameManager.isRenderPassActive(); + final long activeColor = passActive ? frameManager.getCurrentColorTarget() : 0; + final long activeDepth = passActive ? frameManager.getCurrentDepthTarget() : 0; + + if (wantColor) { + for (int db : fbo.drawBuffers) { + if (db < 0 || db >= ContextState.MAX_COLOR_ATTACHMENTS) continue; + final long tex = fbo.colorTextures[db]; + if (tex == 0) continue; + FBOClearTracker.recordPendingColorClear(st, tex, st.clearR, st.clearG, st.clearB, st.clearA); + if (passActive && tex == activeColor) affectsActivePass = true; + } + } + if (wantDepth && fbo.depthTexture != 0) { + FBOClearTracker.recordPendingDepthClear(st, fbo.depthTexture, cs.depthClearValue); + if (passActive && fbo.depthTexture == activeDepth) affectsActivePass = true; + } + + if (affectsActivePass) { + frameManager.endRenderPassIfActive(); + } + } + + @Override public void lineWidth(float width) { /* no-op */ } + @Override public void pointSize(float size) { /* no-op */ } + @Override public void logicOp(int opcode) { /* no-op */ } + @Override public void hint(int target, int mode) { /* no-op */ } + + @Override public void flush() { /* no-op */ } + @Override public void finish() { + if (device.getDevice() != 0) { + SDL_WaitForGPUIdle(device.getDevice()); + } + } + + @Override public void drawArrays(int mode, int first, int count) { + final FrameState f = frameManager.frame(); + if (!f.frameActive) { f.droppedDrawsThisFrame++; return; } + final ContextState st = s(); + if (mode == GL11.GL_TRIANGLE_FAN && count >= 3) { + drawDispatch.drawTriangleFanAsTriangleList(st, first, count); + return; + } + drawDispatch.setPrimitiveTypeForDraw(st, FormatMap.mapPrimitiveType(mode)); + pipelineApplier.ensureRenderPass(st, f); + if (f.renderPass == 0) { f.droppedDrawsThisFrame++; drawDispatch.warnDrawArraysNoRenderPass(mode, st.boundFboId); return; } + if (!pipelineApplier.applyPipelineAndState(st, f)) { f.droppedDrawsThisFrame++; return; } + SDL_DrawGPUPrimitives(f.renderPass, count, 1, first, 0); + } + + @Override public void drawElements(int mode, int count, int type, long indices) { + final ContextState st = s(); + final long rp = prepareIndexedDrawBind(st, mode, type, "drawElements"); + if (rp == 0) return; + final int firstIndex = (int) (indices / FormatMap.indexElementSize(type)); + drawDispatch.issueIndexedDraw(st, rp, st.currentVao.elementBuffer, type, count, 1, firstIndex, 0); + } + + @Override public void drawElementsInstanced(int mode, int count, int type, long indices, int primcount) { + final ContextState st = s(); + final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsInstanced"); + if (rp == 0) return; + final int firstIndex = (int) (indices / FormatMap.indexElementSize(type)); + drawDispatch.issueIndexedDraw(st, rp, st.currentVao.elementBuffer, type, count, primcount, firstIndex, 0); + } + + + @Override public void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) { + final ContextState st = s(); + final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsBaseVertex"); + if (rp == 0) return; + final int firstIndex = (int) (indices / FormatMap.indexElementSize(type)); + drawDispatch.issueIndexedDraw(st, rp, st.currentVao.elementBuffer, type, count, 1, firstIndex, baseVertex); + } + + private long prepareIndexedDrawBind(ContextState st, int mode, int type, String opName) { + if (!drawDispatch.prepareIndexedDraw(st, mode, type)) return 0; + final int ebo = st.currentVao.elementBuffer; + final long eboHandle = resourceManager.getBufferHandle(ebo); + if (eboHandle == 0) { + LOG.warn("{}: EBO {} has no GPU handle, skipping draw", opName, ebo); + return 0; + } + final long rp = frameManager.getRenderPass(); + drawDispatch.bindIndexBufferIfChanged(st, rp, eboHandle, FormatMap.mapIndexElementSize(type), 0); + return rp; + } + + @Override public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { + if (drawcount <= 0) return; + final ContextState st = s(); + final long rp = prepareIndexedDrawBind(st, mode, type, "multiDrawElementsBaseVertex"); + if (rp == 0) return; + final int elementSize = FormatMap.indexElementSize(type); + final int ebo = st.currentVao.elementBuffer; + for (int i = 0; i < drawcount; i++) { + final long offset = (long) i * Integer.BYTES; + final int count = MemoryUtil.memGetInt(pCount + offset); + if (count <= 0) continue; + final long indices = MemoryUtil.memGetAddress(pIndices + (long) i * Pointer.POINTER_SIZE); + drawDispatch.issueIndexedDraw(st, rp, ebo, type, count, 1, (int) (indices / elementSize), MemoryUtil.memGetInt(pBaseVertex + offset)); + } + } + + @Override public void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { + final ContextState cs = s(); + if (drawcount <= 0) return; + Tracy.beginZone(Z_SDL_INDIRECT_DRAW); + try { + final ContextState st = cs; + final long rp = prepareIndexedDrawBind(st, mode, type, "multiDrawElementsIndirect"); + if (rp == 0) return; + final long indirectHandle = resourceManager.getBufferHandle(st.boundIndirectBuffer); + if (indirectHandle == 0) { + LOG.warn("multiDrawElementsIndirect: indirect buffer {} has no GPU handle", st.boundIndirectBuffer); + return; + } + if (stride != 0 && stride != 20) { + LOG.warn("multiDrawElementsIndirect: non-standard stride {} (expected 0 or 20)", stride); + } + if (cs.primitiveRestartEnabled && !drawDispatch.restartMultiDrawWarned) { + LOG.warn("multiDrawElementsIndirect with primitive restart is not supported on the SDL backend; " + + "sentinel indices in the EBO will be drawn as regular indices."); + drawDispatch.restartMultiDrawWarned = true; + } + SDL_DrawGPUIndexedPrimitivesIndirect(rp, indirectHandle, (int) indirect, drawcount); + } finally { + Tracy.endZone(); + } + } + + @Override public void drawBuffer(int mode) { /* render target config */ } + + @Override public void dispatchCompute(int numGroupsX, int numGroupsY, int numGroupsZ) { + computeBinder.executeComputeDispatch(s(), numGroupsX, numGroupsY, numGroupsZ, 0L, false); + } + + @Override public void dispatchComputeIndirect(long offset) { + final int indirectGlId = getBoundBuffer(GL40.GL_DRAW_INDIRECT_BUFFER); + if (indirectGlId == 0) return; + final long indirectHandle = resourceManager.getBufferHandle(indirectGlId); + if (indirectHandle == 0) return; + computeBinder.executeComputeDispatch(s(), 0, 0, 0, indirectHandle, true, (int) offset); + } + + public void beginComputeDispatchBatch() { + s().computeBatchRequested = true; + } + + public void endComputeDispatchBatch() { + final ContextState st = s(); + st.computeBatchRequested = false; + computeBinder.endBatchPassIfOpen(st); + } + + @Override public void copyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size) { + final int srcGlId = getBoundBuffer(readTarget); + final int dstGlId = getBoundBuffer(writeTarget); + if (srcGlId == 0 || dstGlId == 0 || size <= 0) return; + resourceManager.dropArrayShadow(dstGlId); + resourceManager.dropEboShadow(dstGlId); + resourceManager.markBufferContentsDefined(dstGlId); + readbackShadows.invalidate(dstGlId, writeOffset); + + if (s().deferUploads) { + final long dstHandle = resourceManager.getBufferHandle(dstGlId); + if (dstHandle != 0) { + final long seq = TransferThread.nextSeq(); + deferredCopyOp.readOffset = readOffset; + deferredCopyOp.size = size; + deferredCopyOp.dstHandle = dstHandle; + deferredCopyOp.writeOffset = writeOffset; + deferredCopyOp.seq = seq; + final boolean handled = resourceManager.enqueuePersistentCopyDeferred(srcGlId, dstGlId, seq, deferredCopyOp); + if (handled) { + wakeTransferThread(); + return; + } + final long srcHandle = resourceManager.getBufferHandle(srcGlId); + if (srcHandle != 0) { + resourceManager.flushUploadArena(); + enqueueUpload(TransferThread.GpuCopyUpload.acquire(srcHandle, dstHandle, readOffset, writeOffset, size, seq)); + wakeTransferThread(); + return; + } + } + } else { + final long dstHandle = resourceManager.getBufferHandle(dstGlId); + if (dstHandle != 0 && frameManager.getCommandBuffer() != 0) { + if (resourceManager.uploadFromPersistentMapping(srcGlId, readOffset, size, + dstHandle, writeOffset, dstGlId, frameManager.ensureCopyPass())) { + return; + } + } else if (dstHandle == 0) { + LOG.warn("copyBufferSubData: dest buffer {} has no GPU handle", dstGlId); + return; + } + } + + final long srcHandle = resourceManager.getBufferHandle(srcGlId); + final long dstHandle = resourceManager.getBufferHandle(dstGlId); + if (srcHandle == 0 || dstHandle == 0) { + LOG.warn("copyBufferSubData: src={} (handle={}) dst={} (handle={})", srcGlId, srcHandle, dstGlId, dstHandle); + return; + } + if (frameManager.getCommandBuffer() == 0) { + FrameManager.warnDroppedOutsideFrame(droppedCopyWarned, "copyBufferSubData"); + droppedCopyWarned = true; + return; + } + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return; + if (resourceManager.getBufferGlUsage(dstGlId) == GL15.GL_STREAM_READ + && readbackShadows.scheduleDownload(cp, srcHandle, readOffset, dstGlId, writeOffset, size)) { + return; + } + try (var stack = MemoryStack.stackPush()) { + final SDL_GPUBufferLocation src = SDL_GPUBufferLocation.calloc(stack).buffer(srcHandle).offset((int) readOffset); + final SDL_GPUBufferLocation dst = SDL_GPUBufferLocation.calloc(stack).buffer(dstHandle).offset((int) writeOffset); + SDL_CopyGPUBufferToBuffer(cp, src, dst, (int) size, false); + } + } + + @Override public int genTextures() { return resourceManager.genTexture(); } + @Override public void genTextures(IntBuffer textures) { + for (int i = 0; i < textures.remaining(); i++) { + textures.put(textures.position() + i, resourceManager.genTexture()); + } + } + @Override public void deleteTextures(int texture) { + fboClearTracker.scrubPendingClearsForTexture(s(), texture); + resourceManager.deleteTexture(texture); + } + + + @Override public void bindTexture(int target, int texture) { + final ContextState st = s(); + if (st.activeTextureUnit >= 0 && st.activeTextureUnit < st.boundTextures.length) { + if (st.boundTextures[st.activeTextureUnit] != texture) { + st.boundTextures[st.activeTextureUnit] = texture; + st.samplerBindGen++; + } + } + } + @Override public void activeTexture(int texture) { + final ContextState st = s(); + st.activeTextureUnit = texture - GL13.GL_TEXTURE0; + } + + private static boolean canReuseTexture(ResourceManager.TextureMeta m, long handle, int target, int glFormat, int sdlFormat, int w, int h, int d, int levels) { + return m != null + && handle != 0 + && m.width() == w + && m.height() == h + && m.depth() == d + && m.levels() == levels + && m.glTarget() == target + && m.glFormat() == glFormat + && m.sdlFormat() == sdlFormat; + } + + @Override public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer pixels) { + final ContextState st = s(); + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0) return; + + if (level == 0) { + final TextureSamplerState ss = resourceManager.getOrCreateTexSamplerState(glId); + final int numLevels = ss.maxLevel >= 0 ? ss.maxLevel + 1 : PixelOps.defaultMipLevels(width, height); + final boolean bgraSwizzle = format == GL12.GL_BGRA && (internalFormat == GL11.GL_RGBA || internalFormat == GL11.GL_RGBA8); + final int targetSdlFormat = bgraSwizzle + ? SDLGPU.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM + : resourceManager.mapTextureFormat(internalFormat); + if (!canReuseTexture(resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), + target, internalFormat, targetSdlFormat, width, height, 1, numLevels)) { + textureOps.releaseTextureForRealloc(st, glId); + if (bgraSwizzle) { + resourceManager.createTextureWithSdlFormat(glId, target, SDLGPU.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, internalFormat, width, height, 1, numLevels); + } else { + resourceManager.createTexture(glId, target, internalFormat, width, height, 1, numLevels); + } + resourceManager.refreshTextureReferences(glId); + } + } + + textureOps.uploadTextureRegion(st, glId, resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), pixels, 0, 0, width, height, level, format, type); + } + @Override public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, DoubleBuffer pixels) { + texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : (ByteBuffer) null); + } + @Override public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, FloatBuffer pixels) { + texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : (ByteBuffer) null); + } + @Override public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, IntBuffer pixels) { + texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : (ByteBuffer) null); + } + @Override public void texImage3D(int target, int level, int internalFormat, int width, int height, int depth, int border, int format, int type, ByteBuffer pixels) { + final ContextState st = s(); + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0) return; + + if (level == 0) { + final int numLevels = 1; + final int targetSdlFormat = resourceManager.mapTextureFormat(internalFormat); + if (!canReuseTexture(resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), + target, internalFormat, targetSdlFormat, width, height, depth, numLevels)) { + textureOps.releaseTextureForRealloc(st, glId); + resourceManager.createTexture(glId, target, internalFormat, width, height, depth, numLevels); + resourceManager.refreshTextureReferences(glId); + } + } + if (pixels == null) return; + final long texHandle = resourceManager.getTextureHandle(glId); + if (texHandle == 0 || frameManager.getCommandBuffer() == 0) return; + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return; + final ByteBuffer unpacked = PixelOps.applyUnpackPixelStore(pixels, width, height * depth, format, type, st.pixelStore); + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + final ByteBuffer prepped = PixelOps.prepareUploadBuffer(format, meta.sdlFormat(), unpacked, width, height * depth); + try { + resourceManager.uploadToTexture3D(cp, prepped, texHandle, 0, 0, 0, width, height, depth, level); + } finally { + if (prepped != unpacked) MemoryUtil.memFree(prepped); + if (unpacked != pixels) MemoryUtil.memFree(unpacked); + } + } + @Override public void texImage3D(int target, int level, int internalFormat, int width, int height, int depth, int border, int format, int type, IntBuffer pixels) { + texImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : (ByteBuffer) null); + } + @Override public void texImage1D(int target, int level, int internalFormat, int width, int border, int format, int type, ByteBuffer pixels) { + final ContextState st = s(); + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0) return; + + if (level == 0) { + final int numLevels = 1; + final int targetSdlFormat = resourceManager.mapTextureFormat(internalFormat); + if (!canReuseTexture(resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), + target, internalFormat, targetSdlFormat, width, 1, 1, numLevels)) { + textureOps.releaseTextureForRealloc(st, glId); + resourceManager.createTexture(glId, target, internalFormat, width, 1, 1, numLevels); + resourceManager.refreshTextureReferences(glId); + } + } + if (pixels == null) return; + textureOps.uploadTextureRegion(st, glId, resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), + pixels, 0, 0, width, 1, level, format, type); + } + @Override public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, long pixelBufferOffset) { + final ContextState st = s(); + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0) return; + + if (level == 0) { + final TextureSamplerState ss = resourceManager.getOrCreateTexSamplerState(glId); + final int numLevels = ss.maxLevel >= 0 ? ss.maxLevel + 1 : PixelOps.defaultMipLevels(width, height); + final int targetSdlFormat = resourceManager.mapTextureFormat(internalFormat); + if (!canReuseTexture(resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), target, internalFormat, targetSdlFormat, width, height, 1, numLevels)) { + textureOps.releaseTextureForRealloc(st, glId); + resourceManager.createTexture(glId, target, internalFormat, width, height, 1, numLevels); + resourceManager.refreshTextureReferences(glId); + } + } + + if (st.boundPixelUnpackBuffer == 0) return; + final ByteBuffer staging = resourceManager.getPboStaging(st.boundPixelUnpackBuffer); + if (staging == null) return; + final int offset = (int) pixelBufferOffset; + final int dataLen = width * height * PixelOps.glPixelSize(format, type); + if (offset + dataLen > staging.capacity()) return; + staging.position(offset).limit(offset + dataLen); + textureOps.uploadTextureRegion(st, glId, resourceManager.getTextureMeta(glId), + resourceManager.getTextureHandle(glId), + staging.slice(), 0, 0, width, height, level, format, type); + } + + @Override public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { + final ContextState st = s(); + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0 || pixels == null) return; + textureOps.uploadTextureRegion(st, glId, resourceManager.getTextureMeta(glId), resourceManager.getTextureHandle(glId), pixels, xoffset, yoffset, width, height, level, format, type); + } + @Override public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { + if (pixels != null) texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); + } + @Override public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, long pboOffset) { + final ContextState st = s(); + if (st.boundPixelUnpackBuffer == 0) return; + final int glId = st.boundTextures[st.activeTextureUnit]; + if (glId == 0) return; + final ByteBuffer staging = resourceManager.getPboStaging(st.boundPixelUnpackBuffer); + if (staging == null) return; + final int offset = (int) pboOffset; + final int dataLen = width * height * PixelOps.glPixelSize(format, type); + if (offset + dataLen > staging.capacity()) return; + staging.position(offset).limit(offset + dataLen); + textureOps.uploadTextureRegion(st, glId, resourceManager.getTextureMeta(glId), + resourceManager.getTextureHandle(glId), + staging.slice(), xoffset, yoffset, width, height, level, format, type); + } + @Override public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + final ContextState cs = s(); + final int destGlId = cs.boundTextures[cs.activeTextureUnit]; + textureOps.copyTexSubImageImpl(cs,destGlId, level, xoffset, yoffset, x, y, width, height); + } + + @Override public void copyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) { + final ContextState cs = s(); + final int destGlId = cs.boundTextures[cs.activeTextureUnit]; + textureOps.copyTexSubImageImpl(cs, destGlId, level, 0, 0, x, y, width, height); + } + + @Override public void texParameteri(int target, int pname, int param) { + final ContextState cs = s(); + textureOps.texParameteri(cs, pname, param, cs.boundTextures[cs.activeTextureUnit]); + } + + @Override public void texParameterf(int target, int pname, float param) { + final ContextState cs = s(); + textureOps.texParameterf(cs, pname, param, cs.boundTextures[cs.activeTextureUnit]); + } + + @Override public void texParameteriv(int target, int pname, IntBuffer params) { + if (params != null && params.remaining() > 0) texParameteri(target, pname, params.get(0)); + } + @Override public void texParameterfv(int target, int pname, FloatBuffer params) { + if (params != null && params.remaining() > 0) texParameterf(target, pname, params.get(params.position())); + } + @Override public int getTexParameteri(int target, int pname) { + final ContextState cs = s(); + return getTextureParameteri(cs.boundTextures[cs.activeTextureUnit], target, pname); + } + @Override public float getTexParameterf(int target, int pname) { + final ContextState cs = s(); + return getTextureParameterf(cs.boundTextures[cs.activeTextureUnit], target, pname); + } + @Override public int getTexLevelParameteri(int target, int level, int pname) { + final ContextState cs = s(); + final int glId = cs.boundTextures[cs.activeTextureUnit]; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + if (meta == null) return 0; + final int mipW = Math.max(1, meta.width() >> level); + final int mipH = Math.max(1, meta.height() >> level); + return switch (pname) { + case GL11.GL_TEXTURE_WIDTH -> mipW; + case GL11.GL_TEXTURE_HEIGHT -> mipH; + case GL11.GL_TEXTURE_INTERNAL_FORMAT -> { + final int stored = meta.glFormat(); + yield TextureInfoCache.isGenericCompressedInternalFormat(stored) ? GL11.GL_RGBA8 : stored; + } + default -> 0; + }; + } + @Override public void generateMipmap(int target) { + final ContextState st = s(); + generateTextureMipmap(st.boundTextures[st.activeTextureUnit]); + } + @Override public void pixelStorei(int pname, int param) { + final ContextState.PixelStoreState ps = s().pixelStore; + switch (pname) { + case GL11.GL_UNPACK_ALIGNMENT -> ps.unpackAlignment = param; + case GL11.GL_PACK_ALIGNMENT -> ps.packAlignment = param; + case GL11.GL_UNPACK_ROW_LENGTH -> ps.unpackRowLength = param; + case GL11.GL_UNPACK_SKIP_PIXELS -> ps.unpackSkipPixels = param; + case GL11.GL_UNPACK_SKIP_ROWS -> ps.unpackSkipRows = param; + default -> { /* GL_PACK_* and GL_UNPACK_SWAP_BYTES etc are ignored */ } + } + } + + @Override public int genSamplers() { return resourceManager.genSampler(); } + @Override public void deleteSamplers(int sampler) { + resourceManager.deleteSamplerObject(sampler); + final ContextState st = s(); + for (int i = 0; i < st.boundSamplerObjects.length; i++) { + if (st.boundSamplerObjects[i] == sampler) { + st.boundSamplerObjects[i] = 0; + st.samplerBindGen++; + } + } + resourceManager.deleteSampler(sampler); + } + @Override public void bindSampler(int unit, int sampler) { + final ContextState st = s(); + if (unit >= 0 && unit < st.boundSamplerObjects.length) { + if (st.boundSamplerObjects[unit] != sampler) { + st.boundSamplerObjects[unit] = sampler; + st.samplerBindGen++; + } + } + } + @Override public void samplerParameteri(int sampler, int pname, int param) { + if (sampler == 0) return; + final TextureSamplerState ss = resourceManager.getOrCreateSamplerObject(sampler); + switch (pname) { + case GL11.GL_TEXTURE_MIN_FILTER -> ss.minFilter = param; + case GL11.GL_TEXTURE_MAG_FILTER -> ss.magFilter = param; + case GL11.GL_TEXTURE_WRAP_S -> ss.wrapS = param; + case GL11.GL_TEXTURE_WRAP_T -> ss.wrapT = param; + case GL12.GL_TEXTURE_WRAP_R -> ss.wrapR = param; + case GL12.GL_TEXTURE_MIN_LOD -> ss.minLod = (float) param; + case GL12.GL_TEXTURE_MAX_LOD -> ss.maxLod = (float) param; + case GL14.GL_TEXTURE_COMPARE_MODE -> ss.compareMode = param; + case GL14.GL_TEXTURE_COMPARE_FUNC -> ss.compareFunc = param; + default -> { return; } + } + ss.sdlSampler = 0; + s().samplerBindGen++; + } + @Override public void samplerParameterf(int sampler, int pname, float param) { + if (sampler == 0) return; + final TextureSamplerState ss = resourceManager.getOrCreateSamplerObject(sampler); + switch (pname) { + case GL12.GL_TEXTURE_MIN_LOD -> ss.minLod = param; + case GL12.GL_TEXTURE_MAX_LOD -> ss.maxLod = param; + case GL14.GL_TEXTURE_LOD_BIAS -> ss.lodBias = param; + case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> ss.maxAnisotropy = param; + default -> { samplerParameteri(sampler, pname, (int) param); return; } + } + ss.sdlSampler = 0; + s().samplerBindGen++; + } + + @Override public int genFramebuffers() { + final int id = resourceManager.genFboId(); + resourceManager.createFbo(id); + return id; + } + + @Override public void deleteFramebuffers(int framebuffer) { + final ContextState cs = s(); + resourceManager.deleteFbo(framebuffer); + if (cs.boundFboId == framebuffer) cs.boundFboId = 0; + if (cs.boundReadFboId == framebuffer) cs.boundReadFboId = 0; + } + + @Override public void bindFramebuffer(int target, int framebuffer) { + final ContextState cs = s(); + final boolean isRead = target == GL30.GL_READ_FRAMEBUFFER; + final boolean isDraw = target == GL30.GL_DRAW_FRAMEBUFFER; + final boolean isBoth = !isRead && !isDraw; + + if (isRead) { + cs.boundReadFboId = framebuffer; + return; + } + + if (isBoth) { + cs.boundReadFboId = framebuffer; + } + + if (cs.boundFboId == framebuffer) return; + final int oldFboId = cs.boundFboId; + final boolean structurallyIdentical = oldFboId != 0 && framebuffer != 0 && fboClearTracker.fbosHaveSameAttachments(cs, oldFboId, framebuffer); + cs.boundFboId = framebuffer; + + if (structurallyIdentical) { + return; + } + + if (framebuffer == 0) { + cs.pipeline.setColorTargetFormats(cachedSwapchainFormatArray); + cs.pipeline.setDrawBuffers(null); + cs.pipeline.hasDepthTarget = false; + cs.pipeline.depthTargetFormat = 0; + } else { + final FboState fbo = resourceManager.getFbo(framebuffer); + if (fbo != null && fbo.getColorTexture() != 0) { + fboClearTracker.updatePipelineCacheColorFormats(cs, fbo); + cs.pipeline.hasDepthTarget = fbo.depthTexture != 0; + cs.pipeline.depthTargetFormat = fbo.depthFormat; + } + } + cs.pipeline.markOutputDirty(); + } + + @Override public void framebufferTexture2D(int target, int attachment, int textarget, int texture, int level) { + final ContextState cs = s(); + if (cs.boundFboId == 0) return; + final FboState fbo = resourceManager.getFbo(cs.boundFboId); + if (fbo == null) return; + + final int colorIdx = attachment - GL30.GL_COLOR_ATTACHMENT0; + if (colorIdx >= 0 && colorIdx < ContextState.MAX_COLOR_ATTACHMENTS) { + if (texture == 0) { + fbo.detachColor(colorIdx); + fboClearTracker.updatePipelineCacheColorFormats(cs, fbo); + cs.pipeline.markOutputDirty(); + return; + } + final long handle = resourceManager.ensureTextureUsage(texture, SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET); + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(texture); + fbo.colorTextures[colorIdx] = handle; + fbo.colorGlIds[colorIdx] = texture; + resourceManager.markFboAttachment(texture); + fbo.targetsDirty = true; + if (meta != null) { + fbo.colorFormats[colorIdx] = meta.sdlFormat(); + if (colorIdx == 0) { + fbo.width = meta.width(); + fbo.height = meta.height(); + } + } + fbo.colorAttachmentCount = Math.max(fbo.colorAttachmentCount, colorIdx + 1); + fbo.cachedFormatsDirty = true; + fboClearTracker.updatePipelineCacheColorFormats(cs, fbo); + cs.pipeline.markOutputDirty(); + } else if (attachment == GL30.GL_DEPTH_ATTACHMENT || attachment == GL30.GL_DEPTH_STENCIL_ATTACHMENT) { + if (texture == 0) { + fbo.detachDepth(); + cs.pipeline.hasDepthTarget = false; + cs.pipeline.depthTargetFormat = 0; + cs.pipeline.markOutputDirty(); + return; + } + final long handle = resourceManager.ensureTextureUsage(texture, SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET); + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(texture); + fbo.depthTexture = handle; + fbo.depthGlId = texture; + resourceManager.markFboAttachment(texture); + fbo.targetsDirty = true; + if (meta != null) { + fbo.depthFormat = meta.sdlFormat(); + } + cs.pipeline.hasDepthTarget = true; + cs.pipeline.depthTargetFormat = fbo.depthFormat; + cs.pipeline.markOutputDirty(); + } + } + + @Override public void framebufferTexture(int target, int attachment, int texture, int level) { + framebufferTexture2D(target, attachment, GL11.GL_TEXTURE_2D, texture, level); + } + + @Override public int checkFramebufferStatus(int target) { return GL30.GL_FRAMEBUFFER_COMPLETE; } + @Override public void blitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + final ContextState cs = s(); + blitNamedFramebuffer(cs.boundReadFboId, cs.boundFboId, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + } + private static final int[] EMPTY_DRAW_BUFFERS = new int[0]; + + private static int classifyDrawBuffer(int buf) { + if (buf >= GL30.GL_COLOR_ATTACHMENT0 && buf < GL30.GL_COLOR_ATTACHMENT0 + ContextState.MAX_COLOR_ATTACHMENTS) { + return buf - GL30.GL_COLOR_ATTACHMENT0; + } + return -1; + } + + @Override public void drawBuffers(int buffer) { + final ContextState cs = s(); + if (cs.boundFboId == 0) return; + final FboState fbo = resourceManager.getFbo(cs.boundFboId); + if (fbo == null) return; + + if (buffer == GL11.GL_NONE) { + if (fbo.drawBuffers.length == 0) return; + frameManager.endRenderPassIfActive(); + fbo.drawBuffers = EMPTY_DRAW_BUFFERS; + markDrawBuffersChanged(fbo, true); + return; + } + final int idx = classifyDrawBuffer(buffer); + if (fbo.drawBuffers.length == 1 && fbo.drawBuffers[0] == idx) return; + frameManager.endRenderPassIfActive(); + if (fbo.drawBuffers.length == 1) { + fbo.drawBuffers[0] = idx; + } else { + fbo.drawBuffers = new int[]{idx}; + } + markDrawBuffersChanged(fbo, true); + } + @Override public void drawBuffers(IntBuffer bufs) { + final ContextState cs = s(); + if (cs.boundFboId == 0) return; + final FboState fbo = resourceManager.getFbo(cs.boundFboId); + if (fbo == null) return; + applyDrawBuffersFromIntBuffer(fbo, bufs, true); + } + + private void applyDrawBuffersFromIntBuffer(FboState fbo, IntBuffer bufs, boolean isBound) { + final int count = bufs.remaining(); + final int basePos = bufs.position(); + if (fbo.drawBuffers.length == count) { + boolean same = true; + for (int i = 0; i < count; i++) { + if (fbo.drawBuffers[i] != classifyDrawBuffer(bufs.get(basePos + i))) { same = false; break; } + } + if (same) return; + } + if (isBound) frameManager.endRenderPassIfActive(); + final int[] indices = (fbo.drawBuffers.length == count) ? fbo.drawBuffers : new int[count]; + for (int i = 0; i < count; i++) { + indices[i] = classifyDrawBuffer(bufs.get(basePos + i)); + } + if (indices != fbo.drawBuffers) fbo.drawBuffers = indices; + markDrawBuffersChanged(fbo, isBound); + } + + private void markDrawBuffersChanged(FboState fbo, boolean isBound) { + final ContextState cs = s(); + fbo.targetsDirty = true; + fbo.cachedFormatsDirty = true; + if (isBound) { + fboClearTracker.updatePipelineCacheColorFormats(cs, fbo); + cs.pipeline.markOutputDirty(); + } + } + @Override public void readBuffer(int mode) { + final int fboId = s().boundReadFboId; + if (fboId == 0) return; + final FboState fbo = resourceManager.getFbo(fboId); + if (fbo == null) return; + if (mode >= GL30.GL_COLOR_ATTACHMENT0 && mode < GL30.GL_COLOR_ATTACHMENT0 + ContextState.MAX_COLOR_ATTACHMENTS) { + fbo.readBufferIndex = mode - GL30.GL_COLOR_ATTACHMENT0; + } + } + + + @Override public void readPixels(int x, int y, int width, int height, int format, int type, ByteBuffer pixels) { + final ContextState cs = s(); + final long texHandle; + final int srcSdlFormat; + if (cs.boundReadFboId == 0) { + texHandle = frameManager.getSwapchainTexture(); + srcSdlFormat = frameManager.getSwapchainFormat(); + } else { + final FboState fbo = resourceManager.getFbo(cs.boundReadFboId); + if (fbo == null) return; + final int colorGlId = fbo.colorGlIds[fbo.readBufferIndex]; + texHandle = resourceManager.getTextureHandle(colorGlId); + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(colorGlId); + srcSdlFormat = meta != null ? meta.sdlFormat() : SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + } + textureOps.readbackTexture(texHandle, x, y, width, height, 0, pixels); + pixels.rewind(); + PixelOps.postProcessReadback(pixels, width, height, format, srcSdlFormat, cs.boundReadFboId == 0); + } + @Override public void readPixels(int x, int y, int width, int height, int format, int type, FloatBuffer pixels) { + readPixels(x, y, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); + } + @Override public void readPixels(int x, int y, int width, int height, int format, int type, IntBuffer pixels) { + readPixels(x, y, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); + } + @Override public void getTexImage(int target, int level, int format, int type, ByteBuffer pixels) { + final ContextState cs = s(); + final int glId = cs.boundTextures[cs.activeTextureUnit]; + final long texHandle = resourceManager.getTextureHandle(glId); + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + if (meta == null) return; + textureOps.readbackTexture(texHandle, 0, 0, meta.width(), meta.height(), level, pixels); + pixels.rewind(); + PixelOps.postProcessReadback(pixels, meta.width(), meta.height(), format, meta.sdlFormat(), false); + } + @Override public void getTexImage(int target, int level, int format, int type, IntBuffer pixels) { + getTexImage(target, level, format, type, MemoryUtil.memByteBuffer(pixels)); + } + @Override public void getTexImage(int target, int level, int format, int type, long pixelBufferOffset) { + final ContextState cs = s(); + final int pbo = cs.boundPixelPackBuffer; + if (pbo == 0) return; + final int glId = cs.boundTextures[cs.activeTextureUnit]; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + if (meta == null) return; + final ByteBuffer tmp = MemoryUtil.memAlloc(meta.width() * meta.height() * 4); + try { + getTexImage(target, level, format, type, tmp); + final long handle = resourceManager.getBufferHandle(pbo); + if (handle != 0 && frameManager.getCommandBuffer() != 0) { + tmp.rewind(); + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), tmp, handle, pixelBufferOffset, false); + resourceManager.markBufferContentsDefined(pbo); + } + } finally { + MemoryUtil.memFree(tmp); + } + } + + @Override public int getFramebufferAttachmentParameteri(int target, int attachment, int pname) { + final FboState fbo = resourceManager.getFbo(s().boundFboId); + if (fbo == null) return 0; + final int colorIdx = attachment - GL30.GL_COLOR_ATTACHMENT0; + final boolean isColor = (colorIdx >= 0 && colorIdx < ContextState.MAX_COLOR_ATTACHMENTS); + final boolean isDepth = (attachment == GL30.GL_DEPTH_ATTACHMENT || attachment == GL30.GL_DEPTH_STENCIL_ATTACHMENT); + if (pname == GL30.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME) { + return isColor ? fbo.colorGlIds[colorIdx] : isDepth ? fbo.depthGlId : 0; + } + if (pname == GL30.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE) { + if (isColor && fbo.colorGlIds[colorIdx] != 0) return GL11.GL_TEXTURE; + if (isDepth && fbo.depthGlId != 0) return GL11.GL_TEXTURE; + return GL11.GL_NONE; + } + return 0; + } + + @Override public int createShader(int type) { return shaderManager.createShader(type); } + @Override public void deleteShader(int shader) { shaderManager.deleteShader(shader); } + @Override public void shaderSource(int shader, CharSequence source) { shaderManager.shaderSource(shader, source); } + @Override public void compileShader(int shader) { shaderManager.compileShader(shader); } + @Override public boolean isShader(int obj) { return shaderManager.isShader(obj); } + @Override public boolean isProgram(int obj) { return shaderManager.isProgram(obj); } + @Override public int createProgram() { return shaderManager.createProgram(); } + @Override public void deleteProgram(int program) { + debugLabels.onProgramDeleted(program); + uniformEntriesCache.remove(program); + if (s().boundProgram == program) { + shaderManager.markProgramForDeletion(program); + return; + } + shaderManager.releaseProgramFinal(program); + } + @Override public void attachShader(int program, int shader) { shaderManager.attachShader(program, shader); } + @Override public void detachShader(int program, int shader) { /* No-op: SDL GPU shaders only needed at link time */ } + @Override public void linkProgram(int program) { + uniformEntriesCache.remove(program); + shaderManager.linkProgram(program); + final ContextState st = s(); + if (st.boundProgram == program) { + refreshBoundProgramShaderHandles(program); + } + } + + private void refreshBoundProgramShaderHandles(int program) { + final ContextState cs = s(); + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null) { + cs.pipeline.invalidateShaderHandles(); + return; + } + if (prog.sdlVertexShader == 0 && prog.vertexSpirv != null) { + final var vr = prog.vertexResources; + prog.sdlVertexShader = shaderManager.createSDLShader(prog.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures()); + } + if (prog.sdlFragmentShader == 0 && prog.fragmentSpirv != null) { + final var fr = prog.fragmentResources; + prog.sdlFragmentShader = shaderManager.createSDLShader(prog.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures()); + } + cs.pipeline.vertexShader = prog.sdlVertexShader; + cs.pipeline.fragmentShader = prog.sdlFragmentShader; + cs.pipeline.programId = program; + cs.pipeline.maxFragOutputLocation = prog.maxFragOutputLocation; + cs.pipeline.shaderInputMask = prog.vertexInputMask; + cs.pipeline.shaderInputVecSize = prog.vertexInputVecSize; + cs.pipeline.shaderInputBaseType = prog.vertexInputBaseType; + cs.pipeline.shaderInputName = prog.vertexInputName; + cs.pipeline.markShaderDirty(); + } + @Override public void useProgram(int program) { + final ContextState cs = s(); + final ContextState st = cs; + final int prevBoundProgram = st.boundProgram; + if (prevBoundProgram == program) return; + debugLabels.updateAutoDebugGroup(st, program); + + if (prevBoundProgram != 0) { + final ShaderManager.ProgramObject prevProg = shaderManager.getProgram(prevBoundProgram); + if (prevProg != null && prevProg.deletePending) { + shaderManager.releaseProgramFinal(prevBoundProgram); + } + } + st.boundProgram = program; + if (program == 0) { + st.boundProgramObj = null; + cs.pipeline.vertexShader = 0; + cs.pipeline.fragmentShader = 0; + cs.pipeline.programId = 0; + cs.pipeline.markShaderDirty(); + return; + } + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null) { + st.boundProgramObj = null; + if (missingProgramWarned.add(program)) { + LOG.warn("useProgram({}): program object missing from shaderManager (was it deleted?); zeroing pipeline shaders, draws will silently skip", program); + } + cs.pipeline.vertexShader = 0; + cs.pipeline.fragmentShader = 0; + cs.pipeline.programId = 0; + cs.pipeline.markShaderDirty(); + return; + } + st.boundProgramObj = prog; + if (prog.sdlVertexShader == 0 && prog.vertexSpirv != null) { + final var vr = prog.vertexResources; + prog.sdlVertexShader = shaderManager.createSDLShader(prog.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures()); + } + if (prog.sdlFragmentShader == 0 && prog.fragmentSpirv != null) { + final var fr = prog.fragmentResources; + prog.sdlFragmentShader = shaderManager.createSDLShader(prog.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures()); + } + cs.pipeline.vertexShader = prog.sdlVertexShader; + cs.pipeline.fragmentShader = prog.sdlFragmentShader; + cs.pipeline.programId = program; + cs.pipeline.maxFragOutputLocation = prog.maxFragOutputLocation; + cs.pipeline.shaderInputMask = prog.vertexInputMask; + cs.pipeline.shaderInputVecSize = prog.vertexInputVecSize; + cs.pipeline.shaderInputBaseType = prog.vertexInputBaseType; + cs.pipeline.shaderInputName = prog.vertexInputName; + cs.pipeline.markShaderDirty(); + } + + @Override public boolean supportsDebugOutput() { return debugLabels.isEnabled(); } + + @Override + public void debugMessageCallback(GLDebugMessageListener listener, long userParam) { + DebugMessageRelay.setListener(listener, userParam, debugLabels.isEnabled()); + } + + @Override + public int getDebugMessageLog(int count, IntBuffer sources, IntBuffer types, IntBuffer ids, IntBuffer severities, IntBuffer lengths, ByteBuffer messageLog) { + return DebugMessageRelay.drain(count, sources, types, ids, severities, lengths, messageLog); + } + + @Override + public void objectLabel(int identifier, int name, CharSequence label) { + debugLabels.objectLabel(identifier, name, label); + } + + @Override + public void pushDebugGroup(int source, int id, CharSequence message) { + debugLabels.pushDebugGroup(message); + } + + @Override + public void popDebugGroup() { + debugLabels.popDebugGroup(); + } + + @Override + public void debugMessageInsert(int source, int type, int id, int severity, CharSequence message) { + debugLabels.debugMessageInsert(message); + } + + + @Override public String getShaderInfoLog(int shader, int maxLength) { return shaderManager.getShaderInfoLog(shader); } + @Override public void getShaderInfoLog(int shader, IntBuffer length, ByteBuffer infoLog) { + writeUtf8(shaderManager.getShaderInfoLog(shader), length, infoLog); + } + @Override public String getProgramInfoLog(int program, int maxLength) { return shaderManager.getProgramInfoLog(program); } + @Override public void getProgramInfoLog(int program, IntBuffer length, ByteBuffer infoLog) { + writeUtf8(shaderManager.getProgramInfoLog(program), length, infoLog); + } + + private static void writeUtf8(String s, IntBuffer length, ByteBuffer out) { + if (out == null) { + if (length != null && length.remaining() > 0) length.put(0, 0); + return; + } + if (s == null) return; + final byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + final int n = Math.min(bytes.length, out.remaining()); + out.put(bytes, 0, n); + if (length != null && length.remaining() > 0) length.put(0, n); + } + @Override public int getShaderi(int shader, int pname) { + return switch (pname) { + case GL20.GL_COMPILE_STATUS -> shaderManager.isCompiled(shader) ? 1 : 0; + case GL20.GL_SHADER_TYPE -> shaderManager.getShaderType(shader); + case GL20.GL_INFO_LOG_LENGTH -> shaderManager.getShaderInfoLog(shader).length(); + default -> 0; + }; + } + @Override public int getProgrami(int program, int pname) { + return switch (pname) { + case GL20.GL_LINK_STATUS -> shaderManager.isLinked(program) ? 1 : 0; + case GL20.GL_VALIDATE_STATUS -> shaderManager.isLinked(program) ? 1 : 0; + case GL20.GL_INFO_LOG_LENGTH -> shaderManager.getProgramInfoLog(program).length(); + case GL20.GL_ATTACHED_SHADERS -> shaderManager.getAttachedShaderCount(program); + case GL20.GL_ACTIVE_UNIFORMS -> { + final var entries = getOrBuildUniformEntries(program); + yield entries != null ? entries.size() : 0; + } + case GL20.GL_ACTIVE_UNIFORM_MAX_LENGTH -> { + final var entries = getOrBuildUniformEntries(program); + int max = 0; + if (entries != null) for (UniformEntry e : entries) max = Math.max(max, e.name.length() + 1); + yield max; + } + case GL20.GL_ACTIVE_ATTRIBUTES -> { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + yield prog != null ? prog.getActiveAttribNames().size() : 0; + } + case GL20.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH -> { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + int max = 0; + if (prog != null) for (String n : prog.getActiveAttribNames()) max = Math.max(max, n.length() + 1); + yield max; + } + default -> 0; + }; + } + + private record UniformEntry(String name, int glType, int arrayLen) {} + private final Int2ObjectOpenHashMap> uniformEntriesCache = new Int2ObjectOpenHashMap<>(); + + private List getOrBuildUniformEntries(int program) { + final List cached = uniformEntriesCache.get(program); + if (cached != null) return cached; + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null || !prog.linked) return null; + final ArrayList result = new ArrayList<>(prog.nameToLocation.size()); + for (Map.Entry e : prog.nameToLocation.entrySet()) { + final String name = e.getKey(); + final int loc = e.getValue(); + int glType; + int arrayLen = 1; + if (prog.allSamplerNames.contains(name)) { + glType = GL20.GL_SAMPLER_2D; + } else { + ShaderManager.UniformMemberInfo umi = prog.anyBlockMemberInfo(loc); + if (umi == null) umi = prog.locationToMemberInfo.get(loc); + if (umi != null) { + glType = FormatMap.mapMemberInfoToGlType(umi); + arrayLen = Math.max(1, umi.arrayLen()); + } else { + glType = GL20.GL_FLOAT_VEC4; + } + if (prog.boolUniforms.contains(name)) { + glType = FormatMap.remapUnsignedIntToBool(glType); + } + } + result.add(new UniformEntry(name, glType, arrayLen)); + } + result.sort(Comparator.comparing(UniformEntry::name)); + final List immutable = Collections.unmodifiableList(result); + uniformEntriesCache.put(program, immutable); + return immutable; + } + + @Override public void getAttachedShaders(int program, IntBuffer count, IntBuffer shaders) { + shaderManager.getAttachedShaders(program, count, shaders); + } + @Override public String getShaderSource(int shader, int maxLength) { + final String src = shaderManager.getShaderSource(shader); + return maxLength > 0 && src.length() > maxLength ? src.substring(0, maxLength) : src; + } + @Override public void getProgramiv(int program, int pname, IntBuffer params) { + if (params.remaining() > 0) params.put(0, getProgrami(program, pname)); + } + @Override public String getActiveUniform(int program, int index, int maxLength, IntBuffer sizeType) { + final List entries = getOrBuildUniformEntries(program); + if (entries == null || index < 0 || index >= entries.size()) { + if (sizeType != null && sizeType.remaining() >= 2) { sizeType.put(0, 1); sizeType.put(1, GL20.GL_FLOAT_VEC4); } + return ""; + } + final UniformEntry e = entries.get(index); + if (sizeType != null && sizeType.remaining() >= 2) { + sizeType.put(0, e.arrayLen()); + sizeType.put(1, e.glType()); + } + return maxLength > 0 && e.name().length() > maxLength ? e.name().substring(0, maxLength) : e.name(); + } + @Override public void getActiveUniform(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) { + final List entries = getOrBuildUniformEntries(program); + final UniformEntry e = (entries != null && index >= 0 && index < entries.size()) ? entries.get(index) : null; + if (size != null && size.remaining() > 0) size.put(0, e != null ? e.arrayLen() : 1); + if (type != null && type.remaining() > 0) type.put(0, e != null ? e.glType() : GL20.GL_FLOAT_VEC4); + writeUtf8(e != null ? e.name() : "", length, name); + } + @Override public void bindAttribLocation(int program, int index, CharSequence name) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog != null) { + prog.attribLocationBindings.put(name.toString(), index); + } + } + @Override public int getAttribLocation(int program, CharSequence name) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null) return -1; + if (prog.linked) return prog.resolvedAttribLocations.getInt(name.toString()); + return prog.attribLocationBindings.getInt(name.toString()); + } + @Override public int getAttribLocation(int program, ByteBuffer name) { + return getAttribLocation(program, MemoryUtil.memASCII(name)); + } + @Override public int getUniformLocation(int program, CharSequence name) { + return shaderManager.getUniformLocation(program, name.toString()); + } + @Override public int getUniformLocation(int program, ByteBuffer name) { + return shaderManager.getUniformLocation(program, MemoryUtil.memASCII(name)); + } + @Override public void getShaderSource(int shader, IntBuffer length, ByteBuffer source) { + writeUtf8(shaderManager.getShaderSource(shader), length, source); + } + + @Override public void uniform1i(int location, int v0) { + if (location < 0) return; + final ContextState st = s(); + final ShaderManager.ProgramObject prog = st.boundProgramObj; + if (prog != null) { + final String name = prog.locationToName.get(location); + if (name != null && prog.allSamplerNames.contains(name)) { + if (prog.samplerTextureUnits.put(name, v0) != v0) prog.samplerUnitsDirty = true; + return; + } + if (name != null && prog.allImageNames.contains(name)) { + prog.imageTextureUnits.put(name, v0); + return; + } + if (debugLabels.isEnabled() && name == null && !prog.allSamplerNames.isEmpty() && v0 >= 0 && v0 <= 31) { + LOG.warn("uniform1i: loc={} val={} prog={} -- location NOT in locationToName (samplers={})", location, v0, st.boundProgram, prog.allSamplerNames); + } + } else if (debugLabels.isEnabled() && v0 >= 0 && v0 <= 16) { + LOG.warn("uniform1i: loc={} val={} -- NO program bound", location, v0); + } + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 1); + a[0] = Float.intBitsToFloat(v0); + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform1f(int location, float v0) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 1); + a[0] = v0; + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform2f(int location, float v0, float v1) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 2); + a[0] = v0; a[1] = v1; + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform2i(int location, int v0, int v1) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 2); + a[0] = Float.intBitsToFloat(v0); a[1] = Float.intBitsToFloat(v1); + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform3f(int location, float v0, float v1, float v2) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 3); + a[0] = v0; a[1] = v1; a[2] = v2; + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform3i(int location, int v0, int v1, int v2) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 3); + a[0] = Float.intBitsToFloat(v0); a[1] = Float.intBitsToFloat(v1); a[2] = Float.intBitsToFloat(v2); + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform4f(int location, float v0, float v1, float v2, float v3) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 4); + a[0] = v0; a[1] = v1; a[2] = v2; a[3] = v3; + pipelineApplier.putUniform(st, location, a); + } + @Override public void uniform4i(int location, int v0, int v1, int v2, int v3) { + if (location < 0) return; + final ContextState st = s(); + final float[] a = pipelineApplier.reuseOrAlloc(st, location, 4); + a[0] = Float.intBitsToFloat(v0); a[1] = Float.intBitsToFloat(v1); + a[2] = Float.intBitsToFloat(v2); a[3] = Float.intBitsToFloat(v3); + pipelineApplier.putUniform(st, location, a); + } + + @Override public void uniform1fv(int location, FloatBuffer value) { + pipelineApplier.putUniformFv(s(), location, value); + } + @Override public void uniform2(int location, FloatBuffer value) { + pipelineApplier.putUniformFv(s(), location, value); + } + @Override public void uniform1iv(int location, IntBuffer value) { storeIntUniform(location, value); } + @Override public void uniform2iv(int location, IntBuffer value) { storeIntUniform(location, value); } + @Override public void uniform3iv(int location, IntBuffer value) { storeIntUniform(location, value); } + @Override public void uniform4iv(int location, IntBuffer value) { storeIntUniform(location, value); } + private void storeIntUniform(int location, IntBuffer value) { + if (location < 0) return; + final ContextState st = s(); + final int n = value.remaining(); + final int pos = value.position(); + final float[] v = pipelineApplier.reuseOrAlloc(st, location, n); + for (int i = 0; i < n; i++) v[i] = Float.intBitsToFloat(value.get(pos + i)); + pipelineApplier.putUniform(st, location, v); + } + @Override public void uniform3(int location, FloatBuffer value) { + pipelineApplier.putUniformFv(s(), location, value); + } + @Override public void uniform4(int location, FloatBuffer value) { + pipelineApplier.putUniformFv(s(), location, value); + } + @Override public void uniform3fv(int location, float[] values) { pipelineApplier.putUniform(s(), location, values); } + @Override public void uniform4fv(int location, float[] values) { pipelineApplier.putUniform(s(), location, values); } + @Override public void uniformMatrix2(int location, boolean transpose, FloatBuffer value) { + pipelineApplier.storeMatrix(s(), location, transpose, value, 2); + } + @Override public void uniformMatrix3(int location, boolean transpose, FloatBuffer value) { + pipelineApplier.storeMatrix(s(), location, transpose, value, 3); + } + @Override public void uniformMatrix4(int location, boolean transpose, FloatBuffer value) { + pipelineApplier.storeMatrix(s(), location, transpose, value, 4); + } + + @Override public void vertexAttrib2f(int index, float v0, float v1) { + if (index >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = s(); + final float[] a = st.attribDefaults; + final int base = index * 4; + if (a[base] != v0 || a[base+1] != v1 || a[base+2] != 0f || a[base+3] != 1f) { + a[base] = v0; a[base+1] = v1; a[base+2] = 0f; a[base+3] = 1f; + st.attribDefaultsDirtyMask |= (1 << index); + } + } + @Override public void vertexAttrib3f(int index, float v0, float v1, float v2) { + if (index >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = s(); + final float[] a = st.attribDefaults; + final int base = index * 4; + if (a[base] != v0 || a[base+1] != v1 || a[base+2] != v2 || a[base+3] != 1f) { + a[base] = v0; a[base+1] = v1; a[base+2] = v2; a[base+3] = 1f; + st.attribDefaultsDirtyMask |= (1 << index); + } + } + @Override public void vertexAttrib4f(int index, float v0, float v1, float v2, float v3) { + if (index >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = s(); + final float[] a = st.attribDefaults; + final int base = index * 4; + if (a[base] != v0 || a[base+1] != v1 || a[base+2] != v2 || a[base+3] != v3) { + a[base] = v0; a[base+1] = v1; a[base+2] = v2; a[base+3] = v3; + st.attribDefaultsDirtyMask |= (1 << index); + } + } + + @Override public int genBuffers() { return resourceManager.genBuffer(); } + @Override public void deleteBuffers(int buffer) { dropMappingFor(buffer); readbackShadows.release(buffer); resourceManager.deleteBuffer(buffer); } + @Override public void deleteBuffers(IntBuffer buffers) { + for (int i = 0; i < buffers.remaining(); i++) { + final int buffer = buffers.get(buffers.position() + i); + dropMappingFor(buffer); + readbackShadows.release(buffer); + resourceManager.deleteBuffer(buffer); + } + } + + private static void dropMappingFor(int buffer) { + final ContextState st = s(); + if (buffer == 0 || st.mappedBufferGlId != buffer || st.mappedStagingBuffer == null) return; + MemoryUtil.memFree(st.mappedStagingBuffer); + clearMappedState(st); + } + @Override public void bindBuffer(int target, int buffer) { + final ContextState st = s(); + switch (target) { + case GL15.GL_ARRAY_BUFFER -> st.boundArrayBuffer = buffer; + case GL15.GL_ELEMENT_ARRAY_BUFFER -> { + if (st.currentVao.elementBuffer != buffer) { + st.currentVao.elementBuffer = buffer; + st.bumpAttribStateGen(); + } + } + case GL31.GL_UNIFORM_BUFFER -> st.boundUniformBuffer = buffer; + case GL30.GL_PIXEL_UNPACK_BUFFER -> st.boundPixelUnpackBuffer = buffer; + case GL30.GL_PIXEL_PACK_BUFFER -> st.boundPixelPackBuffer = buffer; + case GL40.GL_DRAW_INDIRECT_BUFFER -> st.boundIndirectBuffer = buffer; + case GL31.GL_COPY_READ_BUFFER -> st.boundCopyReadBuffer = buffer; + case GL31.GL_COPY_WRITE_BUFFER -> st.boundCopyWriteBuffer = buffer; + case GL43.GL_SHADER_STORAGE_BUFFER -> { + st.boundSSBO = buffer; + resourceManager.markBufferContentsDefined(buffer); + } + } + } + @Override public void bindBufferBase(int target, int index, int buffer) { + final ContextState cs = s(); + if (index >= 0 && index < ContextState.MAX_INDEXED_BUFFERS) { + switch (target) { + case GL31.GL_UNIFORM_BUFFER -> { + final ContextState st = cs; + st.boundUboByIndex[index] = buffer; + st.uboRangeOffset[index] = 0; + st.uboRangeSize[index] = 0; + st.uboRangeGen++; + } + case GL43.GL_SHADER_STORAGE_BUFFER -> { + cs.boundSsboByIndex[index] = buffer; + cs.ssboBindGen++; + } + } + } + bindBuffer(target, buffer); + } + + @Override public void bindBufferRange(int target, int index, int buffer, long offset, long size) { + final ContextState cs = s(); + if (index >= 0 && index < ContextState.MAX_INDEXED_BUFFERS) { + switch (target) { + case GL31.GL_UNIFORM_BUFFER -> { + final ContextState st = cs; + st.boundUboByIndex[index] = buffer; + st.uboRangeOffset[index] = (int) offset; + st.uboRangeSize[index] = (int) size; + st.uboRangeGen++; + } + case GL43.GL_SHADER_STORAGE_BUFFER -> { + cs.boundSsboByIndex[index] = buffer; + cs.ssboBindGen++; + } + } + } + bindBuffer(target, buffer); + } + + @Override public int getUniformBlockIndex(int program, CharSequence name) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null) return -1; + return (prog.vertexUboSize > 0 || prog.fragmentUboSize > 0) ? 0 : -1; + } + + @Override public void uniformBlockBinding(int program, int blockIndex, int binding) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog != null) prog.externalUboBinding = binding; + } + + @Override public int getIndexedBufferBinding(int target, int index) { + final ContextState cs = s(); + if (index < 0 || index >= ContextState.MAX_INDEXED_BUFFERS) return 0; + return switch (target) { + case GL31.GL_UNIFORM_BUFFER -> cs.boundUboByIndex[index]; + case GL43.GL_SHADER_STORAGE_BUFFER -> cs.boundSsboByIndex[index]; + default -> 0; + }; + } + + @Override public int getIntegerIndexed(int pname, int index) { + final ContextState cs = s(); + if (index < 0 || index >= ContextState.MAX_IMAGE_UNITS) return unknownGetInteger(pname); + return switch (pname) { + case GL42.GL_IMAGE_BINDING_NAME -> cs.boundStorageTextureByUnit[index]; + case GL42.GL_IMAGE_BINDING_LEVEL -> cs.boundStorageTextureLevel[index]; + case GL42.GL_IMAGE_BINDING_LAYERED -> cs.boundStorageTextureLayered[index] ? GL11.GL_TRUE : GL11.GL_FALSE; + case GL42.GL_IMAGE_BINDING_LAYER -> cs.boundStorageTextureLayer[index]; + case GL42.GL_IMAGE_BINDING_ACCESS -> cs.boundStorageTextureAccess[index]; + case GL42.GL_IMAGE_BINDING_FORMAT -> cs.boundStorageTextureFormat[index]; + default -> unknownGetInteger(pname); + }; + } + + @Override public void bufferData(int target, long size, int usage) { + final int glId = getBoundBuffer(target); + if (glId == 0) return; + resourceManager.recordBufferGlParams(glId, usage, BufferParams.MUTABLE_STORE); + if (target == GL31.GL_UNIFORM_BUFFER) { + if (resourceManager.getBufferSize(glId) == size) return; + if (size > 0) { + resourceManager.recordBufferSizeOnly(glId, size); + final ByteBuffer shadow = resourceManager.getOrAllocUboShadow(glId, (int) size); + shadow.position(0).limit((int) size); + for (int i = 0; i < (int) size; i += 8) shadow.putLong(i, 0L); + } + return; + } + final int sdlUsage = FormatMap.mapBufferUsage(target); + readbackShadows.release(glId); + resourceManager.deleteBuffer(glId); + resourceManager.createBuffer(glId, sdlUsage, size); + if (target == GL15.GL_ARRAY_BUFFER) s().bumpAttribStateGen(); + } + + @Override public void bufferData(int target, ByteBuffer data, int usage) { + final ContextState cs = s(); + final int glId = getBoundBuffer(target); + if (glId == 0 || data == null) return; + final long dataSize = data.remaining(); + resourceManager.recordBufferGlParams(glId, usage, BufferParams.MUTABLE_STORE); + if (target == GL31.GL_UNIFORM_BUFFER) { + if (dataSize > 0) { + resourceManager.recordBufferSizeOnly(glId, dataSize); + final ByteBuffer shadow = resourceManager.getOrAllocUboShadow(glId, (int) dataSize); + final ByteBuffer src = data.duplicate(); + shadow.position(0).limit((int) dataSize); + shadow.put(src); + shadow.position(0).limit((int) dataSize); + } + return; + } + final int sdlUsage = FormatMap.mapBufferUsage(target); + readbackShadows.release(glId); + resourceManager.deleteBuffer(glId); + final long handle = resourceManager.createBuffer(glId, sdlUsage, dataSize); + if (target == GL15.GL_ARRAY_BUFFER) cs.bumpAttribStateGen(); + if (target == GL15.GL_ELEMENT_ARRAY_BUFFER && dataSize > 0 + && (cs.primitiveRestartEnabled || resourceManager.hasEboShadow(glId))) { + persistentSync.mirrorEboShadow(glId, data, 0, (int) dataSize); + } + if (target == GL15.GL_ARRAY_BUFFER && dataSize > 0 && resourceManager.hasArrayShadow(glId)) { + resourceManager.mirrorArrayShadowFull(glId, data); + } + if (handle != 0) { + if (cs.deferUploads) { + enqueuePreCopied(data, handle, 0, false); + } else if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), data, handle, 0, false); + } + resourceManager.markBufferContentsDefined(glId); + } + } + + + @Override public void bufferData(int target, FloatBuffer data, int usage) { + if (data != null) bufferData(target, MemoryUtil.memByteBuffer(data), usage); + } + + @Override public void bufferData(int target, ShortBuffer data, int usage) { + if (data != null) bufferData(target, MemoryUtil.memByteBuffer(data), usage); + } + + @Override public void bufferData(int target, IntBuffer data, int usage) { + if (data != null) bufferData(target, MemoryUtil.memByteBuffer(data), usage); + } + + @Override public void bufferData(int target, DoubleBuffer data, int usage) { + if (data != null) bufferData(target, MemoryUtil.memByteBuffer(data), usage); + } + + private static final int STACK_PRIM_BYTES_MAX = 64 * 1024; + + @Override public void bufferData(int target, int[] data, int usage) { + final int bytes = data.length * 4; + if (bytes <= STACK_PRIM_BYTES_MAX) { + try (var stack = MemoryStack.stackPush()) { + final ByteBuffer buf = stack.malloc(bytes); + buf.asIntBuffer().put(data); + buf.position(0).limit(bytes); + bufferData(target, buf, usage); + } + return; + } + final ByteBuffer buf = MemoryUtil.memAlloc(bytes); + buf.asIntBuffer().put(data); + bufferData(target, buf, usage); + MemoryUtil.memFree(buf); + } + + @Override public void bufferData(int target, float[] data, int usage) { + final int bytes = data.length * 4; + if (bytes <= STACK_PRIM_BYTES_MAX) { + try (var stack = MemoryStack.stackPush()) { + final ByteBuffer buf = stack.malloc(bytes); + buf.asFloatBuffer().put(data); + buf.position(0).limit(bytes); + bufferData(target, buf, usage); + } + return; + } + final ByteBuffer buf = MemoryUtil.memAlloc(bytes); + buf.asFloatBuffer().put(data); + bufferData(target, buf, usage); + MemoryUtil.memFree(buf); + } + + @Override public void bufferSubData(int target, long offset, ByteBuffer data) { + final ContextState cs = s(); + final int glId = getBoundBuffer(target); + if (glId == 0 || data == null) return; + if (target == GL31.GL_UNIFORM_BUFFER) { + final ByteBuffer shadow = resourceManager.getUboShadow(glId); + if (shadow != null) { + final ByteBuffer src = data.duplicate(); + final int rem = src.remaining(); + shadow.position((int) offset).limit((int) offset + rem); + shadow.put(src); + shadow.position(0); + } + return; + } + if (target == GL15.GL_ELEMENT_ARRAY_BUFFER + && (cs.primitiveRestartEnabled || resourceManager.hasEboShadow(glId))) { + persistentSync.mirrorEboShadow(glId, data, (int) offset, data.remaining()); + } + if (target == GL15.GL_ARRAY_BUFFER && resourceManager.hasArrayShadow(glId)) { + resourceManager.mirrorArrayShadowRegion(glId, data, (int) offset); + } + final long handle = resourceManager.getBufferHandle(glId); + if (handle != 0) { + if (target == GL43.GL_SHADER_STORAGE_BUFFER) { + if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), data, handle, offset, true); + } else { + FrameManager.warnDroppedOutsideFrame(droppedSsboWriteWarned, "bufferSubData(GL_SHADER_STORAGE_BUFFER)"); + droppedSsboWriteWarned = true; + } + resourceManager.markBufferContentsDefined(glId); + return; + } + final boolean cycle = target == GL40.GL_DRAW_INDIRECT_BUFFER; + if (cs.deferUploads) { + enqueuePreCopied(data, handle, offset, cycle); + } else if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), data, handle, offset, cycle); + } + resourceManager.markBufferContentsDefined(glId); + } + } + + @Override public void bufferSubData(int target, long offset, ShortBuffer data) { + if (data != null) bufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + + @Override public void bufferSubData(int target, long offset, IntBuffer data) { + if (data != null) bufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + + @Override public void bufferSubData(int target, long offset, FloatBuffer data) { + if (data != null) bufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + + @Override public void bufferSubData(int target, long offset, DoubleBuffer data) { + if (data != null) bufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + + private int getBoundBuffer(int target) { return s().getBoundBuffer(target); } + + @Override public ByteBuffer mapBuffer(int target, int access) { + final int glId = getBoundBuffer(target); + final long size = resourceManager.getBufferSize(glId); + if (size <= 0) { + LOG.error("mapBuffer: buffer {} has no known size, cannot map", glId); + return null; + } + return mapBufferRange(target, 0, size, BufferParams.accessEnumToBits(access)); + } + + @Override public ByteBuffer mapBuffer(int target, int access, long length, ByteBuffer old_buffer) { + return mapBufferRange(target, 0, length, BufferParams.accessEnumToBits(access)); + } + + @Override public boolean unmapBuffer(int target) { + final ContextState cs = s(); + final int glId = getBoundBuffer(target); + + final PersistentMapping pm = resourceManager.removePersistentMapping(glId); + if (pm != null) { + resourceManager.releasePersistentStaging(pm); + return true; + } + + final ContextState st = cs; + if (st.mappedStagingBuffer == null) return false; + + final boolean writeMap = (st.mappedAccessFlags & GL30.GL_MAP_WRITE_BIT) != 0; + + if (target == GL30.GL_PIXEL_UNPACK_BUFFER) { + st.mappedStagingBuffer.position(0).limit((int) st.mappedLength); + final long gpuHandle = resourceManager.getBufferHandle(st.mappedBufferGlId); + if (writeMap && gpuHandle != 0) { + if (st.deferUploads) { + enqueuePreCopied(st.mappedStagingBuffer, gpuHandle, st.mappedOffset, false); + } else if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), st.mappedStagingBuffer, gpuHandle, st.mappedOffset, false); + } + resourceManager.markBufferContentsDefined(st.mappedBufferGlId); + } + final ByteBuffer old = resourceManager.putPboStaging(glId, st.mappedStagingBuffer); + if (old != null) MemoryUtil.memFree(old); + clearMappedState(st); + return true; + } + + if (target == GL31.GL_UNIFORM_BUFFER) { + final ByteBuffer shadow = resourceManager.getUboShadow(st.mappedBufferGlId); + if (writeMap && shadow != null && st.mappedOffset + st.mappedLength <= shadow.capacity()) { + st.mappedStagingBuffer.position(0).limit((int) st.mappedLength); + shadow.position((int) st.mappedOffset).limit((int) (st.mappedOffset + st.mappedLength)); + shadow.put(st.mappedStagingBuffer); + shadow.position(0).limit(shadow.capacity()); + resourceManager.markBufferContentsDefined(st.mappedBufferGlId); + } + MemoryUtil.memFree(st.mappedStagingBuffer); + clearMappedState(st); + return true; + } + + if (!writeMap) { + MemoryUtil.memFree(st.mappedStagingBuffer); + clearMappedState(st); + return true; + } + + st.mappedStagingBuffer.position(0).limit((int) st.mappedLength); + final long gpuHandle; + if (st.mappedInvalidate) { + final int sdlUsage = FormatMap.mapBufferUsage(0); + final long glSize = Math.max(resourceManager.getBufferSize(st.mappedBufferGlId), st.mappedLength); + final int glUsage = resourceManager.getBufferGlUsage(st.mappedBufferGlId); + final int storageFlags = resourceManager.getBufferStorageFlags(st.mappedBufferGlId); + resourceManager.deleteBuffer(st.mappedBufferGlId); + gpuHandle = resourceManager.createBuffer(st.mappedBufferGlId, sdlUsage, glSize); + resourceManager.recordBufferGlParams(st.mappedBufferGlId, glUsage, storageFlags); + st.bumpAttribStateGen(); + } else { + gpuHandle = resourceManager.getBufferHandle(st.mappedBufferGlId); + } + if (target == GL15.GL_ELEMENT_ARRAY_BUFFER + && (cs.primitiveRestartEnabled || resourceManager.hasEboShadow(st.mappedBufferGlId))) { + final int len = (int) st.mappedLength; + st.mappedStagingBuffer.position(0).limit(len); + persistentSync.mirrorEboShadow(st.mappedBufferGlId, st.mappedStagingBuffer, (int) st.mappedOffset, len); + st.mappedStagingBuffer.position(0).limit(len); + } + if (target == GL15.GL_ARRAY_BUFFER && resourceManager.hasArrayShadow(st.mappedBufferGlId)) { + final int len = (int) st.mappedLength; + st.mappedStagingBuffer.position(0).limit(len); + resourceManager.mirrorArrayShadowRegion(st.mappedBufferGlId, st.mappedStagingBuffer, (int) st.mappedOffset); + st.mappedStagingBuffer.position(0).limit(len); + } + if (gpuHandle != 0) { + if (st.deferUploads) { + enqueuePreCopied(st.mappedStagingBuffer, gpuHandle, st.mappedOffset, false); + } else if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), st.mappedStagingBuffer, gpuHandle, st.mappedOffset, false); + } + resourceManager.markBufferContentsDefined(st.mappedBufferGlId); + } + + MemoryUtil.memFree(st.mappedStagingBuffer); + clearMappedState(st); + return true; + } + + private static void clearMappedState(ContextState st) { + st.mappedStagingBuffer = null; + st.mappedBufferGlId = 0; + st.mappedOffset = 0; + st.mappedLength = 0; + st.mappedInvalidate = false; + st.mappedAccessFlags = 0; + } + + @Override public ByteBuffer mapBufferRange(int target, long offset, long length, int access) { + final int glId = getBoundBuffer(target); + if (glId == 0 || length <= 0) return null; + + final boolean persistent = (access & GL44.GL_MAP_PERSISTENT_BIT) != 0; + + if (persistent) { + if (target == GL15.GL_ARRAY_BUFFER) resourceManager.dropArrayShadow(glId); + final ByteBuffer staging = MemoryUtil.memCalloc((int) length); + final PersistentMapping fresh = new PersistentMapping(staging, offset, length, access); + final PersistentMapping prior = resourceManager.swapPersistentMapping(glId, fresh); + if (prior != null) resourceManager.releasePersistentStaging(prior); + return staging; + } + + final ContextState st = s(); + if (st.mappedStagingBuffer != null) MemoryUtil.memFree(st.mappedStagingBuffer); + st.mappedStagingBuffer = MemoryUtil.memAlloc((int) length); + st.mappedBufferGlId = glId; + st.mappedOffset = offset; + st.mappedLength = length; + st.mappedInvalidate = (access & GL30.GL_MAP_INVALIDATE_BUFFER_BIT) != 0; + st.mappedAccessFlags = access; + if ((access & (GL30.GL_MAP_INVALIDATE_BUFFER_BIT | GL30.GL_MAP_INVALIDATE_RANGE_BIT)) == 0) { + seedMappedStaging(target, glId, offset, length, st.mappedStagingBuffer); + } + return st.mappedStagingBuffer; + } + + private void seedMappedStaging(int target, int glId, long offset, long length, ByteBuffer staging) { + final int len = (int) length; + final long handle = resourceManager.getBufferHandle(glId); + + if (handle == 0 || resourceManager.hasUndefinedContents(glId)) { + MemoryUtil.memSet(staging, 0); + return; + } + + final ByteBuffer direct = switch (target) { + case GL31.GL_UNIFORM_BUFFER -> resourceManager.getUboShadow(glId); + case GL30.GL_PIXEL_UNPACK_BUFFER -> resourceManager.getPboStaging(glId); + default -> null; + }; + if (direct != null && offset >= 0 && offset + len <= direct.capacity()) { + serveFromShadow(direct, (int) offset, staging, len); + staging.position(0).limit(len); + return; + } + if (target == GL31.GL_UNIFORM_BUFFER) { + MemoryUtil.memSet(staging, 0); + return; + } + + if (readBufferRangeCpuFirst(target, glId, handle, offset, staging, len)) { + staging.position(0).limit(len); + return; + } + final long size = resourceManager.getBufferSize(glId); + if (offset < 0 || offset + len > size) { + MemoryUtil.memSet(staging, 0); + return; + } + downloadBufferBlocking(handle, (int) offset, len, staging); + staging.position(0).limit(len); + } + + private boolean readBufferRangeCpuFirst(int target, int glId, long handle, long offset, ByteBuffer dst, int rem) { + if (target == GL15.GL_ARRAY_BUFFER) { + final ByteBuffer shadow = resourceManager.getArrayShadow(glId); + if (shadow != null && offset >= 0 && offset + rem <= shadow.capacity()) { + serveFromShadow(shadow, (int) offset, dst, rem); + return true; + } + if (resourceManager.isArrayShadowWanted(glId)) { + final int fullSize = (int) resourceManager.getBufferSize(glId); + if (resourceManager.canShadowArrayBuffer(fullSize) && offset >= 0 && offset + rem <= fullSize) { + final ByteBuffer full = resourceManager.getOrAllocArrayShadow(glId, fullSize); + full.position(0).limit(fullSize); + downloadBufferBlocking(handle, 0, fullSize, full); + full.position(0).limit(fullSize); + serveFromShadow(full, (int) offset, dst, rem); + return true; + } + } else { + resourceManager.markArrayShadowWanted(glId); + } + } else if (target == GL15.GL_ELEMENT_ARRAY_BUFFER) { + final ByteBuffer shadow = resourceManager.getEboShadow(glId); + if (shadow != null && offset >= 0 && offset + rem <= shadow.capacity()) { + serveFromShadow(shadow, (int) offset, dst, rem); + return true; + } + if (resourceManager.isEboShadowWanted(glId)) { + final int fullSize = (int) resourceManager.getBufferSize(glId); + if (fullSize > 0 && offset >= 0 && offset + rem <= fullSize) { + final ByteBuffer full = resourceManager.getOrAllocEboShadow(glId, fullSize); + full.position(0).limit(fullSize); + downloadBufferBlocking(handle, 0, fullSize, full); + full.position(0).limit(fullSize); + resourceManager.bumpEboShadowVersion(glId); + resourceManager.invalidateSplitCacheFor(glId); + serveFromShadow(full, (int) offset, dst, rem); + return true; + } + } else { + resourceManager.markEboShadowWanted(glId); + } + } + return false; + } + + @Override public void flushMappedBufferRange(int target, long offset, long length) { + final int glId = getBoundBuffer(target); + if (glId == 0 || length <= 0) return; + persistentSync.onPersistentBufferWrite(glId, offset, length); + } + + @Override public void bufferStorage(int target, ByteBuffer data, int flags) { + bufferData(target, data, GL15.GL_DYNAMIC_DRAW); + recordImmutableStorage(target, flags); + } + + @Override public void bufferStorage(int target, long size, int flags) { + bufferData(target, size, GL15.GL_DYNAMIC_DRAW); + recordImmutableStorage(target, flags); + } + + private void recordImmutableStorage(int target, int flags) { + final int glId = getBoundBuffer(target); + if (glId != 0) resourceManager.recordBufferGlParams(glId, GL15.GL_DYNAMIC_DRAW, flags); + } + @Override public void getBufferSubData(int target, long offset, ByteBuffer data) { + final int glId = getBoundBuffer(target); + if (glId == 0 || data == null) return; + final long handle = resourceManager.getBufferHandle(glId); + if (handle == 0) return; + final int rem = data.remaining(); + + if (readbackShadows.serve(glId, offset, data, rem)) return; + if (readBufferRangeCpuFirst(target, glId, handle, offset, data, rem)) return; + + downloadBufferBlocking(handle, (int) offset, rem, data); + } + + private void downloadBufferBlocking(long handle, int offset, int size, ByteBuffer out) { + flushDeferredUploadsForRead(); + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (cb == 0) return; + resourceManager.downloadFromBuffer(cb, handle, offset, size, out); + } + + private void flushDeferredUploadsForRead() { + final ContextState st = s(); + drainDeferredPersistentRegions(st); + resourceManager.flushUploadArena(); + if (transferThread != null && st.frameHighestEnqueuedSeq > transferThread.getSubmittedSeq()) { + transferThread.awaitSubmittedUpTo(st.frameHighestEnqueuedSeq); + } + } + + private static void serveFromShadow(ByteBuffer shadow, int srcOffset, ByteBuffer data, int rem) { + final int dstPos = data.position(); + if (shadow.isDirect() && data.isDirect()) { + MemoryUtil.memCopy(MemoryUtil.memAddress0(shadow) + srcOffset, MemoryUtil.memAddress(data), rem); + data.position(dstPos + rem); + } else { + final ByteBuffer s = shadow.duplicate(); + s.position(srcOffset).limit(srcOffset + rem); + data.put(s); + } + } + @Override public void getBufferSubData(int target, long offset, ShortBuffer data) { + getBufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + @Override public void getBufferSubData(int target, long offset, IntBuffer data) { + getBufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + @Override public void getBufferSubData(int target, long offset, FloatBuffer data) { + getBufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + @Override public void getBufferSubData(int target, long offset, DoubleBuffer data) { + getBufferSubData(target, offset, MemoryUtil.memByteBuffer(data)); + } + @Override public int getBufferParameteri(int target, int pname) { + if (BufferParams.isUnknownPname(pname)) { + GLStateManager.warnOnce("buffer-param-pname", "getBufferParameteri: unsupported pname 0x{} on target 0x{}", + Integer.toHexString(pname), Integer.toHexString(target)); + return 0; + } + final int glId = getBoundBuffer(target); + if (glId == 0) { + GLStateManager.warnOnce("buffer-param-unbound", "getBufferParameteri: no buffer bound to target 0x{}", Integer.toHexString(target)); + return 0; + } + + final PersistentMapping pm = resourceManager.getPersistentMapping(glId); + final ContextState st = s(); + final boolean plainMapped = st.mappedStagingBuffer != null && st.mappedBufferGlId == glId; + + final boolean mapped; + final int accessFlags; + final long mapOffset; + final long mapLength; + if (pm != null) { + mapped = true; + accessFlags = pm.accessFlags; + mapOffset = pm.offset; + mapLength = pm.length; + } else if (plainMapped) { + mapped = true; + accessFlags = st.mappedAccessFlags; + mapOffset = st.mappedOffset; + mapLength = st.mappedLength; + } else { + mapped = false; + accessFlags = 0; + mapOffset = 0; + mapLength = 0; + } + + return BufferParams.resolve(pname, resourceManager.getBufferSize(glId), + resourceManager.getBufferGlUsage(glId), resourceManager.getBufferStorageFlags(glId), + mapped, accessFlags, mapOffset, mapLength); + } + @Override public boolean isBuffer(int buffer) { return resourceManager.getBufferHandle(buffer) != 0 || resourceManager.getBufferSize(buffer) > 0; } + @Override public boolean isTexture(int texture) { return resourceManager.getTextureHandle(texture) != 0 || resourceManager.getTextureMeta(texture) != null; } + @Override public boolean isFramebuffer(int framebuffer) { return resourceManager.getFbo(framebuffer) != null; } + @Override public boolean isRenderbuffer(int renderbuffer) { return resourceManager.getTextureHandle(renderbuffer) != 0 || resourceManager.getTextureMeta(renderbuffer) != null; } + @Override public boolean isSampler(int sampler) { return resourceManager.getSamplerHandle(sampler) != 0 || resourceManager.getSamplerObject(sampler) != null; } + @Override public boolean isQuery(int query) { return query > 0 && query < nextQueryId.get(); } + + private final AtomicInteger nextQueryId = new AtomicInteger(1); + + @Override public void genQueries(IntBuffer ids) { + for (int i = ids.position(); i < ids.limit(); i++) ids.put(i, nextQueryId.getAndIncrement()); + } + @Override public int genQueries() { return nextQueryId.getAndIncrement(); } + @Override public void deleteQueries(int id) {} + @Override public void beginQuery(int target, int id) { warnQueriesUnsupported(); } + @Override public void endQuery(int target) {} + @Override public void queryCounter(int id, int target) { warnQueriesUnsupported(); } + @Override public void getQueryObjectui(int id, int pname, IntBuffer params) { + params.put(params.position(), queryResult(pname)); + } + @Override public int getQueryObjecti(int id, int pname) { return queryResult(pname); } + @Override public long getQueryObjectui64(int id, int pname) { return queryResult(pname); } + + private static int queryResult(int pname) { + return pname == GL15.GL_QUERY_RESULT_AVAILABLE ? 1 : 0; + } + + private boolean queriesUnsupportedWarned; + + private void warnQueriesUnsupported() { + if (queriesUnsupportedWarned) return; + queriesUnsupportedWarned = true; + LOG.warn("GL query objects are unsupported on the SDL GPU backend: SDL_gpu exposes no timestamp or occlusion query API."); + } + + private final AtomicInteger nextVaoId = new AtomicInteger(1); + + @Override public int genVertexArrays() { + final int id = nextVaoId.getAndIncrement(); + resourceManager.putVao(id, new ContextState.VAOState()); + return id; + } + @Override public void deleteVertexArrays(int array) { + final ContextState cs = s(); + final ContextState st = cs; + if (st.boundVAO == array) { + st.boundVAO = 0; + st.currentVao = st.defaultVaoState; + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + resourceManager.deleteVao(array); + } + @Override public void bindVertexArray(int array) { + final ContextState cs = s(); + final ContextState st = cs; + if (array == st.boundVAO) return; + st.boundVAO = array; + st.currentVao = (array == 0) ? st.defaultVaoState : resourceManager.getOrCreateVao(array); + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + @Override public boolean isVertexArray(int array) { + return array != 0 && resourceManager.getVao(array) != null; + } + @Override public void vertexAttribPointer(int index, int size, int type, boolean normalized, int stride, long pointer) { + applyVertexAttribPointer(index, size, type, normalized, false, stride, pointer); + } + @Override public void vertexAttribIPointer(int index, int size, int type, int stride, long pointer) { + applyVertexAttribPointer(index, size, type, false, true, stride, pointer); + } + + private void applyVertexAttribPointer(int index, int size, int type, boolean normalized, boolean isInteger, int stride, long pointer) { + vertexAttribs.applyVertexAttribPointer(s(), index, size, type, normalized, isInteger, stride, pointer); + } + @Override public void enableVertexAttribArray(int index) { + final ContextState cs = s(); + if (index < ContextState.MAX_VERTEX_ATTRIBS) { + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + if (vao.attribEnabled[index]) return; + vao.attribEnabled[index] = true; + vao.attribEnabledMask |= (1 << index); + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + } + @Override public void disableVertexAttribArray(int index) { + final ContextState cs = s(); + if (index < ContextState.MAX_VERTEX_ATTRIBS) { + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + if (!vao.attribEnabled[index]) return; + vao.attribEnabled[index] = false; + vao.attribEnabledMask &= ~(1 << index); + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + } + @Override public void vertexAttribDivisor(int index, int divisor) { + final ContextState cs = s(); + if (index >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + final int b = vao.attribBinding[index]; + if (b < 0 || b >= ContextState.MAX_VERTEX_ATTRIBS) return; + int effective = divisor; + if (divisor > 1) { + vertexAttribs.warnDivisorClamp(st.boundProgram, index, divisor); + effective = 1; + } + if (vao.bindingDivisor[b] != effective) { + vao.bindingDivisor[b] = effective; + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + } + + @Override public void bindVertexBuffer(int bindingindex, int buffer, long offset, int stride) { + final ContextState cs = s(); + if (bindingindex < 0 || bindingindex >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + if (vao.bindingBuffer[bindingindex] != buffer || vao.bindingOffset[bindingindex] != offset) { + final int oldBuffer = vao.bindingBuffer[bindingindex]; + vao.bindingBuffer[bindingindex] = buffer; + vao.bindingOffset[bindingindex] = offset; + st.bumpAttribStateGen(); + if (oldBuffer != buffer) { + cs.pipeline.markInputDirtyIfLivenessChanged(pipelineStore, oldBuffer, buffer); + } + } + if (vao.bindingStride[bindingindex] != stride) { + vao.bindingStride[bindingindex] = stride; + cs.pipeline.markInputDirty(); + } + } + @Override public void vertexAttribFormat(int attribindex, int size, int type, boolean normalized, int relativeoffset) { + final ContextState cs = s(); + if (attribindex >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + vao.attribSize[attribindex] = size; + vao.attribType[attribindex] = type; + vao.attribNormalized[attribindex] = normalized; + vao.attribIsInteger[attribindex] = false; + vao.attribRelativeOffset[attribindex] = relativeoffset; + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + @Override public void vertexAttribIFormat(int attribindex, int size, int type, int relativeoffset) { + final ContextState cs = s(); + if (attribindex >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + vao.attribSize[attribindex] = size; + vao.attribType[attribindex] = type; + vao.attribNormalized[attribindex] = false; + vao.attribIsInteger[attribindex] = true; + vao.attribRelativeOffset[attribindex] = relativeoffset; + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + @Override public void vertexAttribBinding(int attribindex, int bindingindex) { + final ContextState cs = s(); + if (attribindex >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState st = cs; + final ContextState.VAOState vao = st.currentVao; + if (vao.attribBinding[attribindex] != bindingindex) { + vao.attribBinding[attribindex] = bindingindex; + st.bumpAttribStateGen(); + cs.pipeline.markInputDirty(); + } + } + + @Override public int createTextures(int target) { return resourceManager.genTexture(); } + @Override public void bindTextureUnit(int unit, int texture) { + final ContextState st = s(); + if (unit >= 0 && unit < st.boundTextures.length) { + if (st.boundTextures[unit] != texture) { + st.boundTextures[unit] = texture; + st.samplerBindGen++; + } + } + } + @Override public void textureParameteri(int texture, int target, int pname, int param) { + textureOps.texParameteri(s(), pname, param, texture); + } + @Override public void textureParameterf(int texture, int target, int pname, float param) { + textureOps.texParameterf(s(), pname, param, texture); + } + @Override public void textureParameteriv(int texture, int target, int pname, IntBuffer params) { + if (params.remaining() > 0) textureParameteri(texture, target, pname, params.get(params.position())); + } + @Override public void texStorage1D(int target, int levels, int internalFormat, int width) { + final ContextState st = s(); + texStorageImpl(st, st.boundTextures[st.activeTextureUnit], target, internalFormat, width, 1, 1, levels); + } + @Override public void texStorage2D(int target, int levels, int internalFormat, int width, int height) { + final ContextState st = s(); + texStorageImpl(st, st.boundTextures[st.activeTextureUnit], target, internalFormat, width, height, 1, levels); + } + @Override public void texStorage3D(int target, int levels, int internalFormat, int width, int height, int depth) { + final ContextState st = s(); + texStorageImpl(st, st.boundTextures[st.activeTextureUnit], target, internalFormat, width, height, depth, levels); + } + @Override public void textureStorage1D(int texture, int levels, int internalFormat, int width) { + texStorageImpl(s(), texture, GL11.GL_TEXTURE_2D, internalFormat, width, 1, 1, levels); + } + @Override public void textureStorage2D(int texture, int levels, int internalFormat, int width, int height) { + texStorageImpl(s(), texture, GL11.GL_TEXTURE_2D, internalFormat, width, height, 1, levels); + } + @Override public void textureStorage3D(int texture, int levels, int internalFormat, int width, int height, int depth) { + texStorageImpl(s(), texture, GL11.GL_TEXTURE_2D, internalFormat, width, height, depth, levels); + } + + private void texStorageImpl(ContextState st, int glId, int target, int internalFormat, int w, int h, int d, int levels) { + if (glId == 0) return; + textureOps.releaseTextureForRealloc(st, glId); + resourceManager.createTexture(glId, target, internalFormat, w, h, d, levels); + resourceManager.refreshTextureReferences(glId); + } + @Override public void generateTextureMipmap(int texture) { + final long texHandle = resourceManager.getTextureHandle(texture); + if (texHandle == 0 || frameManager.getCommandBuffer() == 0) return; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(texture); + if (meta == null || meta.levels() <= 1) return; + // SDL asserts if any pass (render or copy) is active when generating mipmaps. + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + frameManager.noteMipGen(); + textureOps.clearPendingMipGen(texture); + SDL_GenerateMipmapsForGPUTexture(frameManager.getCommandBuffer(), texHandle); + } + @Override public void textureImage2DEXT(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { + if (texture == 0) return; + final ContextState st = s(); + if (level == 0) { + final TextureSamplerState ss = resourceManager.getOrCreateTexSamplerState(texture); + final int numLevels = ss.maxLevel >= 0 ? ss.maxLevel + 1 : PixelOps.defaultMipLevels(width, height); + textureOps.releaseTextureForRealloc(st, texture); + if (format == GL12.GL_BGRA && (internalformat == GL11.GL_RGBA || internalformat == GL11.GL_RGBA8)) { + resourceManager.createTextureWithSdlFormat(texture, target, + SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + internalformat, width, height, 1, numLevels); + } else { + resourceManager.createTexture(texture, target, internalformat, width, height, 1, numLevels); + } + resourceManager.refreshTextureReferences(texture); + } + textureOps.uploadTextureRegion(st, texture, resourceManager.getTextureMeta(texture), resourceManager.getTextureHandle(texture), pixels, 0, 0, width, height, level, format, type); + } + @Override public void textureImage2DEXT(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { + if (pixels != null) textureImage2DEXT(texture, target, level, internalformat, width, height, border, format, type, MemoryUtil.memByteBuffer(pixels)); + else textureImage2DEXT(texture, target, level, internalformat, width, height, border, format, type, (ByteBuffer) null); + } + @Override public void textureSubImage2D(int texture, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { + if (texture == 0 || pixels == null) return; + textureOps.uploadTextureRegion(s(), texture, resourceManager.getTextureMeta(texture), + resourceManager.getTextureHandle(texture), + pixels, xoffset, yoffset, width, height, level, format, type); + } + @Override public void textureSubImage2D(int texture, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { + if (pixels != null) textureSubImage2D(texture, level, xoffset, yoffset, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); + } + @Override public int createFramebuffers() { return genFramebuffers(); } + @Override public void namedFramebufferTexture(int framebuffer, int attachment, int texture, int level) { + final ContextState cs = s(); + final int savedFbo = cs.boundFboId; + cs.boundFboId = framebuffer; + if (resourceManager.getFbo(framebuffer) == null) resourceManager.createFbo(framebuffer); + framebufferTexture2D(GL30.GL_FRAMEBUFFER, attachment, GL11.GL_TEXTURE_2D, texture, level); + cs.boundFboId = savedFbo; + if (savedFbo != 0 && savedFbo != framebuffer) { + final FboState currentFbo = resourceManager.getFbo(savedFbo); + if (currentFbo != null) { + fboClearTracker.updatePipelineCacheColorFormats(cs, currentFbo); + cs.pipeline.markOutputDirty(); + } + } + } + @Override public void namedFramebufferReadBuffer(int framebuffer, int mode) { + final FboState fbo = resourceManager.getFbo(framebuffer); + if (fbo == null) return; + if (mode >= GL30.GL_COLOR_ATTACHMENT0 && mode < GL30.GL_COLOR_ATTACHMENT0 + ContextState.MAX_COLOR_ATTACHMENTS) { + fbo.readBufferIndex = mode - GL30.GL_COLOR_ATTACHMENT0; + } + } + @Override public void namedFramebufferDrawBuffers(int framebuffer, IntBuffer bufs) { + final FboState fbo = resourceManager.getFbo(framebuffer); + if (fbo == null) return; + applyDrawBuffersFromIntBuffer(fbo, bufs, framebuffer == s().boundFboId); + } + @Override public void blitNamedFramebuffer(int readFramebuffer, int drawFramebuffer, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + final FboState srcFbo = resourceManager.getFbo(readFramebuffer); + final FboState dstFbo = resourceManager.getFbo(drawFramebuffer); + if (srcFbo == null || dstFbo == null) return; + + final boolean isDepth = (mask & GL11.GL_DEPTH_BUFFER_BIT) != 0; + long srcTex = 0, dstTex = 0; + int dstGlId = 0; + if (isDepth) { + srcTex = srcFbo.depthTexture; + dstTex = dstFbo.depthTexture; + dstGlId = dstFbo.depthGlId; + } else if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) { + srcTex = srcFbo.colorTextures[srcFbo.readBufferIndex]; + dstTex = dstFbo.colorTextures[0]; + dstGlId = dstFbo.colorGlIds[0]; + } + if (srcTex == 0 || dstTex == 0) return; + + final ContextState cs = s(); + fboClearTracker.materializePendingClearForTexture(cs, srcTex); + if (!fboClearTracker.discardPendingClearIfFullyCovered(cs, dstTex, dstX0, dstY0, 0, dstX1 - dstX0, dstY1 - dstY0, resourceManager.getTextureMeta(dstGlId))) { + fboClearTracker.materializePendingClearForTexture(cs, dstTex); + } + + if (isDepth) { + textureOps.copyTexture(srcTex, srcX0, srcY0, dstTex, dstX0, dstY0, srcX1 - srcX0, srcY1 - srcY0); + } else { + final ResourceManager.TextureMeta srcMeta = resourceManager.getTextureMeta(srcFbo.colorGlIds[srcFbo.readBufferIndex]); + final ResourceManager.TextureMeta dstMeta = resourceManager.getTextureMeta(dstFbo.colorGlIds[0]); + if (TextureOps.canCopyInsteadOfBlit(srcMeta, dstMeta, srcX1 - srcX0, srcY1 - srcY0, dstX1 - dstX0, dstY1 - dstY0)) { + textureOps.copyTexture(srcTex, srcX0, srcY0, dstTex, dstX0, dstY0, srcX1 - srcX0, srcY1 - srcY0); + } else { + textureOps.blitTexture(srcTex, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0, dstTex, dstX0, dstY0, dstX1 - dstX0, dstY1 - dstY0, filter); + } + } + } + @Override public int createBuffers() { return resourceManager.genBuffer(); } + @Override public void namedBufferData(int buffer, long size, int usage) { + if (buffer == 0 || size <= 0) return; + final int sdlUsage = FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER); + resourceManager.deleteBuffer(buffer); + resourceManager.createBuffer(buffer, sdlUsage, size); + resourceManager.recordBufferGlParams(buffer, usage, BufferParams.MUTABLE_STORE); + } + @Override public void namedBufferData(int buffer, ByteBuffer data, int usage) { + if (buffer == 0 || data == null) return; + final int sdlUsage = FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER); + resourceManager.deleteBuffer(buffer); + final long handle = resourceManager.createBuffer(buffer, sdlUsage, data.remaining()); + resourceManager.recordBufferGlParams(buffer, usage, BufferParams.MUTABLE_STORE); + if (handle != 0 && frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), data, handle, 0, false); + resourceManager.markBufferContentsDefined(buffer); + } + } + @Override public void namedBufferData(int buffer, FloatBuffer data, int usage) { + if (data != null) namedBufferData(buffer, MemoryUtil.memByteBuffer(data), usage); + } + @Override public void namedBufferSubData(int buffer, long offset, ByteBuffer data) { + if (buffer == 0 || data == null) return; + final long handle = resourceManager.getBufferHandle(buffer); + if (handle != 0 && frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), data, handle, offset, false); + resourceManager.markBufferContentsDefined(buffer); + } + } + @Override public void copyTextureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + textureOps.copyTexSubImageImpl(s(),texture, level, xoffset, yoffset, x, y, width, height); + } + + + @Override public int getTextureParameteri(int texture, int target, int pname) { + final TextureSamplerState ss = resourceManager.getTexSamplerState(texture); + if (ss == null) { + return switch (pname) { + case GL11.GL_TEXTURE_MIN_FILTER -> GL11.GL_NEAREST_MIPMAP_LINEAR; + case GL11.GL_TEXTURE_MAG_FILTER -> GL11.GL_LINEAR; + case GL11.GL_TEXTURE_WRAP_S, GL11.GL_TEXTURE_WRAP_T, GL12.GL_TEXTURE_WRAP_R -> GL11.GL_REPEAT; + case GL12.GL_TEXTURE_MAX_LEVEL -> 1000; + default -> 0; + }; + } + return switch (pname) { + case GL11.GL_TEXTURE_MIN_FILTER -> ss.minFilter; + case GL11.GL_TEXTURE_MAG_FILTER -> ss.magFilter; + case GL11.GL_TEXTURE_WRAP_S -> ss.wrapS; + case GL11.GL_TEXTURE_WRAP_T -> ss.wrapT; + case GL12.GL_TEXTURE_WRAP_R -> ss.wrapR; + case GL12.GL_TEXTURE_MAX_LEVEL -> ss.maxLevel; + default -> 0; + }; + } + @Override public float getTextureParameterf(int texture, int target, int pname) { + final TextureSamplerState ss = resourceManager.getTexSamplerState(texture); + if (ss == null) { + return switch (pname) { + case GL12.GL_TEXTURE_MIN_LOD -> -1000.0f; + case GL12.GL_TEXTURE_MAX_LOD -> 1000.0f; + case GL14.GL_TEXTURE_LOD_BIAS -> 0.0f; + case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> 1.0f; + default -> getTextureParameteri(texture, target, pname); + }; + } + return switch (pname) { + case GL12.GL_TEXTURE_MIN_LOD -> ss.minLod; + case GL12.GL_TEXTURE_MAX_LOD -> ss.maxLod; + case GL14.GL_TEXTURE_LOD_BIAS -> ss.lodBias; + case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> ss.maxAnisotropy; + default -> getTextureParameteri(texture, target, pname); + }; + } + @Override public int getTextureLevelParameteri(int texture, int level, int pname) { + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(texture); + if (meta == null) return 0; + final int mipW = Math.max(1, meta.width() >> level); + final int mipH = Math.max(1, meta.height() >> level); + return switch (pname) { + case GL11.GL_TEXTURE_WIDTH -> mipW; + case GL11.GL_TEXTURE_HEIGHT -> mipH; + case GL11.GL_TEXTURE_INTERNAL_FORMAT -> { + final int stored = meta.glFormat(); + yield TextureInfoCache.isGenericCompressedInternalFormat(stored) ? GL11.GL_RGBA8 : stored; + } + default -> 0; + }; + } + + @Override public int getInteger(int pname) { + final ContextState cs = s(); + return switch (pname) { + case GL11.GL_MAX_TEXTURE_SIZE -> 16384; + case GL20.GL_MAX_TEXTURE_IMAGE_UNITS -> 17; + case GL20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS -> 17; + case GL20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS -> 32; + case GL20.GL_MAX_VERTEX_ATTRIBS -> 16; + case GL20.GL_MAX_DRAW_BUFFERS -> 8; + case GL30.GL_MAX_COLOR_ATTACHMENTS -> 8; + case GL15.GL_ARRAY_BUFFER_BINDING -> cs.boundArrayBuffer; + case GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING -> cs.currentVao.elementBuffer; + case GL20.GL_CURRENT_PROGRAM -> cs.boundProgram; + case GL32.GL_CONTEXT_PROFILE_MASK -> GL32.GL_CONTEXT_CORE_PROFILE_BIT; + case GL30.GL_MAJOR_VERSION -> 4; + case GL30.GL_MINOR_VERSION -> 6; + case GL30.GL_NUM_EXTENSIONS -> ADVERTISED_EXTENSIONS.length; + case GL42.GL_MAX_IMAGE_UNITS -> 8; + case GL43.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS -> 8; + case GL43.GL_MAX_DEBUG_GROUP_STACK_DEPTH -> 64; + case GL43.GL_MAX_LABEL_LENGTH -> 256; + case GL43.GL_MAX_DEBUG_MESSAGE_LENGTH -> 1024; + case GL11.GL_DRAW_BUFFER -> drawBufferEnum(cs.boundFboId); + case GL11.GL_READ_BUFFER -> readBufferEnum(cs.boundReadFboId); + case GL11.GL_TEXTURE_BINDING_2D -> boundTextureOf(cs.activeTextureUnit, cs.boundTextures); + default -> { + final int limit = deviceLimit(pname); + yield limit >= 0 ? limit : unknownGetInteger(pname); + } + }; + } + + static int bufferEnum(int fboId, int attachmentIndex) { + if (fboId == 0) return GL11.GL_BACK; + if (attachmentIndex < 0) return GL11.GL_NONE; + return GL30.GL_COLOR_ATTACHMENT0 + attachmentIndex; + } + + private int drawBufferEnum(int fboId) { + if (fboId == 0) return bufferEnum(0, 0); + final FboState fbo = resourceManager.getFbo(fboId); + final int idx = (fbo == null || fbo.drawBuffers.length == 0) ? -1 : fbo.drawBuffers[0]; + return bufferEnum(fboId, idx); + } + + private int readBufferEnum(int fboId) { + if (fboId == 0) return bufferEnum(0, 0); + final FboState fbo = resourceManager.getFbo(fboId); + return bufferEnum(fboId, fbo == null ? -1 : fbo.readBufferIndex); + } + + static int boundTextureOf(int unit, int[] boundTextures) { + return (unit >= 0 && unit < boundTextures.length) ? boundTextures[unit] : 0; + } + + static int deviceLimit(int pname) { + return switch (pname) { + case GL20.GL_MAX_VERTEX_UNIFORM_COMPONENTS, GL20.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS -> MAX_UNIFORM_COMPONENTS_PER_STAGE; + case GL30.GL_MAX_ARRAY_TEXTURE_LAYERS -> MAX_ARRAY_TEXTURE_LAYERS; + default -> -1; + }; + } + + static final int MAX_UNIFORM_COMPONENTS_PER_STAGE = 4096 / Float.BYTES; + static final int MAX_ARRAY_TEXTURE_LAYERS = 256; + + private static int unknownGetInteger(int pname) { + synchronized (UNKNOWN_GET_INTEGER_SEEN) { + if (UNKNOWN_GET_INTEGER_SEEN.add(pname)) { + LOG.warn("getInteger: unhandled pname 0x{}, returning 0; callers that save/restore this state will corrupt it", Integer.toHexString(pname)); + } + } + return 0; + } + + private static final IntOpenHashSet UNKNOWN_GET_INTEGER_SEEN = new IntOpenHashSet(); + @Override public void getInteger(int pname, IntBuffer params) { + if (params.remaining() > 0) params.put(params.position(), getInteger(pname)); + } + @Override public float getFloat(int pname) { + return switch (pname) { + case GL11.GL_LINE_WIDTH -> 1.0f; + case GL11.GL_POINT_SIZE -> 1.0f; + default -> 0.0f; + }; + } + @Override public void getFloat(int pname, FloatBuffer params) { + if (params == null || params.remaining() == 0) return; + if (pname == GL12.GL_ALIASED_LINE_WIDTH_RANGE || pname == GL11.GL_LINE_WIDTH_RANGE) { + if (params.remaining() >= 2) { + params.put(params.position(), 1.0f); + params.put(params.position() + 1, 1.0f); + } + } else { + params.put(params.position(), getFloat(pname)); + } + } + @Override public boolean getBoolean(int pname) { + final ContextState cs = s(); + return switch (pname) { + case GL11.GL_DEPTH_TEST -> cs.pipeline.depthTestEnabled; + case GL11.GL_BLEND -> cs.pipeline.blendEnabledPerAttachment[0]; + case GL11.GL_CULL_FACE -> cs.pipeline.cullEnabled; + case GL11.GL_SCISSOR_TEST -> cs.scissorEnabled; + case GL11.GL_STENCIL_TEST -> cs.pipeline.stencilTestEnabled; + case GL11.GL_DEPTH_WRITEMASK -> cs.pipeline.depthWriteEnabled; + default -> false; + }; + } + @Override public void getBoolean(int pname, ByteBuffer params) { + if (params != null && params.remaining() > 0) params.put(params.position(), (byte)(getBoolean(pname) ? 1 : 0)); + } + @Override public String getString(int pname) { + if (pname == GL11.GL_RENDERER) return cachedRenderer; + if (pname == GL11.GL_VENDOR) return cachedVendor; + if (pname == GL11.GL_VERSION) return cachedVersion; + if (pname == GL20.GL_SHADING_LANGUAGE_VERSION) return "4.60"; + if (pname == GL11.GL_EXTENSIONS) return cachedExtensions; + return ""; + } + @Override public String getStringi(int name, int index) { + if (name == GL11.GL_EXTENSIONS && index >= 0 && index < ADVERTISED_EXTENSIONS.length) { + return ADVERTISED_EXTENSIONS[index]; + } + return ""; + } + @Override public int getError() { return 0; } + + @Override public long fenceSync(int condition, int flags) { return fenceTracker.fenceSync(); } + @Override public int clientWaitSync(long sync, int flags, long timeout) { return fenceTracker.clientWaitSync(sync, flags, timeout); } + @Override public void deleteSync(long sync) { fenceTracker.deleteSync(sync); } + public boolean isFenceSignaled(long sync) { return fenceTracker.isFenceSignaled(sync); } + public int getSyncStatus(long sync) { return fenceTracker.getSyncStatus(sync); } + @Override public void waitSync(long sync, int flags, long timeout) { fenceTracker.waitSync(sync); } + @Override public int getSynci(long sync, int pname, IntBuffer length) { + final int val = fenceTracker.getSyncStatus(sync); + if (length != null && length.remaining() > 0) length.put(length.position(), val); + return val; + } + + private static final int CLEAR_CHUNK_BYTES = 64 * 1024; + @Override public void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, ByteBuffer data) { + final int glId = getBoundBuffer(target); + if (glId == 0 || size <= 0) return; + final long handle = resourceManager.getBufferHandle(glId); + if (handle == 0 || frameManager.getCommandBuffer() == 0) return; + + final int elemBytes = Math.max(1, PixelOps.glPixelSize(format, type)); + final int chunkBytes = (int) Math.min(size, CLEAR_CHUNK_BYTES); + final int alignedChunk = (chunkBytes / elemBytes) * elemBytes; + if (alignedChunk == 0) return; + resourceManager.markBufferContentsDefined(glId); + final ByteBuffer chunk = MemoryUtil.memAlloc(alignedChunk); + try { + for (int i = 0; i < alignedChunk; i++) { + final byte v = (data != null && (i % elemBytes) < data.remaining()) + ? data.get(data.position() + (i % elemBytes)) : 0; + chunk.put(i, v); + } + chunk.position(0).limit(alignedChunk); + long remaining = size; + long writeOffset = offset; + final boolean defer = s().deferUploads && target != GL43.GL_SHADER_STORAGE_BUFFER; + while (remaining > 0) { + final int n = (int) Math.min(remaining, alignedChunk); + chunk.position(0).limit(n); + if (defer) { + enqueuePreCopied(chunk, handle, writeOffset, false); + } else { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), chunk, handle, writeOffset, false); + } + remaining -= n; + writeOffset += n; + } + } finally { + MemoryUtil.memFree(chunk); + } + } + + @Override public void clearTexImage(int texture, int level, int format, int type) { + final long texHandle = resourceManager.getTextureHandle(texture); + if (texHandle == 0 || frameManager.getCommandBuffer() == 0) return; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(texture); + if (meta == null || level >= meta.levels()) return; + final int mipW = Math.max(1, meta.width() >> level); + final int mipH = Math.max(1, meta.height() >> level); + final int mipD = Math.max(1, meta.depth() >> level); + final int bpp = PixelOps.sdlFormatTexelBytes(meta.sdlFormat()); + if (mipW <= 0 || mipH <= 0 || bpp <= 0) return; + + if (mipD > 1 && PixelOps.isSdlFormatUnsignedInteger(meta.sdlFormat()) + && image3DClear.clear(texture, mipW, mipH, mipD)) { + return; + } + + // Volume-sized staging, so it is only reached for 3D formats the compute clear cannot address. + final long totalBytes = (long) mipW * mipH * mipD * bpp; + if (totalBytes <= 0 || totalBytes > Integer.MAX_VALUE) return; + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return; + final ByteBuffer zeros = MemoryUtil.memCalloc((int) totalBytes); + try { + if (mipD > 1) { + resourceManager.uploadToTexture3D(cp, zeros, texHandle, 0, 0, 0, mipW, mipH, mipD, level); + } else { + resourceManager.uploadToTexture(cp, zeros, texHandle, 0, 0, mipW, mipH, level); + } + } finally { + MemoryUtil.memFree(zeros); + } + } + + @Override public void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) { + final ContextState cs = s(); + if (unit < 0 || unit >= ContextState.MAX_IMAGE_UNITS) return; + if (texture != 0) { + resourceManager.ensureTextureUsage(texture, imageUsageForAccess(access)); + } + cs.boundStorageTextureByUnit[unit] = texture; + cs.boundStorageTextureLevel[unit] = level; + cs.boundStorageTextureLayered[unit] = layered; + cs.boundStorageTextureLayer[unit] = layer; + cs.boundStorageTextureAccess[unit] = access; + cs.boundStorageTextureFormat[unit] = format; + } + + public static int imageUsageForAccess(int access) { + return access == GL15.GL_READ_ONLY ? SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ : SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE; + } + + @Override public void memoryBarrier(int barriers) { + // Graphics storage bindings are read-only on SDL_GPU; RW is compute-pass only + frameManager.endCopyPassIfActive(); + } + + @Override public void copyImageSubData(int srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, + int dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, + int srcWidth, int srcHeight, int srcDepth) { + final long srcTex = resourceManager.getTextureHandle(srcName); + final long dstTex = resourceManager.getTextureHandle(dstName); + if (srcTex == 0 || dstTex == 0) return; + final ContextState copySt = s(); + fboClearTracker.materializePendingClearForTexture(copySt, srcTex); + if (dstZ != 0 || !fboClearTracker.discardPendingClearIfFullyCovered(copySt, dstTex, dstX, dstY, dstLevel, srcWidth, srcHeight, resourceManager.getTextureMeta(dstName))) { + fboClearTracker.materializePendingClearForTexture(copySt, dstTex); + } + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return; + try (var stack = MemoryStack.stackPush()) { + final var src = SDL_GPUTextureLocation.calloc(stack) + .texture(srcTex).mip_level(srcLevel).x(srcX).y(srcY).z(srcZ); + final var dst = SDL_GPUTextureLocation.calloc(stack) + .texture(dstTex).mip_level(dstLevel).x(dstX).y(dstY).z(dstZ); + SDL_CopyGPUTextureToTexture(cp, src, dst, srcWidth, srcHeight, Math.max(1, srcDepth), false); + } + } + + @Override public void stencilFunc(int func, int ref, int mask) { + final ContextState cs = s(); + final int op = FormatMap.mapCompareOp(func); + final int cm = mask & 0xFF; + cs.stencilRef = ref; + if (op == cs.pipeline.stencilFrontCompareOp && op == cs.pipeline.stencilBackCompareOp && cm == cs.pipeline.stencilCompareMask) + return; + cs.pipeline.stencilFrontCompareOp = op; + cs.pipeline.stencilBackCompareOp = op; + cs.pipeline.stencilCompareMask = cm; + cs.pipeline.markOutputDirty(); + } + @Override public void stencilFuncSeparate(int face, int func, int ref, int mask) { + final ContextState cs = s(); + final int op = FormatMap.mapCompareOp(func); + final int cm = mask & 0xFF; + cs.stencilRef = ref; + final boolean front = (face == GL11.GL_FRONT || face == GL20.GL_FRONT_AND_BACK); + final boolean back = (face == GL11.GL_BACK || face == GL20.GL_FRONT_AND_BACK); + final int newFront = front ? op : cs.pipeline.stencilFrontCompareOp; + final int newBack = back ? op : cs.pipeline.stencilBackCompareOp; + if (newFront == cs.pipeline.stencilFrontCompareOp && newBack == cs.pipeline.stencilBackCompareOp && cm == cs.pipeline.stencilCompareMask) + return; + cs.pipeline.stencilFrontCompareOp = newFront; + cs.pipeline.stencilBackCompareOp = newBack; + cs.pipeline.stencilCompareMask = cm; + cs.pipeline.markOutputDirty(); + } + @Override public void stencilOp(int sfail, int dpfail, int dppass) { + final ContextState cs = s(); + final int sf = FormatMap.mapStencilOp(sfail); + final int df = FormatMap.mapStencilOp(dpfail); + final int pa = FormatMap.mapStencilOp(dppass); + if (sf == cs.pipeline.stencilFrontFailOp && df == cs.pipeline.stencilFrontDepthFailOp && pa == cs.pipeline.stencilFrontPassOp && sf == cs.pipeline.stencilBackFailOp && df == cs.pipeline.stencilBackDepthFailOp && pa == cs.pipeline.stencilBackPassOp) + return; + cs.pipeline.stencilFrontFailOp = sf; + cs.pipeline.stencilFrontDepthFailOp = df; + cs.pipeline.stencilFrontPassOp = pa; + cs.pipeline.stencilBackFailOp = sf; + cs.pipeline.stencilBackDepthFailOp = df; + cs.pipeline.stencilBackPassOp = pa; + cs.pipeline.markOutputDirty(); + } + @Override public void stencilOpSeparate(int face, int sfail, int dpfail, int dppass) { + final ContextState cs = s(); + final int sf = FormatMap.mapStencilOp(sfail); + final int df = FormatMap.mapStencilOp(dpfail); + final int pa = FormatMap.mapStencilOp(dppass); + final boolean front = (face == GL11.GL_FRONT || face == GL20.GL_FRONT_AND_BACK); + final boolean back = (face == GL11.GL_BACK || face == GL20.GL_FRONT_AND_BACK); + final int nFFail = front ? sf : cs.pipeline.stencilFrontFailOp; + final int nFDFail = front ? df : cs.pipeline.stencilFrontDepthFailOp; + final int nFPass = front ? pa : cs.pipeline.stencilFrontPassOp; + final int nBFail = back ? sf : cs.pipeline.stencilBackFailOp; + final int nBDFail = back ? df : cs.pipeline.stencilBackDepthFailOp; + final int nBPass = back ? pa : cs.pipeline.stencilBackPassOp; + if (nFFail == cs.pipeline.stencilFrontFailOp && nFDFail == cs.pipeline.stencilFrontDepthFailOp && nFPass == cs.pipeline.stencilFrontPassOp && nBFail == cs.pipeline.stencilBackFailOp && nBDFail == cs.pipeline.stencilBackDepthFailOp && nBPass == cs.pipeline.stencilBackPassOp) + return; + cs.pipeline.stencilFrontFailOp = nFFail; + cs.pipeline.stencilFrontDepthFailOp = nFDFail; + cs.pipeline.stencilFrontPassOp = nFPass; + cs.pipeline.stencilBackFailOp = nBFail; + cs.pipeline.stencilBackDepthFailOp = nBDFail; + cs.pipeline.stencilBackPassOp = nBPass; + cs.pipeline.markOutputDirty(); + } + @Override public void stencilMask(int mask) { + final ContextState cs = s(); + final int wm = mask & 0xFF; + if (wm == cs.pipeline.stencilWriteMask) return; + cs.pipeline.stencilWriteMask = wm; + cs.pipeline.markOutputDirty(); + } + @Override public void stencilMaskSeparate(int face, int mask) { + final ContextState cs = s(); + final int wm = mask & 0xFF; + if (wm == cs.pipeline.stencilWriteMask) return; + cs.pipeline.stencilWriteMask = wm; + cs.pipeline.markOutputDirty(); + } + + public long getFrameNumber() { + return frameManager.getFrameNumber(); + } + + private int voxLocStart = -1; + private int voxLocCount = -1; + + public boolean bindVoxelizationRegion(int ssboBinding, int vertexBufferGlId, long openPass, float x, float y, float z) { + if (ssboBinding < 0 || ssboBinding >= ContextState.MAX_INDEXED_BUFFERS || vertexBufferGlId == 0) return false; + final ContextState st = s(); + if (st.boundProgram == 0) return false; + bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, ssboBinding, vertexBufferGlId); + final int loc = shaderManager.getUniformLocation(st.boundProgram, "u_RegionOffset"); + if (loc >= 0) GLStateManager.glUniform3f(loc, x, y, z); + if (openPass != 0) voxelizationDispatcher.rebindVertexBuffer(st, openPass); + return true; + } + + /** Reflected at link time, so it names exactly the images the compute writes rather than everything bound. */ + public String[] getComputeWrittenImageNames(int programId) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(programId); + if (prog == null || !prog.linked || prog.computeBindingMap == null) return new String[0]; + final String[] names = prog.computeBindingMap.rwStorageTextureNames(); + return names == null ? new String[0] : names.clone(); + } + + public long beginVoxelizationBatch(int ssboBinding) { + if (ssboBinding < 0 || ssboBinding >= ContextState.MAX_INDEXED_BUFFERS) return 0; + final ContextState st = s(); + final int program = st.boundProgram; + if (program == 0 || st.boundSsboByIndex[ssboBinding] == 0) return 0; + voxLocStart = shaderManager.getUniformLocation(program, "_vg_startVertex"); + voxLocCount = shaderManager.getUniformLocation(program, "_vg_vertexCount"); + return voxelizationDispatcher.beginBatch(st); + } + + public void voxelizeRange(long pass, int vertexOffset, int vertexCount) { + voxelizationDispatcher.dispatchRange(pass, voxLocStart, voxLocCount, vertexOffset, vertexCount, s()); + } + + public void endVoxelizationBatch(long pass) { + voxelizationDispatcher.endBatch(pass); + } + + @Override + public void drawArraysInstanced(int mode, int first, int count, int primcount) { + if (!frameManager.isFrameActive()) return; + final ContextState st = s(); + drawDispatch.setPrimitiveTypeForDraw(st, FormatMap.mapPrimitiveType(mode)); + pipelineApplier.ensureRenderPass(st); + if (!frameManager.isRenderPassActive()) return; + if (!pipelineApplier.applyPipelineAndState(st)) return; + SDL_DrawGPUPrimitives(frameManager.getRenderPass(), count, primcount, first, 0); + } + + @Override + public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { + if (firsts == null || counts == null) return; + final int n = Math.min(firsts.remaining(), counts.remaining()); + for (int i = 0; i < n; i++) { + drawArrays(mode, firsts.get(firsts.position() + i), counts.get(counts.position() + i)); + } + } + + @Override + public void primitiveRestartIndex(int index) { + final ContextState cs = s(); + if (cs.primitiveRestartSentinel == index) return; + cs.primitiveRestartSentinel = index; + resourceManager.clearSplitCache(); + } + + @Override + public void pointParameterf(int pname, float param) {} + + @Override + public void pointParameteri(int pname, int param) {} + + @Override + public void getActiveAttrib(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + final List names = prog != null ? prog.getActiveAttribNames() : List.of(); + final String aname = (index >= 0 && index < names.size()) ? names.get(index) : ""; + if (size != null && size.remaining() > 0) size.put(0, 1); + if (type != null && type.remaining() > 0) type.put(0, prog != null ? prog.getAttribGlType(aname) : GL20.GL_FLOAT_VEC4); + writeUtf8(aname, length, name); + } + + @Override + public String getActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(program); + if (prog == null) { + if (sizeType != null && sizeType.remaining() >= 2) { + sizeType.put(0, 1); + sizeType.put(1, GL20.GL_FLOAT_VEC4); + } + return ""; + } + final var names = prog.getActiveAttribNames(); + final String aname = (index >= 0 && index < names.size()) ? names.get(index) : ""; + if (sizeType != null && sizeType.remaining() >= 2) { + sizeType.put(0, 1); + sizeType.put(1, prog.getAttribGlType(aname)); + } + if (aname.isEmpty()) return ""; + return maxLength > 0 && aname.length() > maxLength ? aname.substring(0, maxLength) : aname; + } + + private int boundRenderbufferId; + + @Override + public int genRenderbuffers() { + return resourceManager.genTexture(); + } + + @Override + public void deleteRenderbuffers(int renderbuffer) { + if (renderbuffer == boundRenderbufferId) boundRenderbufferId = 0; + deleteTextures(renderbuffer); + } + + @Override + public void bindRenderbuffer(int target, int renderbuffer) { + boundRenderbufferId = renderbuffer; + } + + @Override + public void renderbufferStorage(int target, int internalformat, int width, int height) { + if (boundRenderbufferId == 0) return; + resourceManager.deleteTexture(boundRenderbufferId); + resourceManager.createTexture(boundRenderbufferId, GL11.GL_TEXTURE_2D, internalformat, width, height, 1, 1); + } + + private boolean warnedMSAARenderbuffer = false; + + @Override + public void renderbufferStorageMultisample(int target, int samples, int internalformat, int width, int height) { + if (samples > 1 && !warnedMSAARenderbuffer) { + warnedMSAARenderbuffer = true; + LOG.warn("SDL backend: MSAA renderbuffer requested (samples={}) but unsupported; falling back to 1-sample.", samples); + } + renderbufferStorage(target, internalformat, width, height); + } + + @Override + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer) { + framebufferTexture2D(target, attachment, GL11.GL_TEXTURE_2D, renderbuffer, 0); + } + + @Override + public void clearBufferData(int target, int internalformat, int format, int type, ByteBuffer data) { + final int glId = getBoundBuffer(target); + if (glId == 0) return; + final long size = resourceManager.getBufferSize(glId); + if (size <= 0) return; + clearBufferSubData(target, internalformat, 0L, size, format, type, data); + } + + private final class DeferredCopyOp implements BiConsumer { + long readOffset, size, dstHandle, writeOffset, seq; + @Override + public void accept(PersistentMapping src, PersistentMapping dst) { + enqueueUpload(TransferThread.StagingReadUpload.acquire(src.staging, readOffset, size, dstHandle, writeOffset, seq, false)); + if (dst != null) PersistentBufferSync.mirrorPersistentCopy(src.staging, readOffset, dst.staging, writeOffset, size); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/AwareGLDebugShim.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/AwareGLDebugShim.java new file mode 100644 index 000000000..0216a65af --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/AwareGLDebugShim.java @@ -0,0 +1,37 @@ +package com.gtnewhorizons.angelica.sdlgpu.compat; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GLDebugMessageCallback; +import org.lwjgl.opengl.GLDebugMessageCallbackI; +import org.lwjgl.system.Callback; + +import java.io.PrintStream; + +/** Redirect targets for Lwjgl3ify-Aware callers - redirect to GLStateManager */ +public final class AwareGLDebugShim { + + private static final Logger LOG = LogManager.getLogger("SDLGPU"); + + private AwareGLDebugShim() {} + + public static void glDebugMessageCallback(GLDebugMessageCallbackI callback, long userParam) { + GLStateManager.registerDebugMessageListener(callback == null ? null : callback::invoke, userParam); + } + + public static Callback setupDebugMessageCallback() { + return setupDebugMessageCallback(System.err); + } + + public static Callback setupDebugMessageCallback(PrintStream stream) { + if (!BackendManager.RENDER_BACKEND.supportsDebugOutput()) { + LOG.info("GLUtil.setupDebugMessageCallback ignored: {} has no driver message stream. Run with -Dorg.lwjgl.util.Debug=true to enable it.", BackendManager.RENDER_BACKEND.getName()); + return null; + } + final GLDebugMessageCallback proc = GLDebugMessageCallback.create((source, type, id, severity, length, message, userParam) -> stream.println("[Angelica] GL debug message: " + GLDebugMessageCallback.getMessage(length, message))); + GLStateManager.registerDebugMessageListener(proc::invoke, 0L); + return proc; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShim.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShim.java new file mode 100644 index 000000000..ab375dafa --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShim.java @@ -0,0 +1,45 @@ +package com.gtnewhorizons.angelica.sdlgpu.compat; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.BufferUtils; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GLCapabilities; +import org.lwjgl.system.FunctionProvider; + +import java.lang.reflect.Constructor; +import java.util.Set; +import java.util.function.IntFunction; + +/** {@link GLCapabilities} shim for Lwjgl3ify-Aware mods */ +public final class Lwjgl3GLCapabilitiesShim { + + private static final Logger LOG = LogManager.getLogger("SDLGPU"); + + private static final long SENTINEL_ADDRESS = 0xDEAD_0000_0000_0001L; + + private Lwjgl3GLCapabilitiesShim() {} + + public static void installOnCurrentThread(Set advertised) { + GL.setCapabilities(create(advertised)); + LOG.info("Installed fabricated LWJGL3 GLCapabilities on {} ({} capability names advertised)", Thread.currentThread().getName(), advertised.size()); + } + + public static void clearOnCurrentThread() { + GL.setCapabilities(null); + LOG.info("Cleared fabricated LWJGL3 GLCapabilities on {}", Thread.currentThread().getName()); + } + + public static GLCapabilities create(Set advertised) { + final FunctionProvider provider = name -> SENTINEL_ADDRESS; + final IntFunction bufferFactory = BufferUtils::createPointerBuffer; + try { + final Constructor ctor = GLCapabilities.class.getDeclaredConstructor(FunctionProvider.class, Set.class, boolean.class, IntFunction.class); + ctor.setAccessible(true); + return ctor.newInstance(provider, advertised, true, bufferFactory); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("GLCapabilities(FunctionProvider, Set, boolean, IntFunction) is gone", e); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinder.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinder.java new file mode 100644 index 000000000..e558e1a3b --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinder.java @@ -0,0 +1,427 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.Hashing; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerBinder; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.UniformStaging; +import org.lwjgl.PointerBuffer; +import org.lwjgl.sdl.SDL_GPUStorageBufferReadWriteBinding; +import org.lwjgl.sdl.SDL_GPUStorageTextureReadWriteBinding; +import org.lwjgl.sdl.SDL_GPUTextureSamplerBinding; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.system.MemoryStack; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class ComputeBinder implements ComputeDispatchSink { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final Tracy.ZoneId Z_SDL_COMPUTE_PASS = Tracy.zoneId("sdlComputePass", Tracy.COLOR_TERRAIN); + private final IntOpenHashSet loggedRoWithoutReadUsage = new IntOpenHashSet(); + private final LongOpenHashSet loggedMissingBindings = new LongOpenHashSet(); + + private void warnRoWithoutReadUsage(ContextState st, int glId, int unit, int usage) { + if (!loggedRoWithoutReadUsage.add(glId)) return; + LOG.warn("[ComputeBinder] program {} binds texture {} at image unit {} as a readonly storage image, but its usage 0x{} lacks COMPUTE_STORAGE_READ; skipping the dispatch", st.boundProgram, glId, unit, Integer.toHexString(usage)); + } + + private void warnMissingBinding(ContextState st, int kindId, String kind, int slotOrUnit, boolean dropped) { + final long key = ((long) st.boundProgram << 32) | ((long) kindId << 9) | ((long) (dropped ? 1 : 0) << 8) | (slotOrUnit & 0xFFL); + if (!loggedMissingBindings.add(key)) return; + LOG.warn("[ComputeBinder] program " + st.boundProgram + " has nothing bound at " + kind + " " + slotOrUnit + (dropped ? "; skipping the dispatch" : "; substituting a zeroed stand-in"), new Throwable("binding site")); + } + + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + private final SamplerBinder samplerBinder; + private boolean droppedDispatchWarned; + + public ComputeBinder(FrameManager frameManager, ResourceManager resourceManager, ShaderManager shaderManager, SamplerBinder samplerBinder) { + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + this.samplerBinder = samplerBinder; + } + + public void executeComputeDispatch(ContextState st, int gx, int gy, int gz, long indirectHandle, boolean indirect) { + executeComputeDispatch(st, gx, gy, gz, indirectHandle, indirect, 0); + } + + public void executeComputeDispatch(ContextState st, int gx, int gy, int gz, long indirectHandle, boolean indirect, int indirectOffset) { + Tracy.beginZone(Z_SDL_COMPUTE_PASS); + try { + if (st.computeBatchRequested) { + executeInBatchScope(st, gx, gy, gz, indirectHandle, indirect, indirectOffset); + return; + } + final long pass = beginBatchedComputeDispatch(st, true); + if (pass == 0) return; + if (indirect) SDL_DispatchGPUComputeIndirect(pass, indirectHandle, indirectOffset); + else SDL_DispatchGPUCompute(pass, gx, gy, gz); + SDL_EndGPUComputePass(pass); + frameManager.noteComputePassEnded(); + } finally { + Tracy.endZone(); + } + } + + private void executeInBatchScope(ContextState st, int gx, int gy, int gz, long indirectHandle, boolean indirect, int indirectOffset) { + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (st.computeBatchPass != 0 && canJoinBatch(st, prog)) { + frameManager.noteComputeBatchJoin(); + final long pass = st.computeBatchPass; + final ShaderManager.ComputeBindingMap map = prog.computeBindingMap; + try (MemoryStack stack = MemoryStack.stackPush()) { + final boolean ok = bindComputeSamplers(st, prog, pass, map.samplerGlSlots(), map.samplerNames(), stack) + && bindRoStorageTextures(st, prog, pass, map, stack) + && bindRoStorageBuffers(st, pass, map.roSsboGlSlots(), stack); + if (!ok) return; + } + pushComputeUboData(st, frameManager.getCommandBuffer(), prog, map.uboGlSlots()); + if (indirect) SDL_DispatchGPUComputeIndirect(pass, indirectHandle, indirectOffset); + else SDL_DispatchGPUCompute(pass, gx, gy, gz); + return; + } + + endBatchPassIfOpen(st); + final long pass = beginBatchedComputeDispatch(st, true); + if (pass == 0) return; + st.computeBatchPass = pass; + st.computeBatchProgram = st.boundProgram; + snapshotRwBindings(st, prog); + if (indirect) SDL_DispatchGPUComputeIndirect(pass, indirectHandle, indirectOffset); + else SDL_DispatchGPUCompute(pass, gx, gy, gz); + } + + public void endBatchPassIfOpen(ContextState st) { + if (st.computeBatchPass != 0) { + SDL_EndGPUComputePass(st.computeBatchPass); + frameManager.noteComputePassEnded(); + st.computeBatchPass = 0; + st.computeBatchProgram = 0; + st.computeBatchRwBufCount = -1; + st.computeBatchRwTexCount = -1; + } + } + + private void snapshotRwBindings(ContextState st, ShaderManager.ProgramObject prog) { + final ShaderManager.ComputeBindingMap map = prog.computeBindingMap; + final int[] bufSlots = map.rwSsboGlSlots(); + for (int i = 0; i < bufSlots.length; i++) { + st.computeBatchRwBufs[i] = resolveStorageBufHandle(st, bufSlots[i]); + } + st.computeBatchRwBufCount = bufSlots.length; + final int[] texSlots = map.rwStorageTextureGlSlots(); + for (int i = 0; i < texSlots.length; i++) { + final int unit = resolveUnit(prog.imageTextureUnits, map.rwStorageTextureNames(), i, texSlots[i]); + final long real = resolveStorageTexHandle(st, unit); + st.computeBatchRwTexs[i] = real != 0 ? real : standInStorageTex(st, map, i, unit, true); + st.computeBatchRwTexLevels[i] = real != 0 ? st.boundStorageTextureLevel[unit] : 0; + } + st.computeBatchRwTexCount = texSlots.length; + } + + private boolean canJoinBatch(ContextState st, ShaderManager.ProgramObject prog) { + if (prog == null || !prog.linked || prog.sdlComputePipeline == 0) return false; + if (st.boundProgram != st.computeBatchProgram) return false; + final ShaderManager.ComputeBindingMap map = prog.computeBindingMap; + final int[] bufSlots = map.rwSsboGlSlots(); + if (st.computeBatchRwBufCount != bufSlots.length) return false; + for (int i = 0; i < bufSlots.length; i++) { + if (resolveStorageBufHandle(st, bufSlots[i]) != st.computeBatchRwBufs[i]) return false; + } + final int[] texSlots = map.rwStorageTextureGlSlots(); + if (st.computeBatchRwTexCount != texSlots.length) return false; + for (int i = 0; i < texSlots.length; i++) { + final int unit = resolveUnit(prog.imageTextureUnits, map.rwStorageTextureNames(), i, texSlots[i]); + final long real = resolveStorageTexHandle(st, unit); + if ((real != 0 ? real : standInStorageTex(st, map, i, unit, true)) != st.computeBatchRwTexs[i]) return false; + if ((real != 0 ? st.boundStorageTextureLevel[unit] : 0) != st.computeBatchRwTexLevels[i]) return false; + } + return true; + } + + @Override + public long beginBatchedComputeDispatch(ContextState st, boolean cycleRwBuffers) { + final int programId = st.boundProgram; + if (programId == 0) return 0; + final ShaderManager.ProgramObject prog = shaderManager.getProgram(programId); + if (prog == null || !prog.linked || prog.sdlComputePipeline == 0) return 0; + + frameManager.endRenderPassIfActive(); + frameManager.endCopyPassIfActive(); + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) { + FrameManager.warnDroppedOutsideFrame(droppedDispatchWarned, "compute dispatch"); + droppedDispatchWarned = true; + return 0; + } + + final ShaderManager.ComputeBindingMap map = prog.computeBindingMap; + final int[] samplerSlots = map.samplerGlSlots(); + final int[] rwTexSlots = map.rwStorageTextureGlSlots(); + final int[] roBufSlots = map.roSsboGlSlots(); + final int[] rwBufSlots = map.rwSsboGlSlots(); + final int[] uboSlots = map.uboGlSlots(); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final SDL_GPUStorageTextureReadWriteBinding.Buffer rwTex; + if (rwTexSlots.length == 0) { + rwTex = null; + } else { + rwTex = buildRwTextureBindings(st, prog, map, stack); + if (rwTex == null) return 0; + } + final SDL_GPUStorageBufferReadWriteBinding.Buffer rwBuf; + if (rwBufSlots.length == 0) { + rwBuf = null; + } else { + rwBuf = buildRwBufferBindings(st, rwBufSlots, stack, cycleRwBuffers); + if (rwBuf == null) return 0; + } + + final long pass = SDL_BeginGPUComputePass(cb, rwTex, rwBuf); + if (pass == 0) return 0; + frameManager.noteComputePassBegun(); + + final boolean ok = bindComputeSamplers(st, prog, pass, samplerSlots, map.samplerNames(), stack) + && bindRoStorageTextures(st, prog, pass, map, stack) + && bindRoStorageBuffers(st, pass, roBufSlots, stack); + if (!ok) { + SDL_EndGPUComputePass(pass); + frameManager.noteComputePassEnded(); + return 0; + } + pushComputeUboData(st, cb, prog, uboSlots); + + SDL_BindGPUComputePipeline(pass, prog.sdlComputePipeline); + return pass; + } + } + + @Override + public void dispatchInBatch(long pass, int gx, int gy, int gz) { + if (pass == 0) return; + SDL_DispatchGPUCompute(pass, gx, gy, gz); + } + + @Override + public void rebindRoStorageBuffers(ContextState st, long pass) { + if (pass == 0) return; + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (prog == null || !prog.linked) return; + try (MemoryStack stack = MemoryStack.stackPush()) { + bindRoStorageBuffers(st, pass, prog.computeBindingMap.roSsboGlSlots(), stack); + } + } + + @Override + public void endBatchedComputeDispatch(long pass) { + if (pass == 0) return; + SDL_EndGPUComputePass(pass); + frameManager.noteComputePassEnded(); + } + + @Override + public void pushPendingComputeUniforms(ContextState st) { + final int programId = st.boundProgram; + if (programId == 0) return; + final ShaderManager.ProgramObject prog = shaderManager.getProgram(programId); + if (prog == null || !prog.linked) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + final int[] uboSlots = prog.computeBindingMap.uboGlSlots(); + if (uboSlots.length == 0) return; + pushComputeUboData(st, cb, prog, uboSlots); + } + + private long resolveStorageTexHandle(ContextState st, int unit) { + final int glId = st.boundStorageTextureByUnit[unit]; + return glId != 0 ? resourceManager.getTextureHandle(glId) : 0; + } + + private long standInStorageTex(ContextState st, ShaderManager.ComputeBindingMap map, int i, int unit, boolean readWrite) { + final int[] formats = readWrite ? map.rwStorageTextureFormats() : map.roStorageTextureFormats(); + final int[] targets = readWrite ? map.rwStorageTextureTargets() : map.roStorageTextureTargets(); + if (i >= formats.length || i >= targets.length) return 0; + + final int glFormat = formats[i] != 0 ? formats[i] : st.boundStorageTextureFormat[unit]; + if (glFormat == 0) return 0; + return resourceManager.getOrCreateComputeStandInTexture(glFormat, targets[i], readWrite); + } + + private static int resolveUnit(Object2IntOpenHashMap unitsByName, String[] names, int i, int fallback) { + if (names != null && i < names.length) { + final String name = names[i]; + if (name != null && unitsByName.containsKey(name)) return unitsByName.getInt(name); + } + return fallback; + } + + private long resolveStorageBufHandle(ContextState st, int slot) { + final int glId = st.boundSsboByIndex[slot]; + return glId != 0 ? resourceManager.getBufferHandle(glId) : 0; + } + + private SDL_GPUStorageTextureReadWriteBinding.Buffer buildRwTextureBindings(ContextState st, ShaderManager.ProgramObject prog, ShaderManager.ComputeBindingMap map, MemoryStack stack) { + final int[] units = map.rwStorageTextureGlSlots(); + final SDL_GPUStorageTextureReadWriteBinding.Buffer buf = SDL_GPUStorageTextureReadWriteBinding.calloc(units.length, stack); + for (int i = 0; i < units.length; i++) { + final int unit = resolveUnit(prog.imageTextureUnits, map.rwStorageTextureNames(), i, units[i]); + long handle = resolveStorageTexHandle(st, unit); + int level = st.boundStorageTextureLevel[unit]; + if (handle == 0) { + handle = standInStorageTex(st, map, i, unit, true); + level = 0; + if (handle == 0) { + warnMissingBinding(st, 0, "RW storage image unit", unit, true); + return null; + } + warnMissingBinding(st, 0, "RW storage image unit", unit, false); + } + buf.get(i).texture(handle).mip_level(level).layer(0).cycle(false); + } + buf.position(0); + return buf; + } + + private SDL_GPUStorageBufferReadWriteBinding.Buffer buildRwBufferBindings(ContextState st, int[] slots, MemoryStack stack, boolean cycle) { + final SDL_GPUStorageBufferReadWriteBinding.Buffer buf = SDL_GPUStorageBufferReadWriteBinding.calloc(slots.length, stack); + for (int i = 0; i < slots.length; i++) { + final long handle = resolveStorageBufHandle(st, slots[i]); + + if (handle == 0) { warnMissingBinding(st, 1, "RW storage buffer slot", slots[i], true); return null; } + buf.get(i).buffer(handle).cycle(cycle); + } + buf.position(0); + return buf; + } + + private boolean bindComputeSamplers(ContextState st, ShaderManager.ProgramObject prog, long pass, int[] units, String[] names, MemoryStack stack) { + if (units.length == 0) return true; + final SDL_GPUTextureSamplerBinding.Buffer buf = SDL_GPUTextureSamplerBinding.calloc(units.length, stack); + for (int i = 0; i < units.length; i++) { + final int unit = resolveUnit(prog.samplerTextureUnits, names, i, units[i]); + final int texGlId = st.boundTextures[unit]; + long texHandle = texGlId != 0 ? resourceManager.getTextureHandle(texGlId) : 0; + if (texHandle == 0) { + texHandle = resourceManager.getOrCreateFallbackTexture(); + if (texHandle == 0) { warnMissingBinding(st, 2, "sampler texture unit", unit, true); return false; } + warnMissingBinding(st, 2, "sampler texture unit", unit, false); + } + long sampHandle = samplerBinder.getSamplerForUnit(st, unit, texGlId); + if (sampHandle == 0) { + sampHandle = resourceManager.getOrCreateDefaultSampler(); + if (sampHandle == 0) { warnMissingBinding(st, 3, "sampler unit", unit, true); return false; } + warnMissingBinding(st, 3, "sampler unit", unit, false); + } + buf.get(i).texture(texHandle).sampler(sampHandle); + } + buf.position(0); + SDL_BindGPUComputeSamplers(pass, 0, buf); + return true; + } + + private boolean bindRoStorageTextures(ContextState st, ShaderManager.ProgramObject prog, long pass, ShaderManager.ComputeBindingMap map, MemoryStack stack) { + final int[] units = map.roStorageTextureGlSlots(); + if (units.length == 0) return true; + final PointerBuffer ptrs = stack.mallocPointer(units.length); + for (int i = 0; i < units.length; i++) { + final int unit = resolveUnit(prog.imageTextureUnits, map.roStorageTextureNames(), i, units[i]); + long handle = resolveStorageTexHandle(st, unit); + if (handle == 0) { + handle = standInStorageTex(st, map, i, unit, false); + if (handle == 0) { warnMissingBinding(st, 4, "RO storage image unit", unit, true); return false; } + warnMissingBinding(st, 4, "RO storage image unit", unit, false); + ptrs.put(i, handle); + continue; + } + final int glId = st.boundStorageTextureByUnit[unit]; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + if (meta != null && (meta.usage() & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ) == 0) { + warnRoWithoutReadUsage(st, glId, unit, meta.usage()); + return false; + } + ptrs.put(i, handle); + } + SDL_BindGPUComputeStorageTextures(pass, 0, ptrs); + return true; + } + + private boolean bindRoStorageBuffers(ContextState st, long pass, int[] slots, MemoryStack stack) { + if (slots.length == 0) return true; + final PointerBuffer ptrs = stack.mallocPointer(slots.length); + for (int i = 0; i < slots.length; i++) { + long handle = resolveStorageBufHandle(st, slots[i]); + if (handle == 0) { + handle = resourceManager.getOrCreateFallbackStorageBuffer(); + if (handle == 0) { warnMissingBinding(st, 5, "RO storage buffer slot", slots[i], true); return false; } + warnMissingBinding(st, 5, "RO storage buffer slot", slots[i], false); + } + ptrs.put(i, handle); + } + SDL_BindGPUComputeStorageBuffers(pass, 0, ptrs); + return true; + } + + private void pushComputeUboData(ContextState st, long cb, ShaderManager.ProgramObject prog, int[] uboSlots) { + if (prog.lastComputeUboHash == null || prog.lastComputeUboHash.length != uboSlots.length) { + prog.lastComputeUboHash = new long[uboSlots.length]; + prog.lastComputeCb = 0; + prog.lastComputeFrame = 0; + } + final long curFrame = frameManager.getFrameNumber(); + final boolean cacheValid = cb == prog.lastComputeCb && curFrame == prog.lastComputeFrame; + final long[] cache = prog.lastComputeUboHash; + if (!cacheValid) { + for (int i = 0; i < cache.length; i++) cache[i] = 0L; + prog.lastComputeCb = cb; + prog.lastComputeFrame = curFrame; + } + final ShaderManager.ComputeBindingMap map = prog.computeBindingMap; + final boolean[] isDefault = map.uboIsDefaultBlock(); + final int[] declaredSizes = map.uboSizes(); + final UniformStaging us = st.uniformStaging(prog); + for (int i = 0; i < uboSlots.length; i++) { + final ByteBuffer view; + if (i < isDefault.length && isDefault[i]) { + if (us.fsUniformBuf == null || prog.fragmentUboSize <= 0) continue; + view = us.fsUniformBuf; + view.position(0).limit(prog.fragmentUboSize); + } else { + final int slot = uboSlots[i]; + final int bufGlId = st.boundUboByIndex[slot]; + if (bufGlId == 0) continue; + final ByteBuffer shadow = resourceManager.getUboShadow(bufGlId); + if (shadow == null) continue; + final int offset = st.uboRangeOffset[slot]; + if (offset < 0 || offset >= shadow.capacity()) continue; + int size = (i < declaredSizes.length && declaredSizes[i] > 0) ? declaredSizes[i] : shadow.capacity() - offset; + final int rangeSize = st.uboRangeSize[slot]; + if (rangeSize > 0) size = Math.min(size, rangeSize); + size = Math.min(size, shadow.capacity() - offset); + if (size <= 0) continue; + view = frameManager.getUboPushView(bufGlId, shadow); + view.position(offset).limit(offset + size); + } + final int pos = view.position(); + final int len = view.remaining(); + final long hash = Hashing.hashBytes(view, pos, len); + if (cache[i] == hash && hash != 0L) { + continue; + } + SDL_PushGPUComputeUniformData(cb, i, view); + cache[i] = hash; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeDispatchSink.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeDispatchSink.java new file mode 100644 index 000000000..41a231c99 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeDispatchSink.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; + +public interface ComputeDispatchSink { + default long beginBatchedComputeDispatch(ContextState st) { + return beginBatchedComputeDispatch(st, true); + } + + long beginBatchedComputeDispatch(ContextState st, boolean cycleRwBuffers); + + void dispatchInBatch(long pass, int gx, int gy, int gz); + + void rebindRoStorageBuffers(ContextState st, long pass); + + void endBatchedComputeDispatch(long pass); + + void pushPendingComputeUniforms(ContextState st); +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcher.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcher.java new file mode 100644 index 000000000..0f9c20267 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcher.java @@ -0,0 +1,38 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; + +public final class VoxelizationDispatcher { + private static final int WORKGROUP_SIZE = 64; + + private final ComputeDispatchSink computeBinder; + + public VoxelizationDispatcher(ComputeDispatchSink computeBinder) { + this.computeBinder = computeBinder; + } + + public long beginBatch(ContextState st) { + return computeBinder.beginBatchedComputeDispatch(st, false); + } + + public void rebindVertexBuffer(ContextState st, long pass) { + computeBinder.rebindRoStorageBuffers(st, pass); + } + + public void dispatchRange(long pass, int locStart, int locCount, int vertexOffset, int vertexCount, ContextState st) { + if (pass == 0 || vertexCount <= 0) return; + if (locStart >= 0) GLStateManager.glUniform1i(locStart, vertexOffset); + if (locCount >= 0) GLStateManager.glUniform1i(locCount, vertexCount); + computeBinder.pushPendingComputeUniforms(st); + final int groups = (vertexCount + WORKGROUP_SIZE - 1) / WORKGROUP_SIZE; + computeBinder.dispatchInBatch(pass, groups, 1, 1); + } + + public void endBatch(long pass) { + if (pass == 0) return; + computeBinder.endBatchedComputeDispatch(pass); + } + + public static int workgroupSize() { return WORKGROUP_SIZE; } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java new file mode 100644 index 000000000..16c5cf0c4 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java @@ -0,0 +1,233 @@ +package com.gtnewhorizons.angelica.sdlgpu.device; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; +import com.gtnewhorizons.angelica.sdlgpu.util.DebugMessageRelay; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDLLog; +import org.lwjgl.sdl.SDLProperties; +import org.lwjgl.sdl.SDLStdinc; +import org.lwjgl.sdl.SDL_DisplayMode; +import org.lwjgl.sdl.SDL_LogOutputFunction; +import org.lwjgl.sdl.SDLVersion; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.Platform; +import org.lwjglx.opengl.Display; + +import java.nio.IntBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.sdl.SDLHints.SDL_HINT_GPU_DRIVER; +import static org.lwjgl.sdl.SDLHints.SDL_SetHint; +import static org.lwjgl.sdl.SDLVideo.*; +import static org.lwjgl.system.MemoryUtil.memUTF8; + +public final class Device { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + public static final int FRAMES_IN_FLIGHT = 3; + + private long device; + private int supportedShaderFormats; + private String driverName; + private String deviceName; + private String driverVersion; + private String driverInfo; + private int presentMode = SDL_GPU_PRESENTMODE_VSYNC; + private SDL_LogOutputFunction logCallback; // prevent GC + + // Default to vulkan for now until D3D is more tested + static String resolveDriverName(String userHint, boolean windows) { + return userHint.isEmpty() && windows ? "vulkan" : null; + } + + public void claimWindow(long window, boolean lwjglDebug) { + installLogCallback(); + + final int ver = SDLVersion.SDL_GetVersion(); + LOG.info("SDL runtime version {}.{}.{} (raw {})", SDLVersion.SDL_VERSIONNUM_MAJOR(ver), SDLVersion.SDL_VERSIONNUM_MINOR(ver), SDLVersion.SDL_VERSIONNUM_MICRO(ver), ver); + + final String driverHint = SystemProperties.SDL_GPU_DRIVER; + if (!driverHint.isEmpty()) { + SDL_SetHint(SDL_HINT_GPU_DRIVER, driverHint); + LOG.info("SDL GPU driver hint set to '{}'", driverHint); + } + + final int requestedFormats = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL; + + final boolean gpuDebug = lwjglDebug || SystemProperties.SDL_GPU_DEBUG; + final String forcedDriver = resolveDriverName(driverHint, Platform.get() == Platform.WINDOWS); + device = SDL_CreateGPUDevice(requestedFormats, gpuDebug, forcedDriver); + if (device == 0 && forcedDriver != null) { + LOG.warn("Failed to create a '{}' SDL GPU device ({}); falling back to SDL's default backend. Set -D{} to pin one.", forcedDriver, SDLError.SDL_GetError(), SystemProperties.KEY_SDL_GPU_DRIVER); + device = SDL_CreateGPUDevice(requestedFormats, gpuDebug, (CharSequence) null); + } + if (device == 0) { + throw new RuntimeException("Failed to create SDL GPU device: " + SDLError.SDL_GetError()); + } + + driverName = SDL_GetGPUDeviceDriver(device); + supportedShaderFormats = SDL_GetGPUShaderFormats(device); + + final int props = SDL_GetGPUDeviceProperties(device); + deviceName = SDLProperties.SDL_GetStringProperty(props, SDL_PROP_GPU_DEVICE_NAME_STRING, "Unknown GPU"); + driverVersion = SDLProperties.SDL_GetStringProperty(props, SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING, ""); + driverInfo = SDLProperties.SDL_GetStringProperty(props, SDL_PROP_GPU_DEVICE_DRIVER_INFO_STRING, ""); + + LOG.info("SDL GPU device created: gpu={}, driver={} {}, formats=0x{}, debug={}, forcedDriver={}", deviceName, driverName, driverVersion, Integer.toHexString(supportedShaderFormats), gpuDebug, forcedDriver); + + if ("metal".equalsIgnoreCase(driverName) && ver < SDLVersion.SDL_VERSIONNUM(3, 4, 6)) { + LOG.fatal("SDL GPU on Metal requires SDL 3.4.6 or newer; exiting"); + SDLGPUGate.markFatalInit(); + return; + } + + if (window == 0) { + throw new RuntimeException("SDL window not available for GPU device claim"); + } + + if (!SDL_ClaimWindowForGPUDevice(device, window)) { + throw new RuntimeException("Failed to claim window for SDL GPU device: " + SDLError.SDL_GetError()); + } + + final int n = FRAMES_IN_FLIGHT; + if (!SDL_SetGPUAllowedFramesInFlight(device, n)) { + LOG.warn("SDL_SetGPUAllowedFramesInFlight({}) failed: {}", n, SDLError.SDL_GetError()); + } else { + LOG.info("SDL frames-in-flight set to {}", n); + } + + logWindowDiagnostics(window); + LOG.info("SDL GPU device claimed window successfully"); + } + + private void logWindowDiagnostics(long window) { + final long flags = SDL_GetWindowFlags(window); + final boolean hasMetal = (flags & SDL_WINDOW_METAL) != 0; + final boolean hasVulkan = (flags & SDL_WINDOW_VULKAN) != 0; + final boolean hasOpenGL = (flags & SDL_WINDOW_OPENGL) != 0; + try (MemoryStack stack = MemoryStack.stackPush()) { + final IntBuffer pW = stack.ints(0); + final IntBuffer pH = stack.ints(0); + SDL_GetWindowSize(window, pW, pH); + final int wPoints = pW.get(0); + final int hPoints = pH.get(0); + pW.put(0, 0); + pH.put(0, 0); + SDL_GetWindowSizeInPixels(window, pW, pH); + final int wPix = pW.get(0); + final int hPix = pH.get(0); + final int swapFmt = SDL_GetGPUSwapchainTextureFormat(device, window); + LOG.info("SDL window flags=0x{} (metal={}, vulkan={}, opengl={}) size points={}x{} pixels={}x{} swapchainFormat=0x{}", + Long.toHexString(flags), hasMetal, hasVulkan, hasOpenGL, wPoints, hPoints, wPix, hPix, Integer.toHexString(swapFmt)); + } + } + + public int[] getMaxDesktopSizePixels() { + int maxW = 0; + int maxH = 0; + final IntBuffer displays = SDL_GetDisplays(); + if (displays == null) return new int[]{0, 0}; + try { + for (int i = 0; i < displays.remaining(); i++) { + final SDL_DisplayMode mode = SDL_GetDesktopDisplayMode(displays.get(displays.position() + i)); + if (mode == null) continue; + maxW = Math.max(maxW, Math.round(mode.w() * mode.pixel_density())); + maxH = Math.max(maxH, Math.round(mode.h() * mode.pixel_density())); + } + } finally { + SDLStdinc.nSDL_free(MemoryUtil.memAddress(displays)); + } + return new int[]{maxW, maxH}; + } + + public void shutdown() { + if (device != 0) { + final long window = Display.getWindow(); + if (window != 0) { + SDL_ReleaseWindowFromGPUDevice(device, window); + } + SDL_DestroyGPUDevice(device); + device = 0; + LOG.info("SDL GPU device destroyed"); + } + } + + public long getDevice() { + return device; + } + + public String getDriverName() { + return driverName; + } + + public String getDeviceName() { + return deviceName; + } + + public String getDriverVersion() { + return driverVersion; + } + + public String getDriverInfo() { + return driverInfo; + } + + public boolean supportsSpirv() { + return (supportedShaderFormats & SDL_GPU_SHADERFORMAT_SPIRV) != 0; + } + + public boolean supportsMsl() { + return (supportedShaderFormats & SDL_GPU_SHADERFORMAT_MSL) != 0; + } + + public boolean supportsDxil() { + return (supportedShaderFormats & SDL_GPU_SHADERFORMAT_DXIL) != 0; + } + + public boolean supportsDxbc() { + return (supportedShaderFormats & SDL_GPU_SHADERFORMAT_DXBC) != 0; + } + + public void setVSyncEnabled(boolean enabled) { + final long window = Display.getWindow(); + final int mode; + if (enabled) { + mode = SDL_GPU_PRESENTMODE_VSYNC; + } else if (SDL_WindowSupportsGPUPresentMode(device, window, SDL_GPU_PRESENTMODE_MAILBOX)) { + mode = SDL_GPU_PRESENTMODE_MAILBOX; + } else { + mode = SDL_GPU_PRESENTMODE_IMMEDIATE; + } + if (!SDL_SetGPUSwapchainParameters(device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, mode)) { + LOG.warn("Failed to set present mode {}: {} (keeping prior mode {})", mode, SDLError.SDL_GetError(), presentMode); + return; + } + presentMode = mode; + LOG.info("SDL present mode set to {}", mode); + } + + public int getSwapchainTextureFormat() { + final long window = Display.getWindow(); + return SDL_GetGPUSwapchainTextureFormat(device, window); + } + + private void installLogCallback() { + if (logCallback != null) return; + logCallback = SDL_LogOutputFunction.create((userdata, category, priority, message) -> { + final String msg = memUTF8(message); + switch (priority) { + case SDLLog.SDL_LOG_PRIORITY_ERROR, SDLLog.SDL_LOG_PRIORITY_CRITICAL -> LOG.error("[SDL] {}", msg); + case SDLLog.SDL_LOG_PRIORITY_WARN -> LOG.warn("[SDL] {}", msg); + case SDLLog.SDL_LOG_PRIORITY_INFO -> LOG.info("[SDL] {}", msg); + default -> LOG.debug("[SDL] {}", msg); + } + DebugMessageRelay.onSdlMessage(priority, message); + }); + SDLLog.SDL_SetLogOutputFunction(logCallback, 0); + SDLLog.SDL_SetLogPriorities(SDLLog.SDL_LOG_PRIORITY_VERBOSE); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/MemoryStackWrapper.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/MemoryStackWrapper.java new file mode 100644 index 000000000..370ee16d0 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/MemoryStackWrapper.java @@ -0,0 +1,39 @@ +package com.gtnewhorizons.angelica.sdlgpu.device; + +import com.mitchej123.lwjgl.MemoryStack; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; + +public class MemoryStackWrapper extends MemoryStack { + private final org.lwjgl.system.MemoryStack delegate; + + public MemoryStackWrapper(org.lwjgl.system.MemoryStack delegate) { + this.delegate = delegate; + } + + @Override public void close() { delegate.close(); } + @Override public long getPointer() { return delegate.getPointer(); } + @Override public void setPointer(long pointer) { delegate.setPointer((int) pointer); } + @Override public long getAddress() { return delegate.getAddress(); } + @Override public int getSize() { return delegate.getSize(); } + + @Override public ByteBuffer malloc(int size) { return delegate.malloc(size); } + @Override public ShortBuffer mallocShort(int count) { return delegate.mallocShort(count); } + @Override public IntBuffer mallocInt(int count) { return delegate.mallocInt(count); } + @Override public LongBuffer mallocLong(int count) { return delegate.mallocLong(count); } + @Override public FloatBuffer mallocFloat(int count) { return delegate.mallocFloat(count); } + + @Override public ByteBuffer calloc(int size) { return delegate.calloc(size); } + @Override public ShortBuffer callocShort(int count) { return delegate.callocShort(count); } + @Override public IntBuffer callocInt(int count) { return delegate.callocInt(count); } + @Override public LongBuffer callocLong(int count) { return delegate.callocLong(count); } + @Override public FloatBuffer callocFloat(int count) { return delegate.callocFloat(count); } + + @Override public long nmalloc(int size) { return delegate.nmalloc(size); } + @Override public long nmalloc(int alignment, int size) { return delegate.nmalloc(alignment, size); } + @Override public long ncalloc(int alignment, int count, int size) { return delegate.ncalloc(alignment, count, size); } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/SDLDrawable.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/SDLDrawable.java new file mode 100644 index 000000000..f5fc7fe93 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/SDLDrawable.java @@ -0,0 +1,63 @@ +package com.gtnewhorizons.angelica.sdlgpu.device; + +import org.lwjglx.opengl.Display; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; +import org.lwjglx.opengl.ContextGL; +import org.lwjglx.opengl.DrawableGL; + +/** + * Drawable for the SDL GPU backend. + */ +public final class SDLDrawable extends DrawableGL { + + public SDLDrawable() { + super((ContextGL) null); + } + + @Override + public void makeCurrent() { + } + + @Override + public void releaseContext() { + BackendManager.RENDER_BACKEND.onRenderThreadReleased(Thread.currentThread()); + } + + @Override + public boolean isCurrent() { + return SDLGPUGate.isActive(); + } + + @Override + public ContextGL createSharedContext() { + return null; + } + + @Override + public void destroy() { + BackendManager.RENDER_BACKEND.onRenderThreadReleased(Thread.currentThread()); + } + + @Override + public void checkGLError() { + } + + @Override + public void setSwapInterval(int swap_interval) { + } + + @Override + public void swapBuffers() { + BackendManager.RENDER_BACKEND.handleSwapBuffers(); + } + + @Override + public void initContext(float r, float g, float b) { + } + + @Override + public long getSdlWindowId() { + return Display.getWindow(); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextState.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextState.java new file mode 100644 index 000000000..6fc15e20a --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextState.java @@ -0,0 +1,357 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.UniformStaging; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.Long2FloatOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; +import org.lwjgl.sdl.SDL_FColor; +import org.lwjgl.sdl.SDL_GPUBufferBinding; +import org.lwjgl.sdl.SDL_GPUTextureSamplerBinding; +import org.lwjgl.sdl.SDL_GPUViewport; +import org.lwjgl.sdl.SDL_Rect; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; + +/** + * Per-thread (per-GL-context) client state for {@link SDLGPURenderBackend}. + */ +public final class ContextState { + + public final Thread owner = Thread.currentThread(); + + public static final int MAX_INDEXED_BUFFERS = 16; + public static final int MAX_IMAGE_UNITS = 8; + public static final int MAX_SAMPLERS = 16; + public static final int MAX_STORAGE_BUFFERS_PER_STAGE = 8; + public static final int MAX_VERTEX_ATTRIBS = 16; + public static final int MAX_COLOR_ATTACHMENTS = 8; + + public static final class PixelStoreState { + public int unpackAlignment = 4; + public int unpackRowLength = 0; + public int unpackSkipPixels = 0; + public int unpackSkipRows = 0; + public int packAlignment = 4; + public boolean isDefault() { + return unpackAlignment == 4 && unpackRowLength == 0 && unpackSkipPixels == 0 && unpackSkipRows == 0 && packAlignment == 4; + } + } + + public final PixelStoreState pixelStore = new PixelStoreState(); + + public static final class VAOState { + public final boolean[] attribEnabled = new boolean[MAX_VERTEX_ATTRIBS]; + public int attribEnabledMask; + public final int[] attribSize = new int[MAX_VERTEX_ATTRIBS]; + public final int[] attribType = new int[MAX_VERTEX_ATTRIBS]; + public final boolean[] attribNormalized = new boolean[MAX_VERTEX_ATTRIBS]; + public final boolean[] attribIsInteger = new boolean[MAX_VERTEX_ATTRIBS]; + public final int[] attribStride = new int[MAX_VERTEX_ATTRIBS]; + public final long[] attribOffset = new long[MAX_VERTEX_ATTRIBS]; + public final int[] attribVBO = new int[MAX_VERTEX_ATTRIBS]; + public final int[] attribRelativeOffset = new int[MAX_VERTEX_ATTRIBS]; + public final int[] attribBinding = new int[MAX_VERTEX_ATTRIBS]; + public final int[] bindingBuffer = new int[MAX_VERTEX_ATTRIBS]; + public final long[] bindingOffset = new long[MAX_VERTEX_ATTRIBS]; + public final int[] bindingStride = new int[MAX_VERTEX_ATTRIBS]; + public final int[] bindingDivisor = new int[MAX_VERTEX_ATTRIBS]; + public int elementBuffer; + public VAOState() { for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++) attribBinding[i] = i; } + } + + public float clearR, clearG, clearB, clearA; + public float viewportX, viewportY, viewportW, viewportH; + public float viewportDepthNear = 0.0f; + public float viewportDepthFar = 1.0f; + public int scissorX, scissorY, scissorW, scissorH; + public boolean scissorEnabled; + public int activeTextureUnit; + public int boundProgram; + public int autoPushedProgram; + + public final PipelineCache pipeline = new PipelineCache(); + + public int slotWrites; + public int slotWritesElided; + public int ssboBinds; + + public float blendColorR, blendColorG, blendColorB, blendColorA; + public int stencilRef; + public float depthClearValue = 1.0f; + public boolean primitiveRestartEnabled; + public int primitiveRestartSentinel; + + public boolean viewportDirty = true; + public boolean scissorDirty = true; + public boolean blendColorDirty = true; + public long lastBoundPipeline; + public long lastAppliedRenderPassGen; + + public int lastAppliedStencilRef = Integer.MIN_VALUE; + public long lastBoundEboHandle; + public int lastBoundEboIndexSize = -1; + public int lastBoundEboOffset; + public int samplerBindGen; + public int lastAppliedSamplerBindGen = -1; + public int lastAppliedSamplerProgram; + public long lastAppliedSamplerCb; + public int lastAppliedStorageTexBindGen = -1; + public int lastAppliedStorageTexProgram; + public long lastAppliedStorageTexCb; + public int ssboBindGen; + public int lastAppliedStorageBufBindGen = -1; + public int lastAppliedStorageBufProgram; + public long lastAppliedStorageBufCb; + public int pendingMutationGen; + public int lastFlushedSamplerBindGen = -1; + public int lastFlushedProgram = -1; + public int lastFlushedPendingMutationGen = -1; + public long lastPushedCbVs; + public long lastPushedCbFs; + public int lastPushedProgramVs; + public int lastPushedProgramFs; + public int uboRangeGen; + public int lastPushedUboGenVs = -1; + public int lastPushedUboGenFs = -1; + public ShaderManager.ProgramObject boundProgramObj; + + private final Reference2ObjectOpenHashMap uniformStagingByProgram = new Reference2ObjectOpenHashMap<>(); + private ShaderManager.ProgramObject stagingProg; + private UniformStaging currentUniformStaging; + + public UniformStaging uniformStaging(ShaderManager.ProgramObject prog) { + if (prog == stagingProg) return currentUniformStaging; + UniformStaging us = uniformStagingByProgram.get(prog); + if (us == null) { + us = new UniformStaging(); + us.allocate(prog); + uniformStagingByProgram.put(prog, us); + } + stagingProg = prog; + currentUniformStaging = us; + return us; + } + + public void releaseUniformStaging(ShaderManager.ProgramObject prog) { + final UniformStaging us = uniformStagingByProgram.remove(prog); + if (us != null) us.free(); + if (stagingProg == prog) { stagingProg = null; currentUniformStaging = null; } + } + + public static final class UniformBlockState { + private ByteBuffer buf; + public FloatBuffer fb; + public boolean dirty; + public int glId; + public int allocSize; + public int size; + public boolean flushedThisFrame; + + private long[] valueHash; + + public FloatBuffer staging(int sizeBytes) { + if (buf == null || buf.capacity() < sizeBytes) { + if (buf != null) MemoryUtil.memFree(buf); + buf = MemoryUtil.memCalloc(sizeBytes); + fb = buf.asFloatBuffer(); + valueHash = new long[(sizeBytes >> 2) + 1]; + } + return fb; + } + + public int hashSlot(int byteOffset) { + final long[] h = valueHash; + if (h == null) return -1; + final int i = byteOffset >> 2; + return (i >= 0 && i < h.length) ? i : -1; + } + + public long hash(int slot) { + return valueHash[slot]; + } + + public void setHash(int slot, long value) { + valueHash[slot] = value; + } + + public ByteBuffer bytes() { + return buf; + } + + public void free() { + if (buf != null) { + MemoryUtil.memFree(buf); + buf = null; + fb = null; + } + } + } + + public final UniformBlockState[] uniformBlocks = { new UniformBlockState(), new UniformBlockState() }; + + public boolean anyUniformBlockDirty() { + return uniformBlocks[0].dirty || uniformBlocks[1].dirty; + } + + public int boundArrayBuffer; + public int boundIndirectBuffer; + public int boundUniformBuffer; + public int boundCopyReadBuffer; + public int boundCopyWriteBuffer; + public int boundSSBO; + public int boundPixelUnpackBuffer; + public int boundPixelPackBuffer; + + public int getBoundBuffer(int target) { + return switch (target) { + case GL15.GL_ARRAY_BUFFER -> boundArrayBuffer; + case GL15.GL_ELEMENT_ARRAY_BUFFER -> currentVao.elementBuffer; + case GL31.GL_UNIFORM_BUFFER -> boundUniformBuffer; + case GL30.GL_PIXEL_UNPACK_BUFFER -> boundPixelUnpackBuffer; + case GL30.GL_PIXEL_PACK_BUFFER -> boundPixelPackBuffer; + case GL40.GL_DRAW_INDIRECT_BUFFER -> boundIndirectBuffer; + case GL31.GL_COPY_READ_BUFFER -> boundCopyReadBuffer; + case GL31.GL_COPY_WRITE_BUFFER -> boundCopyWriteBuffer; + case GL43.GL_SHADER_STORAGE_BUFFER -> boundSSBO; + default -> 0; + }; + } + public final int[] boundUboByIndex = new int[MAX_INDEXED_BUFFERS]; + public final int[] uboRangeOffset = new int[MAX_INDEXED_BUFFERS]; + public final int[] uboRangeSize = new int[MAX_INDEXED_BUFFERS]; + public final int[] boundSsboByIndex = new int[MAX_INDEXED_BUFFERS]; + public final int[] boundStorageTextureByUnit = new int[MAX_IMAGE_UNITS]; + public final int[] boundStorageTextureLevel = new int[MAX_IMAGE_UNITS]; + public final boolean[] boundStorageTextureLayered = new boolean[MAX_IMAGE_UNITS]; + public final int[] boundStorageTextureLayer = new int[MAX_IMAGE_UNITS]; + public final int[] boundStorageTextureAccess = new int[MAX_IMAGE_UNITS]; + public final int[] boundStorageTextureFormat = new int[MAX_IMAGE_UNITS]; + public final int[] boundTextures = new int[32]; + public final int[] boundSamplerObjects = new int[32]; + + public boolean computeBatchRequested; + public long computeBatchPass; + public int computeBatchProgram; + public int computeBatchRwBufCount = -1; + public int computeBatchRwTexCount = -1; + public final long[] computeBatchRwBufs = new long[MAX_INDEXED_BUFFERS]; + public final long[] computeBatchRwTexs = new long[MAX_IMAGE_UNITS]; + public final int[] computeBatchRwTexLevels = new int[MAX_IMAGE_UNITS]; + + public int mappedBufferGlId; + public ByteBuffer mappedStagingBuffer; + public long mappedOffset; + public long mappedLength; + public boolean mappedInvalidate; + public int mappedAccessFlags; + + public final SDL_GPUTextureSamplerBinding.Buffer fragSamplerBindings = SDL_GPUTextureSamplerBinding.calloc(MAX_SAMPLERS); + public final SDL_GPUTextureSamplerBinding.Buffer vertSamplerBindings = SDL_GPUTextureSamplerBinding.calloc(MAX_SAMPLERS); + public final long[] lastFragSamplerTex = new long[MAX_SAMPLERS]; + public final long[] lastFragSamplerSmp = new long[MAX_SAMPLERS]; + public final long[] lastVertSamplerTex = new long[MAX_SAMPLERS]; + public final long[] lastVertSamplerSmp = new long[MAX_SAMPLERS]; + public int lastFragSamplerProgram; + public int lastVertSamplerProgram; + + public final PointerBuffer fragStorageTexBindings = PointerBuffer.allocateDirect(MAX_IMAGE_UNITS); + public final PointerBuffer vertStorageTexBindings = PointerBuffer.allocateDirect(MAX_IMAGE_UNITS); + public final long[] lastFragStorageTex = new long[MAX_IMAGE_UNITS]; + public final long[] lastVertStorageTex = new long[MAX_IMAGE_UNITS]; + public int lastFragStorageTexProgram; + public int lastVertStorageTexProgram; + + public final PointerBuffer fragStorageBufBindings = PointerBuffer.allocateDirect(MAX_STORAGE_BUFFERS_PER_STAGE); + public final PointerBuffer vertStorageBufBindings = PointerBuffer.allocateDirect(MAX_STORAGE_BUFFERS_PER_STAGE); + public final long[] lastFragStorageBuf = new long[MAX_STORAGE_BUFFERS_PER_STAGE]; + public final long[] lastVertStorageBuf = new long[MAX_STORAGE_BUFFERS_PER_STAGE]; + public int lastFragStorageBufProgram; + public int lastVertStorageBufProgram; + + public boolean deferUploads; + public int drawsSincePersistentDrain; + + public boolean needsSeed = true; + public long frameHighestEnqueuedSeq; + + public int boundFboId; + public int boundReadFboId; + + public final LongOpenHashSet clearedTexturesThisFrame = new LongOpenHashSet(); + + public final LongOpenHashSet pendingColorTextures = new LongOpenHashSet(); + public final Long2ObjectOpenHashMap pendingColorValues = new Long2ObjectOpenHashMap<>(); + public final LongOpenHashSet pendingDepthTextures = new LongOpenHashSet(); + public final Long2FloatOpenHashMap pendingDepthValues = new Long2FloatOpenHashMap(); + public boolean pendingSwapchainClear; + public float pendingSwapchainR, pendingSwapchainG, pendingSwapchainB, pendingSwapchainA; + + public final LongArrayList samplerFlushColorHandles = new LongArrayList(); + public final IntArrayList samplerFlushColorGlIds = new IntArrayList(); + public final LongArrayList samplerFlushDepthHandles = new LongArrayList(); + public final IntArrayList samplerFlushDepthGlIds = new IntArrayList(); + + public boolean[] materializeFlushConsumed = new boolean[MAX_COLOR_ATTACHMENTS * 4]; + public final int[] materializeFlushBatchIdx = new int[MAX_COLOR_ATTACHMENTS]; + + public long vboBindingsAddr; + public SDL_GPUBufferBinding eboBinding; + public SDL_GPUViewport cachedViewport; + public SDL_Rect cachedScissor; + public SDL_FColor cachedBlendColor; + + public long attribStateGen = 1; + public long nextAttribStateGen = 1; + public void bumpAttribStateGen() { attribStateGen = ++nextAttribStateGen; } + public long lastAppliedVboBindGen; + public int lastAppliedVboBindProgram; + public long lastAppliedVboBindCb; + public int boundVAO; + public final VAOState defaultVaoState = new VAOState(); + public VAOState currentVao = defaultVaoState; + + public long fanIndexBuffer; + public int fanIndexBufferCapacity; + public int fanIndexBufferOffset; + + public int[] eboSplitFirsts = new int[16]; + public int[] eboSplitCounts = new int[16]; + + public void ensureEboSplitScratch(int min) { + if (eboSplitFirsts.length < min) { + final int n = Math.max(min, eboSplitFirsts.length * 2); + eboSplitFirsts = new int[n]; + eboSplitCounts = new int[n]; + } + } + + public int attribDefaultsDirtyMask; + public final float[] attribDefaults = new float[MAX_VERTEX_ATTRIBS * 4]; + public int attribDefaultsRingBase; + public int ringAdvancesThisFrame; + public int ringChunkBaseOffset; + public int ringChunkUsedBlocks; + public ByteBuffer ringChunkStaging; + + public ContextState() { + vboBindingsAddr = MemoryUtil.nmemCalloc(MAX_VERTEX_ATTRIBS, SDL_GPUBufferBinding.SIZEOF); + eboBinding = SDL_GPUBufferBinding.calloc(); + cachedViewport = SDL_GPUViewport.calloc(); + cachedScissor = SDL_Rect.calloc(); + cachedBlendColor = SDL_FColor.calloc(); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FenceTracker.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FenceTracker.java new file mode 100644 index 000000000..c9e42ee04 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FenceTracker.java @@ -0,0 +1,151 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL32; +import org.lwjgl.system.MemoryStack; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class FenceTracker { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final Tracy.ZoneId Z_SDL_FENCE_WAIT = Tracy.zoneId("sdlFenceWait", Tracy.COLOR_SWAP); + + private final Device device; + private final FrameManager frameManager; + + private long nextFenceId = 1; + private final Long2LongOpenHashMap fenceMap = new Long2LongOpenHashMap(); + private final LongArrayList pendingFenceSyncs = new LongArrayList(); + private final Long2IntOpenHashMap fenceRefcounts = new Long2IntOpenHashMap(); + + private Runnable unresolvedFenceFlush; + private int unresolvedFlushes; + private long unresolvedFlushSync; + + public FenceTracker(Device device, FrameManager frameManager) { + this.device = device; + this.frameManager = frameManager; + } + + public void setUnresolvedFenceFlush(Runnable flush) { + this.unresolvedFenceFlush = flush; + } + + public int getUnresolvedFlushes() { return unresolvedFlushes; } + + private long flushForUnresolved(long sync) { + if (unresolvedFenceFlush == null) return 0L; + if (unresolvedFlushSync == sync) return 0L; + unresolvedFlushSync = sync; + unresolvedFlushes++; + if ((unresolvedFlushes & (unresolvedFlushes - 1)) == 0) { + LOG.warn("clientWaitSync on an unsubmitted fence forced a mid-frame flush (#{}, thread={})", unresolvedFlushes, Thread.currentThread().getName()); + } + unresolvedFenceFlush.run(); + return fenceMap.get(sync); + } + + public long fenceSync() { + final long id = nextFenceId++; + fenceMap.put(id, 0L); + pendingFenceSyncs.add(id); + frameManager.frame().wantFenceOnNextSubmit = true; + return id; + } + + public void resolvePendingFences() { + unresolvedFlushSync = 0L; + if (pendingFenceSyncs.isEmpty()) return; + final long fence = frameManager.frame().lastAcquiredFence; + frameManager.frame().lastAcquiredFence = 0; + for (int i = 0; i < pendingFenceSyncs.size(); i++) { + final long id = pendingFenceSyncs.getLong(i); + if (fence != 0) { + fenceMap.put(id, fence); + fenceRefcounts.addTo(fence, 1); + } else { + fenceMap.remove(id); + } + } + pendingFenceSyncs.clear(); + } + + public int clientWaitSync(long sync, int flags, long timeout) { + if (!fenceMap.containsKey(sync)) return GL32.GL_ALREADY_SIGNALED; + long fence = fenceMap.get(sync); + if (fence == 0) { + if ((flags & GL32.GL_SYNC_FLUSH_COMMANDS_BIT) == 0) return GL32.GL_TIMEOUT_EXPIRED; + fence = flushForUnresolved(sync); + if (fence == 0) return GL32.GL_TIMEOUT_EXPIRED; + } + if (SDL_QueryGPUFence(device.getDevice(), fence)) return GL32.GL_ALREADY_SIGNALED; + if (timeout == 0) return GL32.GL_TIMEOUT_EXPIRED; + Tracy.beginZone(Z_SDL_FENCE_WAIT); + try (var stack = MemoryStack.stackPush()) { + final PointerBuffer fences = stack.mallocPointer(1).put(0, fence); + SDL_WaitForGPUFences(device.getDevice(), true, fences); + } finally { + Tracy.endZone(); + } + return GL32.GL_CONDITION_SATISFIED; + } + + public void deleteSync(long sync) { + final long fence = fenceMap.remove(sync); + if (fence == 0 || device.getDevice() == 0) return; + final int newCount = fenceRefcounts.addTo(fence, -1) - 1; + if (newCount <= 0) { + fenceRefcounts.remove(fence); + SDL_ReleaseGPUFence(device.getDevice(), fence); + } + } + + public void dispose() { + final long dev = device.getDevice(); + if (dev != 0) { + for (long fence : fenceRefcounts.keySet()) { + SDL_ReleaseGPUFence(dev, fence); + } + } + fenceRefcounts.clear(); + fenceMap.clear(); + pendingFenceSyncs.clear(); + } + + public boolean isFenceSignaled(long sync) { + if (!fenceMap.containsKey(sync)) return true; + final long fence = fenceMap.get(sync); + if (fence == 0) return false; + return SDL_QueryGPUFence(device.getDevice(), fence); + } + + public int getSyncStatus(long sync) { + return isFenceSignaled(sync) ? GL32.GL_SIGNALED : GL32.GL_UNSIGNALED; + } + + public void waitSync(long sync) { + if (!fenceMap.containsKey(sync)) return; + long fence = fenceMap.get(sync); + if (fence == 0) { + flushForUnresolved(sync); + return; + } + if (SDL_QueryGPUFence(device.getDevice(), fence)) return; + Tracy.beginZone(Z_SDL_FENCE_WAIT); + try (var stack = MemoryStack.stackPush()) { + final PointerBuffer fences = stack.mallocPointer(1).put(0, fence); + SDL_WaitForGPUFences(device.getDevice(), true, fences); + } finally { + Tracy.endZone(); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FrameManager.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FrameManager.java new file mode 100644 index 000000000..2771e3cd9 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/FrameManager.java @@ -0,0 +1,843 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import com.gtnewhorizons.angelica.sdlgpu.resource.UploadArena; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDL_FColor; +import org.lwjgl.sdl.SDL_GPUColorTargetInfo; +import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo; +import org.lwjglx.opengl.Display; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Arrays; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.*; + +/** + * Per-frame command buffer lifecycle: acquire, render pass, submit. Emulates OpenGL's per-context client state. + */ +public final class FrameManager { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final Tracy.ZoneId Z_SDL_FENCE_WAIT = Tracy.zoneId("sdlFenceWait", Tracy.COLOR_SWAP); + private static final Tracy.ZoneId Z_SDL_SUBMIT = Tracy.zoneId("sdlSubmit", Tracy.COLOR_SWAP); + private static final Tracy.ZoneId Z_SDL_ACQUIRE_WAIT = Tracy.zoneId("sdlAcquireWait", Tracy.COLOR_SWAP); + private static final Tracy.ZoneId Z_SDL_SWAPCHAIN_WAIT = Tracy.zoneId("sdlSwapchainWait", Tracy.COLOR_SWAP); + + private final Device device; + private ResourceManager resourceManager; + + public static final class FrameState { + public final Thread owner = Thread.currentThread(); + public long commandBuffer; + public long renderPass; + public long copyPass; + public boolean computePassOpen; + public long swapchainTexture; + public int swapchainWidth; + public int swapchainHeight; + public boolean frameActive; + public long currentColorTarget; + public long currentDepthTarget; + public long activeLayoutHash; + public long frameNumber; + public boolean clearedThisFrame; + public boolean swapchainUsedThisFrame; + public boolean swapchainAcquiredThisFrame; + public boolean swapchainUnavailable; + public boolean skipPresent; + public long renderPassGeneration; + + public boolean wantFenceOnNextSubmit; + public long lastAcquiredFence; + + public long lastPlottedRenderPassGen; + public int computePassesThisFrame; + public int submitsThisFrame; + public long uniformPushBytesThisFrame; + public int uniformPushesThisFrame; + public int uniformPushSkipsThisFrame; + public int externalUboPushesThisFrame; + public int externalUboPushSkipsThisFrame; + public int persistentDrainsThisFrame; + public final int[] uniformBlockFlushesThisFrame = new int[2]; + public final long[] uniformBlockBytesThisFrame = new long[2]; + public int perFrameBlockPassBreaksThisFrame; + public int batchBreakPipelineThisFrame; + public int batchBreakSamplerThisFrame; + public int stateAppliesThisFrame; + public long acquireWaitNanosThisFrame; + public int mipGensThisFrame; + public int blitsThisFrame; + public int presentSkipsThisFrame; + public int emptyFramesThisFrame; + public int droppedDrawsThisFrame; + public int computeBatchJoinsThisFrame; + public boolean drawableStarved; + public int clearPassesThisFrame; + public int swapchainPassesThisFrame; + public int fboPassesThisFrame; + public int arenaSubmitsThisFrame; + public int arenaOverflowFlushesThisFrame; + public int copyPassesThisFrame; + public int materializedClearPassesThisFrame; + public long lastEndFrameNanos; + + public long pendingUploadCommandBuffer; + public long pendingUploadBytes; + public int pendingUploadCommands; + + public long batchXfer; + public ByteBuffer batchMapped; + public int batchOffset; + + public long arenaXfer; + public ByteBuffer arenaMapped; + public long arenaCommandBuffer; + public long arenaCopyPass; + public final UploadArena arena = new UploadArena(); + + public final LongArrayList pendingTexHandles = new LongArrayList(); + public final IntArrayList pendingTexX = new IntArrayList(); + public final IntArrayList pendingTexY = new IntArrayList(); + public final IntArrayList pendingTexW = new IntArrayList(); + public final IntArrayList pendingTexH = new IntArrayList(); + public final IntArrayList pendingTexLevels = new IntArrayList(); + public final IntArrayList pendingTexOffsets = new IntArrayList(); + + public volatile boolean flushRequested; + public volatile boolean syncOnNextFlush; + public final IntOpenHashSet pendingMipGen = new IntOpenHashSet(); + + public final Int2ObjectOpenHashMap uboPushViews = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectOpenHashMap uboPushViewSource = new Int2ObjectOpenHashMap<>(); + } + + public ByteBuffer getUboPushView(int bufferGlId, ByteBuffer shadow) { + final FrameState f = frame(); + final ByteBuffer existing = f.uboPushViews.get(bufferGlId); + if (existing != null && f.uboPushViewSource.get(bufferGlId) == shadow) { + existing.position(0).limit(shadow.capacity()); + return existing; + } + final ByteBuffer view = shadow.duplicate(); + view.position(0).limit(shadow.capacity()); + f.uboPushViews.put(bufferGlId, view); + f.uboPushViewSource.put(bufferGlId, shadow); + return view; + } + + private volatile boolean globalSyncAtNextBeginFrame; + + private final CopyOnWriteArrayList registeredFrames = new CopyOnWriteArrayList<>(); + + private volatile FrameState soleFrame; + + private final ThreadLocal tlFrame = ThreadLocal.withInitial(() -> { + final FrameState f = new FrameState(); + registeredFrames.add(f); + refreshSoleFrame(); + return f; + }); + + private void refreshSoleFrame() { + soleFrame = registeredFrames.size() == 1 ? registeredFrames.get(0) : null; + } + + public FrameState frame() { + final FrameState f = soleFrame; + if (f != null && f.owner == Thread.currentThread()) return f; + return tlFrame.get(); + } + + public static final long SWAPCHAIN_LAYOUT_HASH = 0x5CA1AB1E5CA1AB1EL; + + public static final long MAX_PENDING_UPLOAD_BYTES = 16L * 1024L * 1024L; + public static final int MAX_PENDING_UPLOAD_COMMANDS = 256; + + private Runnable beforeEndCopyPass; + private Runnable beforePendingUploadSubmit; + + public FrameManager(Device device) { + this.device = device; + } + + public void setResourceManager(ResourceManager resourceManager) { + this.resourceManager = resourceManager; + } + + private static volatile boolean threadLogged; + + public void beginFrame() { + final FrameState f = frame(); + if (f.frameActive) { + LOG.warn("beginFrame() called while frame already active on thread {}", Thread.currentThread().getName()); + return; + } + if (!threadLogged) { + threadLogged = true; + LOG.info("First beginFrame() on thread={}; must match the SDL window-creating thread", Thread.currentThread().getName()); + } + + flushPendingUploadCommandBuffer(f); + if (globalSyncAtNextBeginFrame) { + globalSyncAtNextBeginFrame = false; + Tracy.beginZone(Z_SDL_FENCE_WAIT); + try { SDL_WaitForGPUIdle(device.getDevice()); } + finally { Tracy.endZone(); } + } + + if (f.drawableStarved) { + f.drawableStarved = false; + Tracy.beginZone(Z_SDL_SWAPCHAIN_WAIT); + try { SDL_WaitForGPUSwapchain(device.getDevice(), Display.getWindow()); } + finally { Tracy.endZone(); } + } + + f.commandBuffer = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (f.commandBuffer == 0) { + throw new RuntimeException("Failed to acquire GPU command buffer: " + SDLError.SDL_GetError()); + } + + f.swapchainTexture = 0; + f.swapchainWidth = 0; + f.swapchainHeight = 0; + f.swapchainAcquiredThisFrame = false; + f.swapchainUnavailable = false; + + f.frameActive = true; + f.renderPass = 0; + f.currentColorTarget = 0; + f.currentDepthTarget = 0; + f.frameNumber++; + f.clearedThisFrame = false; + f.swapchainUsedThisFrame = false; + f.skipPresent = false; + } + + public void markFrameEmpty(FrameState f) { + f.skipPresent = true; + f.emptyFramesThisFrame++; + } + + public void ensureSwapchainRenderPass(float clearR, float clearG, float clearB, float clearA, boolean clear) { + ensureSwapchainRenderPass(frame(), clearR, clearG, clearB, clearA, clear); + } + + public void ensureSwapchainRenderPass(FrameState f, float clearR, float clearG, float clearB, float clearA, boolean clear) { + if (!ensureSwapchainAcquired(f)) return; // present-skip; don't bind tex=0 + if (f.renderPass != 0 && f.currentColorTarget == f.swapchainTexture) { + return; + } + + endActiveEncoders(f); + + if (!f.clearedThisFrame) { + clear = true; + } + + try (var stack = stackPush()) { + final SDL_GPUColorTargetInfo.Buffer colorTargets = SDL_GPUColorTargetInfo.calloc(1, stack); + final long ctAddr = colorTargets.get(0).address(); + MemoryAccess.putAddress(ctAddr + SDL_GPUColorTargetInfo.TEXTURE, f.swapchainTexture); + MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.LOAD_OP, clear ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD); + MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + + if (clear) { + final long ccAddr = ctAddr + SDL_GPUColorTargetInfo.CLEAR_COLOR; + MemoryAccess.putFloat(ccAddr + SDL_FColor.R, clearR); + MemoryAccess.putFloat(ccAddr + SDL_FColor.G, clearG); + MemoryAccess.putFloat(ccAddr + SDL_FColor.B, clearB); + MemoryAccess.putFloat(ccAddr + SDL_FColor.A, clearA); + f.clearedThisFrame = true; + } + + if (preRenderPassHook != null) preRenderPassHook.run(); + assertNoEncoderActive(f, "SDL_BeginGPURenderPass(swapchain)"); + f.renderPass = SDL_BeginGPURenderPass(f.commandBuffer, colorTargets, null); + if (f.renderPass == 0) { + throw new RuntimeException("Failed to begin render pass: " + SDLError.SDL_GetError()); + } + f.renderPassGeneration++; + f.swapchainPassesThisFrame++; + f.currentColorTarget = f.swapchainTexture; + f.currentDepthTarget = 0; + f.activeLayoutHash = SWAPCHAIN_LAYOUT_HASH; + f.swapchainUsedThisFrame = true; + } + } + + + private volatile Runnable preRenderPassHook; + private volatile Runnable beforeSubmit; + private volatile Runnable afterPresent; + + public void setPreRenderPassHook(Runnable hook) { this.preRenderPassHook = hook; } + + public void noteComputePassBegun() { + final FrameState f = frame(); + f.computePassesThisFrame++; + f.computePassOpen = true; + } + + public void noteComputePassEnded() { frame().computePassOpen = false; } + + public void noteComputeBatchJoin() { frame().computeBatchJoinsThisFrame++; } + + public void noteUniformPushBytes(long bytes) { + final FrameState f = frame(); + f.uniformPushBytesThisFrame += bytes; + f.uniformPushesThisFrame++; + } + + public void noteUniformPushSkipped() { frame().uniformPushSkipsThisFrame++; } + + public void noteExternalUboPush() { frame().externalUboPushesThisFrame++; } + + public void noteExternalUboPushSkipped() { frame().externalUboPushSkipsThisFrame++; } + + public void notePerFrameBlockPassBreak() { frame().perFrameBlockPassBreaksThisFrame++; } + + public void noteBatchBreakPipeline() { frame().batchBreakPipelineThisFrame++; } + + public void noteBatchBreakSampler() { frame().batchBreakSamplerThisFrame++; } + + public void noteStateApply() { frame().stateAppliesThisFrame++; } + + public void notePersistentDrain() { frame().persistentDrainsThisFrame++; } + + public void noteUniformBlockFlush(int block, long bytes) { + final FrameState f = frame(); + f.uniformBlockFlushesThisFrame[block]++; + f.uniformBlockBytesThisFrame[block] += bytes; + } + + public void noteMipGen() { frame().mipGensThisFrame++; } + + public void noteBlit() { frame().blitsThisFrame++; } + + public void noteClearPass() { frame().clearPassesThisFrame++; } + + public void noteMaterializedClearPass() { frame().materializedClearPassesThisFrame++; } + + public long beginRenderPass(SDL_GPUColorTargetInfo.Buffer colorTargets, SDL_GPUDepthStencilTargetInfo depthTarget) { + final FrameState f = frame(); + endActiveEncoders(f); + if (preRenderPassHook != null) preRenderPassHook.run(); + assertNoEncoderActive(f, "SDL_BeginGPURenderPass"); + f.renderPass = SDL_BeginGPURenderPass(f.commandBuffer, colorTargets, depthTarget); + if (f.renderPass == 0) { + throw new RuntimeException("Failed to begin render pass: " + SDLError.SDL_GetError()); + } + f.renderPassGeneration++; + f.fboPassesThisFrame++; + f.currentColorTarget = colorTargets != null && colorTargets.remaining() > 0 ? colorTargets.texture() : 0; + f.currentDepthTarget = depthTarget != null ? MemoryAccess.getAddress(depthTarget.address() + SDL_GPUDepthStencilTargetInfo.TEXTURE) : 0; + return f.renderPass; + } + + public void endRenderPassIfActive() { + endRenderPassIfActive(frame()); + } + + public void endRenderPassIfActive(FrameState f) { + if (f.renderPass != 0) { + SDL_EndGPURenderPass(f.renderPass); + f.renderPass = 0; + f.currentColorTarget = 0; + f.currentDepthTarget = 0; + f.activeLayoutHash = 0; + } + } + + private void endActiveEncoders(FrameState f) { + endCopyPassIfActive(f); + endRenderPassIfActive(f); + } + + /** Dev-only check */ + private void assertNoEncoderActive(FrameState f, String about) { + if (!SystemProperties.SDL_ENCODER_ASSERTIONS) return; + if (f.renderPass != 0 || f.copyPass != 0 || f.computePassOpen) { + LOG.error("Encoder invariant violated before {}: renderPass={} copyPass={} computePassOpen={} on CB={}", about, f.renderPass, f.copyPass, f.computePassOpen, f.commandBuffer); + endActiveEncoders(f); + if (SystemProperties.SDL_ENCODER_ASSERTIONS_FATAL) { + throw new IllegalStateException("Encoder invariant violated before " + about); + } + } + } + + public long ensureCopyPass() { + final FrameState f = frame(); + if (f.copyPass != 0) { + if (f.commandBuffer == 0 && shouldAutoSubmitPendingUpload(f)) { + endCopyPassIfActive(f); + flushPendingUploadCommandBuffer(f); + } else { + return f.copyPass; + } + } + endActiveEncoders(f); + final long cb = getCommandBuffer(f); + if (cb == 0) return 0; + assertNoEncoderActive(f, "SDL_BeginGPUCopyPass"); + f.copyPass = SDL_BeginGPUCopyPass(cb); + if (Tracy.ENABLED) f.copyPassesThisFrame++; + return f.copyPass; + } + + public long getCopyPass() { + return frame().copyPass; + } + + public void setBeforeEndCopyPassCallback(Runnable callback) { + this.beforeEndCopyPass = callback; + } + + public void setBeforePendingUploadSubmitCallback(Runnable callback) { + this.beforePendingUploadSubmit = callback; + } + + public void setBeforeSubmitCallback(Runnable callback) { + this.beforeSubmit = callback; + } + + public void setAfterPresentCallback(Runnable callback) { + this.afterPresent = callback; + } + + public void requestFlushOnAllRegisteredFrames() { + final int n = registeredFrames.size(); + for (int i = 0; i < n; i++) { + registeredFrames.get(i).flushRequested = true; + } + } + + public void requestSyncFlushOnAllRegisteredFrames() { + globalSyncAtNextBeginFrame = true; + final int n = registeredFrames.size(); + for (int i = 0; i < n; i++) { + final FrameState f = registeredFrames.get(i); + f.flushRequested = true; + f.syncOnNextFlush = true; + } + } + + public void endCopyPassIfActive() { + endCopyPassIfActive(frame()); + } + + private void endCopyPassIfActive(FrameState f) { + if (f.copyPass != 0) { + if (beforeEndCopyPass != null) beforeEndCopyPass.run(); + SDL_EndGPUCopyPass(f.copyPass); + f.copyPass = 0; + } + } + + public void endFrame() { + final FrameState f = frame(); + if (!f.frameActive) return; + + if (beforeSubmit != null) beforeSubmit.run(); + + endCopyPassIfActive(f); + endRenderPassIfActive(f); + + if (!f.swapchainAcquiredThisFrame && !f.swapchainUnavailable && !f.skipPresent && f.commandBuffer != 0) { + ensureSwapchainAcquired(f); + } + + if (f.commandBuffer != 0) { + Tracy.beginZone(Z_SDL_SUBMIT); + try { + if (f.wantFenceOnNextSubmit) { + f.wantFenceOnNextSubmit = false; + f.lastAcquiredFence = SDL_SubmitGPUCommandBufferAndAcquireFence(f.commandBuffer); + if (f.lastAcquiredFence == 0) { + LOG.error("Failed to submit+acquireFence GPU command buffer: {}", SDLError.SDL_GetError()); + } + } else if (!SDL_SubmitGPUCommandBuffer(f.commandBuffer)) { + LOG.error("Failed to submit GPU command buffer: {}", SDLError.SDL_GetError()); + } + } finally { + Tracy.endZone(); + } + f.submitsThisFrame++; + f.commandBuffer = 0; + } + + f.drawableStarved = f.presentSkipsThisFrame > 0; + + if (Tracy.ENABLED && resourceManager != null) SdlFramePlots.emit(f, resourceManager); + f.lastPlottedRenderPassGen = f.renderPassGeneration; + f.computePassesThisFrame = 0; + f.submitsThisFrame = 0; + f.uniformPushBytesThisFrame = 0; + f.uniformPushesThisFrame = 0; + f.uniformPushSkipsThisFrame = 0; + f.externalUboPushesThisFrame = 0; + f.externalUboPushSkipsThisFrame = 0; + f.persistentDrainsThisFrame = 0; + Arrays.fill(f.uniformBlockFlushesThisFrame, 0); + Arrays.fill(f.uniformBlockBytesThisFrame, 0L); + f.perFrameBlockPassBreaksThisFrame = 0; + f.batchBreakPipelineThisFrame = 0; + f.batchBreakSamplerThisFrame = 0; + f.stateAppliesThisFrame = 0; + f.acquireWaitNanosThisFrame = 0; + f.mipGensThisFrame = 0; + f.blitsThisFrame = 0; + f.clearPassesThisFrame = 0; + f.swapchainPassesThisFrame = 0; + f.fboPassesThisFrame = 0; + f.arenaSubmitsThisFrame = 0; + f.arenaOverflowFlushesThisFrame = 0; + f.copyPassesThisFrame = 0; + f.materializedClearPassesThisFrame = 0; + f.presentSkipsThisFrame = 0; + f.emptyFramesThisFrame = 0; + f.droppedDrawsThisFrame = 0; + f.computeBatchJoinsThisFrame = 0; + + f.frameActive = false; + f.swapchainTexture = 0; + + if (afterPresent != null) afterPresent.run(); + } + + public void submitMidFrame() { + final FrameState f = frame(); + if (f.commandBuffer == 0) return; + endCopyPassIfActive(f); + endRenderPassIfActive(f); + Tracy.beginZone(Z_SDL_SUBMIT); + try { + if (f.wantFenceOnNextSubmit) { + f.wantFenceOnNextSubmit = false; + f.lastAcquiredFence = SDL_SubmitGPUCommandBufferAndAcquireFence(f.commandBuffer); + if (f.lastAcquiredFence == 0) { + LOG.error("Mid-frame submit+acquireFence failed: {}", SDLError.SDL_GetError()); + } + } else if (!SDL_SubmitGPUCommandBuffer(f.commandBuffer)) { + LOG.error("Mid-frame submit failed: {}", SDLError.SDL_GetError()); + } + } finally { + Tracy.endZone(); + } + f.submitsThisFrame++; + f.commandBuffer = 0; + if (f.frameActive) { + reacquireCommandBuffer(); + } + } + + public void presentFrame() { + final FrameState f = frame(); + if (f.frameActive) { + endFrame(); + } + beginFrame(); + } + + public long getCommandBuffer() { + return getCommandBuffer(frame()); + } + + public static void warnDroppedOutsideFrame(boolean alreadyWarned, String operation) { + if (alreadyWarned) return; + LOG.warn("{} was issued with no live command buffer and has been dropped; the caller runs after the frame was " + "submitted (thread={})", operation, Thread.currentThread().getName(), new Throwable("call site")); + } + + public long getCommandBuffer(FrameState f) { + if (f.flushRequested) { + if (f.commandBuffer == 0 && f.pendingUploadCommandBuffer != 0) { + endCopyPassIfActive(f); + flushPendingUploadCommandBuffer(f); + } + f.flushRequested = false; + } + if (f.commandBuffer != 0) return f.commandBuffer; + return getOrCreatePendingUploadCommandBuffer(f); + } + + public void recordUploadCommands(long bytes, int commands) { + final FrameState f = frame(); + f.pendingUploadBytes += bytes; + f.pendingUploadCommands += commands; + } + + public boolean shouldAutoSubmitPendingUpload() { + return shouldAutoSubmitPendingUpload(frame()); + } + + private boolean shouldAutoSubmitPendingUpload(FrameState f) { + return f.pendingUploadBytes >= MAX_PENDING_UPLOAD_BYTES || f.pendingUploadCommands >= MAX_PENDING_UPLOAD_COMMANDS; + } + + private long getOrCreatePendingUploadCommandBuffer(FrameState f) { + if (f.pendingUploadCommandBuffer == 0) { + f.pendingUploadCommandBuffer = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (f.pendingUploadCommandBuffer == 0) { + LOG.error("Failed to acquire pending upload command buffer: {}", SDLError.SDL_GetError()); + } + } + return f.pendingUploadCommandBuffer; + } + + public void flushPendingUploadCommandBuffer() { + flushPendingUploadCommandBuffer(frame()); + } + + private void flushPendingUploadCommandBuffer(FrameState f) { + final boolean sync = f.syncOnNextFlush; + if (f.pendingUploadCommandBuffer == 0) { + if (sync) { + f.syncOnNextFlush = false; + Tracy.beginZone(Z_SDL_FENCE_WAIT); + try { SDL_WaitForGPUIdle(device.getDevice()); } + finally { Tracy.endZone(); } + } + return; + } + endCopyPassIfActive(f); + if (beforePendingUploadSubmit != null) beforePendingUploadSubmit.run(); + if (f.pendingUploadCommandBuffer != 0) { + Tracy.beginZone(Z_SDL_SUBMIT); + final boolean submitted; + try { + submitted = SDL_SubmitGPUCommandBuffer(f.pendingUploadCommandBuffer); + } finally { + Tracy.endZone(); + } + if (!submitted) { + LOG.error("Failed to submit pending upload command buffer: {}", SDLError.SDL_GetError()); + } + f.submitsThisFrame++; + f.pendingUploadCommandBuffer = 0; + f.pendingUploadBytes = 0; + f.pendingUploadCommands = 0; + } + if (sync) { + f.syncOnNextFlush = false; + Tracy.beginZone(Z_SDL_FENCE_WAIT); + try { SDL_WaitForGPUIdle(device.getDevice()); } + finally { Tracy.endZone(); } + } + } + + public long getRenderPass() { + return frame().renderPass; + } + + public long getRenderPassGeneration() { + return frame().renderPassGeneration; + } + + public long getRenderPass(FrameState f) { return f.renderPass; } + + public long getRenderPassGeneration(FrameState f) { return f.renderPassGeneration; } + + public boolean isFrameActive(FrameState f) { return f.frameActive; } + + public boolean isRenderPassActive(FrameState f) { return f.renderPass != 0; } + + public long getCurrentColorTarget(FrameState f) { return f.currentColorTarget; } + + public long getCurrentDepthTarget(FrameState f) { return f.currentDepthTarget; } + + public long getActiveLayoutHash(FrameState f) { return f.activeLayoutHash; } + + public long getSwapchainTexture() { + final FrameState f = frame(); + ensureSwapchainAcquired(f); + return f.swapchainTexture; + } + + public int getSwapchainWidth() { + final FrameState f = frame(); + ensureSwapchainAcquired(f); + return f.swapchainWidth; + } + + public int getSwapchainHeight() { + final FrameState f = frame(); + ensureSwapchainAcquired(f); + return f.swapchainHeight; + } + + public int getSwapchainFormat() { + return device.getSwapchainTextureFormat(); + } + + public boolean isFrameActive() { + return frame().frameActive; + } + + public boolean isRenderPassActive() { + return frame().renderPass != 0; + } + + public long getCurrentColorTarget() { + return frame().currentColorTarget; + } + + public long getCurrentDepthTarget() { + return frame().currentDepthTarget; + } + + public long getActiveLayoutHash() { + return frame().activeLayoutHash; + } + + public void setActiveLayoutHash(long h) { + frame().activeLayoutHash = h; + } + + public long getFrameNumber() { + return frame().frameNumber; + } + + public boolean isSwapchainUsedThisFrame() { + return frame().swapchainUsedThisFrame; + } + + public void reacquireCommandBuffer() { + final FrameState f = frame(); + flushPendingUploadCommandBuffer(f); + f.copyPass = 0; + f.commandBuffer = SDL_AcquireGPUCommandBuffer(device.getDevice()); + f.renderPass = 0; + f.currentColorTarget = 0; + f.currentDepthTarget = 0; + + if (f.frameActive) { + final boolean wasAcquired = f.swapchainAcquiredThisFrame; + f.swapchainAcquiredThisFrame = false; + f.swapchainTexture = 0; + if (wasAcquired && !ensureSwapchainAcquired(f)) { + LOG.warn("Failed to re-acquire swapchain after readback: {}", SDLError.SDL_GetError()); + } + f.clearedThisFrame = false; + } + } + + public void releaseThreadState() { + final FrameState f = frame(); + if (resourceManager != null) resourceManager.flushUploadArena(f); + flushPendingUploadCommandBuffer(f); + releaseFrameStateResources(f); + registeredFrames.remove(f); + tlFrame.remove(); + refreshSoleFrame(); + } + + private void releaseFrameStateResources(FrameState f) { + if (f.batchXfer != 0) { + if (f.batchMapped != null) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), f.batchXfer); + f.batchMapped = null; + } + resourceManager.releaseTransferBufferHandle(f.batchXfer); + f.batchXfer = 0; + } + if (f.arenaXfer != 0) { + if (f.arenaMapped != null) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), f.arenaXfer); + f.arenaMapped = null; + } + resourceManager.releaseTransferBufferHandle(f.arenaXfer); + f.arenaXfer = 0; + } + f.arena.reset(); + f.pendingTexHandles.clear(); + f.pendingTexX.clear(); + f.pendingTexY.clear(); + f.pendingTexW.clear(); + f.pendingTexH.clear(); + f.pendingTexLevels.clear(); + f.pendingTexOffsets.clear(); + f.uboPushViews.clear(); + f.uboPushViewSource.clear(); + + if (f.lastAcquiredFence != 0) { + SDL_ReleaseGPUFence(device.getDevice(), f.lastAcquiredFence); + f.lastAcquiredFence = 0; + } + } + + public void releaseAllRegisteredFrames() { + for (FrameState f : registeredFrames) { + releaseFrameStateResources(f); + } + registeredFrames.clear(); + soleFrame = null; + } + + public boolean ensureSwapchainAcquired() { + return ensureSwapchainAcquired(frame()); + } + + public boolean ensureSwapchainAcquired(FrameState f) { + if (f.swapchainAcquiredThisFrame) return true; + if (f.swapchainUnavailable) return false; + if (!f.frameActive || f.commandBuffer == 0) return false; + + endActiveEncoders(f); + + final long t0 = Tracy.ENABLED ? System.nanoTime() : 0L; + final long tex; + final int w; + final int h; + final boolean callOk; + try (var stack = stackPush()) { + final PointerBuffer pTexture = stack.pointers(0); + final IntBuffer pWidth = stack.ints(0); + final IntBuffer pHeight = stack.ints(0); + Tracy.beginZone(Z_SDL_ACQUIRE_WAIT); + try { + callOk = SDL_AcquireGPUSwapchainTexture(f.commandBuffer, Display.getWindow(), pTexture, pWidth, pHeight); + } finally { + Tracy.endZone(); + } + tex = pTexture.get(0); + w = pWidth.get(0); + h = pHeight.get(0); + } catch (RuntimeException re) { + if (Tracy.ENABLED) f.acquireWaitNanosThisFrame += System.nanoTime() - t0; + f.swapchainUnavailable = true; + throw re; + } + if (Tracy.ENABLED) f.acquireWaitNanosThisFrame += System.nanoTime() - t0; + + if (!callOk) { + f.swapchainUnavailable = true; + return false; + } + if (tex == 0) { + f.swapchainUnavailable = true; + f.presentSkipsThisFrame++; + return false; + } + f.swapchainTexture = tex; + f.swapchainWidth = w; + f.swapchainHeight = h; + f.swapchainAcquiredThisFrame = true; + return true; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/SdlFramePlots.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/SdlFramePlots.java new file mode 100644 index 000000000..fb30b79fb --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/SdlFramePlots.java @@ -0,0 +1,107 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.FrameState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; + +final class SdlFramePlots { + + private SdlFramePlots() {} + + private static final long PLOT_RENDER_PASSES = Tracy.plotHandle("sdl.renderPasses"); + private static final long PLOT_CLEAR_PASSES = Tracy.plotHandle("sdl.clearPasses"); + private static final long PLOT_CLEAR_PASSES_MATERIALIZED = Tracy.plotHandle("sdl.clearPasses.materialized"); + private static final long PLOT_PASSES_SWAPCHAIN = Tracy.plotHandle("sdl.passes.swapchain"); + private static final long PLOT_PASSES_FBO = Tracy.plotHandle("sdl.passes.fbo"); + private static final long PLOT_LOCKED_HANDLE_READS = Tracy.plotHandle("sdl.lockedHandleReads"); + private static final long PLOT_SLOT_WRITES = Tracy.plotHandle("sdl.slotWrites"); + private static final long PLOT_SLOT_WRITES_ELIDED = Tracy.plotHandle("sdl.slotWritesElided"); + private static final long PLOT_COMPUTE_PASSES = Tracy.plotHandle("sdl.computePasses"); + private static final long PLOT_SUBMITS = Tracy.plotHandle("sdl.submits"); + private static final long PLOT_UNIFORM_PUSH_BYTES = Tracy.plotHandle("sdl.uniformPushBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long PLOT_UNIFORM_PUSHES = Tracy.plotHandle("sdl.uniformPushes"); + private static final long PLOT_UNIFORM_PUSH_SKIPS = Tracy.plotHandle("sdl.uniformPushSkips"); + private static final long PLOT_EXT_UBO_PUSHES = Tracy.plotHandle("sdl.extUboPushes"); + private static final long PLOT_EXT_UBO_PUSH_SKIPS = Tracy.plotHandle("sdl.extUboPushSkips"); + private static final long PLOT_PERSISTENT_DRAINS = Tracy.plotHandle("sdl.persistentDrains"); + private static final long PLOT_PER_FRAME_BLOCK_FLUSHES = Tracy.plotHandle("sdl.perFrameBlockFlushes"); + private static final long PLOT_PER_FRAME_BLOCK_PASS_BREAKS = Tracy.plotHandle("sdl.perFrameBlockPassBreaks"); + private static final long PLOT_BATCH_BREAK_PIPELINE = Tracy.plotHandle("sdl.batchBreaks.pipeline"); + private static final long PLOT_BATCH_BREAK_SAMPLER = Tracy.plotHandle("sdl.batchBreaks.sampler"); + private static final long PLOT_STATE_APPLIES = Tracy.plotHandle("sdl.stateApplies"); + private static final long PLOT_PER_FRAME_BLOCK_BYTES = Tracy.plotHandle("sdl.perFrameBlockBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long PLOT_PER_PASS_BLOCK_FLUSHES = Tracy.plotHandle("sdl.perPassBlockFlushes"); + private static final long PLOT_PER_PASS_BLOCK_BYTES = Tracy.plotHandle("sdl.perPassBlockBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long PLOT_ACQUIRE_WAIT_US = Tracy.plotHandle("sdl.acquireWaitUs"); + private static final long PLOT_PRESENT_TO_PRESENT_US = Tracy.plotHandle("sdl.presentToPresentUs"); + private static final long PLOT_FRAMES_IN_FLIGHT = Tracy.plotHandle("sdl.framesInFlight"); + private static final long PLOT_MIP_GENS = Tracy.plotHandle("sdl.mipGens"); + private static final long PLOT_BLIT_FALLBACKS = Tracy.plotHandle("sdl.blitFallbacks"); + private static final long PLOT_PRESENT_SKIPS = Tracy.plotHandle("sdl.presentSkips"); + private static final long PLOT_EMPTY_FRAMES = Tracy.plotHandle("sdl.emptyFrames"); + private static final long PLOT_DROPPED_DRAWS = Tracy.plotHandle("sdl.droppedDraws"); + private static final long PLOT_SSBO_BINDS = Tracy.plotHandle("sdl.ssboBinds"); + private static final long PLOT_COMPUTE_BATCH_JOINS = Tracy.plotHandle("sdl.computeBatchJoins"); + private static final long PLOT_ARENA_SUBMITS = Tracy.plotHandle("sdl.arenaSubmits"); + private static final long PLOT_ARENA_OVERFLOW_FLUSHES = Tracy.plotHandle("sdl.arenaOverflowFlushes"); + private static final long PLOT_COPY_PASSES = Tracy.plotHandle("sdl.copyPasses"); + private static final long PLOT_BUFFER_CREATES = Tracy.plotHandle("sdl.bufferCreates"); + private static final long PLOT_BUFFER_DELETES = Tracy.plotHandle("sdl.bufferDeletes"); + private static final long PLOT_BUFFER_POOL_HITS = Tracy.plotHandle("sdl.bufferPoolHits"); + private static final long PLOT_PIPELINE_KEY_RECOMPUTES = Tracy.plotHandle("sdl.pipelineKeyRecomputes"); + private static final long PLOT_PIPELINE_FAST_PATH_HITS = Tracy.plotHandle("sdl.pipelineFastPathHits"); + + private static final int[] contextCounters = new int[SDLGPURenderBackend.CTR_COUNT]; + + static void emit(FrameState f, ResourceManager resourceManager) { + SDLGPURenderBackend.takeContextCounters(contextCounters); + Tracy.plotInt(PLOT_RENDER_PASSES, f.renderPassGeneration - f.lastPlottedRenderPassGen - f.clearPassesThisFrame); + Tracy.plotInt(PLOT_CLEAR_PASSES, f.clearPassesThisFrame); + Tracy.plotInt(PLOT_CLEAR_PASSES_MATERIALIZED, f.materializedClearPassesThisFrame); + Tracy.plotInt(PLOT_PASSES_SWAPCHAIN, f.swapchainPassesThisFrame); + Tracy.plotInt(PLOT_PASSES_FBO, f.fboPassesThisFrame - f.clearPassesThisFrame); + Tracy.plotInt(PLOT_LOCKED_HANDLE_READS, resourceManager.takeLockedReadCount()); + Tracy.plotInt(PLOT_SLOT_WRITES, contextCounters[SDLGPURenderBackend.CTR_SLOT_WRITES]); + Tracy.plotInt(PLOT_SLOT_WRITES_ELIDED, contextCounters[SDLGPURenderBackend.CTR_SLOT_WRITES_ELIDED]); + Tracy.plotInt(PLOT_SSBO_BINDS, contextCounters[SDLGPURenderBackend.CTR_SSBO_BINDS]); + Tracy.plotInt(PLOT_ARENA_SUBMITS, f.arenaSubmitsThisFrame); + Tracy.plotInt(PLOT_ARENA_OVERFLOW_FLUSHES, f.arenaOverflowFlushesThisFrame); + Tracy.plotInt(PLOT_COPY_PASSES, f.copyPassesThisFrame); + Tracy.plotInt(PLOT_BUFFER_CREATES, resourceManager.takeBufferCreateCount()); + Tracy.plotInt(PLOT_BUFFER_DELETES, resourceManager.takeBufferDeleteCount()); + Tracy.plotInt(PLOT_BUFFER_POOL_HITS, resourceManager.takeBufferPoolHitCount()); + Tracy.plotInt(PLOT_PIPELINE_KEY_RECOMPUTES, contextCounters[SDLGPURenderBackend.CTR_KEY_RECOMPUTES]); + Tracy.plotInt(PLOT_PIPELINE_FAST_PATH_HITS, contextCounters[SDLGPURenderBackend.CTR_FAST_PATH_HITS]); + Tracy.plotInt(PLOT_COMPUTE_PASSES, f.computePassesThisFrame); + Tracy.plotInt(PLOT_COMPUTE_BATCH_JOINS, f.computeBatchJoinsThisFrame); + Tracy.plotInt(PLOT_SUBMITS, f.submitsThisFrame); + Tracy.plotInt(PLOT_UNIFORM_PUSH_BYTES, f.uniformPushBytesThisFrame); + Tracy.plotInt(PLOT_UNIFORM_PUSHES, f.uniformPushesThisFrame); + Tracy.plotInt(PLOT_UNIFORM_PUSH_SKIPS, f.uniformPushSkipsThisFrame); + Tracy.plotInt(PLOT_EXT_UBO_PUSHES, f.externalUboPushesThisFrame); + Tracy.plotInt(PLOT_EXT_UBO_PUSH_SKIPS, f.externalUboPushSkipsThisFrame); + Tracy.plotInt(PLOT_PERSISTENT_DRAINS, f.persistentDrainsThisFrame); + Tracy.plotInt(PLOT_PER_FRAME_BLOCK_FLUSHES, f.uniformBlockFlushesThisFrame[ShaderManager.BLOCK_PER_FRAME]); + Tracy.plotInt(PLOT_PER_FRAME_BLOCK_PASS_BREAKS, f.perFrameBlockPassBreaksThisFrame); + Tracy.plotInt(PLOT_BATCH_BREAK_PIPELINE, f.batchBreakPipelineThisFrame); + Tracy.plotInt(PLOT_BATCH_BREAK_SAMPLER, f.batchBreakSamplerThisFrame); + Tracy.plotInt(PLOT_STATE_APPLIES, f.stateAppliesThisFrame); + Tracy.plotInt(PLOT_PER_FRAME_BLOCK_BYTES, f.uniformBlockBytesThisFrame[ShaderManager.BLOCK_PER_FRAME]); + Tracy.plotInt(PLOT_PER_PASS_BLOCK_FLUSHES, f.uniformBlockFlushesThisFrame[ShaderManager.BLOCK_PER_PASS]); + Tracy.plotInt(PLOT_PER_PASS_BLOCK_BYTES, f.uniformBlockBytesThisFrame[ShaderManager.BLOCK_PER_PASS]); + Tracy.plotInt(PLOT_ACQUIRE_WAIT_US, f.acquireWaitNanosThisFrame / 1000); + final long nowNanos = System.nanoTime(); + if (f.lastEndFrameNanos != 0) Tracy.plotInt(PLOT_PRESENT_TO_PRESENT_US, (nowNanos - f.lastEndFrameNanos) / 1000); + f.lastEndFrameNanos = nowNanos; + Tracy.plotInt(PLOT_FRAMES_IN_FLIGHT, Device.FRAMES_IN_FLIGHT); + Tracy.plotInt(PLOT_MIP_GENS, f.mipGensThisFrame); + Tracy.plotInt(PLOT_BLIT_FALLBACKS, f.blitsThisFrame); + Tracy.plotInt(PLOT_PRESENT_SKIPS, f.presentSkipsThisFrame); + Tracy.plotInt(PLOT_EMPTY_FRAMES, f.emptyFramesThisFrame); + Tracy.plotInt(PLOT_DROPPED_DRAWS, f.droppedDrawsThisFrame); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/StateSyncVerifier.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/StateSyncVerifier.java new file mode 100644 index 000000000..6baaecf4e --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/frame/StateSyncVerifier.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +public final class StateSyncVerifier { + + private StateSyncVerifier() {} + + public static void verify(int glsmVao, int backendVao, int glsmDrawFbo, int backendDrawFbo, int glsmReadFbo, int backendReadFbo, int glsmTextureUnit, int backendTextureUnit) { + check("bound VAO", glsmVao, backendVao); + check("draw framebuffer", glsmDrawFbo, backendDrawFbo); + check("read framebuffer", glsmReadFbo, backendReadFbo); + check("active texture unit", glsmTextureUnit, backendTextureUnit); + } + + private static void check(String what, int glsm, int backend) { + if (glsm == backend) return; + throw new IllegalStateException("GLSM/ContextState drift on " + what + ": GLSM=" + glsm + " backend=" + backend + ". GLSM elides redundant binds against its cache, so a bypass of GLStateManager leaves the backend on stale state and the next elided rebind silently drops the call."); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java new file mode 100644 index 000000000..f679e164b --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java @@ -0,0 +1,205 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.FrameState; +import com.gtnewhorizons.angelica.sdlgpu.resource.FormatMap; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; +import org.lwjgl.sdl.SDL_GPUBufferBinding; +import org.lwjgl.sdl.SDL_GPUBufferCreateInfo; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class DrawDispatch { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final int FAN_INDEX_BUFFER_INITIAL = 64 * 1024; + + public interface FanUploadSink { + public void enqueuePreCopied(ByteBuffer data, long dstHandle, long dstOffset, boolean cycle); + } + + private final Device device; + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final PipelineApplier pipelineApplier; + private final FanUploadSink fanUploadSink; + + private final IntOpenHashSet restartShadowMissingWarned = new IntOpenHashSet(); + public boolean restartMultiDrawWarned; + private boolean unsignedByteIndicesWarned; + private boolean prepareFrameInactiveWarned; + private boolean prepareRpInactiveWarned; + private boolean drawArraysRpInactiveWarned; + + public DrawDispatch(Device device, FrameManager frameManager, ResourceManager resourceManager, PipelineApplier pipelineApplier, FanUploadSink fanUploadSink) { + this.device = device; + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.pipelineApplier = pipelineApplier; + this.fanUploadSink = fanUploadSink; + } + + public void setPrimitiveTypeForDraw(ContextState st, int newType) { + if (st.pipeline.primitiveType != newType) { + st.pipeline.primitiveType = newType; + st.pipeline.markOutputDirty(); + } + } + + public void bindIndexBufferIfChanged(ContextState st, long renderPass, long eboHandle, int indexSize, int offset) { + if (st.lastBoundEboHandle == eboHandle && st.lastBoundEboIndexSize == indexSize && st.lastBoundEboOffset == offset) return; + final long addr = st.eboBinding.address(); + MemoryAccess.putAddress(addr + SDL_GPUBufferBinding.BUFFER, eboHandle); + MemoryAccess.putInt(addr + SDL_GPUBufferBinding.OFFSET, offset); + SDL_BindGPUIndexBuffer(renderPass, st.eboBinding, indexSize); + st.lastBoundEboHandle = eboHandle; + st.lastBoundEboIndexSize = indexSize; + st.lastBoundEboOffset = offset; + } + + public void warnDrawArraysNoRenderPass(int mode, int boundFbo) { + if (drawArraysRpInactiveWarned) return; + drawArraysRpInactiveWarned = true; + LOG.warn("drawArrays: render pass not active after ensureRenderPass; draw skipped (mode=0x{} boundFbo={}). Further drops counted in sdl.droppedDraws.", Integer.toHexString(mode), boundFbo); + } + + public boolean prepareIndexedDraw(ContextState st, int mode, int type) { + final FrameState f = frameManager.frame(); + if (type == GL11.GL_UNSIGNED_BYTE) { + f.droppedDrawsThisFrame++; + if (!unsignedByteIndicesWarned) { + LOG.error("SDL backend: drawElements with GL_UNSIGNED_BYTE indices is unsupported; skipping draw. Use SHORT or INT indices."); + unsignedByteIndicesWarned = true; + } + return false; + } + if (!frameManager.isFrameActive(f)) { + f.droppedDrawsThisFrame++; + if (!prepareFrameInactiveWarned) { + prepareFrameInactiveWarned = true; + LOG.warn("prepareIndexedDraw: frame not active; draw skipped (mode=0x{} type=0x{})", Integer.toHexString(mode), Integer.toHexString(type)); + } + return false; + } + setPrimitiveTypeForDraw(st, FormatMap.mapPrimitiveType(mode)); + pipelineApplier.ensureRenderPass(st, f); + if (!frameManager.isRenderPassActive(f)) { + f.droppedDrawsThisFrame++; + if (!prepareRpInactiveWarned) { + prepareRpInactiveWarned = true; + LOG.warn("prepareIndexedDraw: render pass not active after ensureRenderPass; draw skipped (mode=0x{} type=0x{} boundFbo={})", Integer.toHexString(mode), Integer.toHexString(type), st.boundFboId); + } + return false; + } + if (!pipelineApplier.applyPipelineAndState(st, f)) { + f.droppedDrawsThisFrame++; + return false; + } + return true; + } + + public void issueIndexedDraw(ContextState st, long rp, int ebo, int indexType, int count, int instances, int firstIndex, int baseVertex) { + final EBOSplitScanner.EboSplit[] full; + if (st.primitiveRestartEnabled) { + full = resourceManager.getOrScanSplits(ebo, indexType, st.primitiveRestartSentinel); + if (full == null && restartShadowMissingWarned.add(ebo)) { + LOG.warn("primitive restart enabled but EBO {} was uploaded earlier; cannot CPU-scan. Enable GL_PRIMITIVE_RESTART before uploading the EBO to fix.", ebo); + } + } else { + full = null; + } + if (full == null) { + SDL_DrawGPUIndexedPrimitives(rp, count, instances, firstIndex, baseVertex, 0); + return; + } + st.ensureEboSplitScratch(full.length); + final int n = EBOSplitScanner.sliceSplits(full, firstIndex, count, st.eboSplitFirsts, st.eboSplitCounts); + for (int i = 0; i < n; i++) { + final int sCount = st.eboSplitCounts[i]; + if (sCount <= 0) continue; + SDL_DrawGPUIndexedPrimitives(rp, sCount, instances, firstIndex + st.eboSplitFirsts[i], baseVertex, 0); + } + } + + public void drawTriangleFanAsTriangleList(ContextState st, int first, int count) { + final int numTriangles = count - 2; + final boolean use32bit = (first + count - 1) > 65535; + final int bytesPerIndex = use32bit ? 4 : 2; + final int indexDataSize = numTriangles * 3 * bytesPerIndex; + + if (st.fanIndexBuffer == 0) { + st.fanIndexBufferCapacity = Math.max(indexDataSize, FAN_INDEX_BUFFER_INITIAL); + st.fanIndexBuffer = createFanIndexBuffer(st.fanIndexBufferCapacity); + st.fanIndexBufferOffset = 0; + } else if (st.fanIndexBufferOffset + indexDataSize > st.fanIndexBufferCapacity) { + frameManager.endRenderPassIfActive(); + resourceManager.releaseBufferDeferred(st.fanIndexBuffer); + st.fanIndexBufferCapacity = Math.max(indexDataSize, st.fanIndexBufferCapacity * 2); + st.fanIndexBuffer = createFanIndexBuffer(st.fanIndexBufferCapacity); + st.fanIndexBufferOffset = 0; + } + + final int uploadOffset = st.fanIndexBufferOffset; + try (var stack = MemoryStack.stackPush()) { + final ByteBuffer indexBytes = stack.malloc(indexDataSize); + final long base = MemoryUtil.memAddress(indexBytes); + if (use32bit) { + for (int i = 0; i < numTriangles; i++) { + final long off = base + (long) i * 12L; + MemoryAccess.putInt(off, first); + MemoryAccess.putInt(off + 4, first + i + 1); + MemoryAccess.putInt(off + 8, first + i + 2); + } + } else { + for (int i = 0; i < numTriangles; i++) { + final long off = base + (long) i * 6L; + MemoryAccess.putShort(off, (short) first); + MemoryAccess.putShort(off + 2, (short) (first + i + 1)); + MemoryAccess.putShort(off + 4, (short) (first + i + 2)); + } + } + indexBytes.position(0).limit(indexDataSize); + + if (st.deferUploads) { + fanUploadSink.enqueuePreCopied(indexBytes, st.fanIndexBuffer, uploadOffset, false); + } else if (frameManager.getCommandBuffer() != 0) { + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), indexBytes, st.fanIndexBuffer, uploadOffset, false); + } + } + st.fanIndexBufferOffset += indexDataSize; + + setPrimitiveTypeForDraw(st, SDL_GPU_PRIMITIVETYPE_TRIANGLELIST); + pipelineApplier.ensureRenderPass(st); + if (!frameManager.isRenderPassActive()) return; + if (!pipelineApplier.applyPipelineAndState(st)) return; + + final int elementSize = use32bit ? SDL_GPU_INDEXELEMENTSIZE_32BIT : SDL_GPU_INDEXELEMENTSIZE_16BIT; + final long rp = frameManager.getRenderPass(); + bindIndexBufferIfChanged(st, rp, st.fanIndexBuffer, elementSize, uploadOffset); + SDL_DrawGPUIndexedPrimitives(rp, numTriangles * 3, 1, 0, 0, 0); + } + + private long createFanIndexBuffer(int capacity) { + try (var s = MemoryStack.stackPush()) { + final long handle = SDL_CreateGPUBuffer(device.getDevice(), SDL_GPUBufferCreateInfo.calloc(s).usage(SDL_GPU_BUFFERUSAGE_INDEX).size(capacity)); + resourceManager.trackBufferHandle(handle); + return handle; + } + } + + public void clearWarnedState() { + restartShadowMissingWarned.clear(); + restartMultiDrawWarned = false; + unsignedByteIndicesWarned = false; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/EBOSplitScanner.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/EBOSplitScanner.java new file mode 100644 index 000000000..a6ed55ce0 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/EBOSplitScanner.java @@ -0,0 +1,64 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.lwjgl.opengl.GL11; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; +import java.util.ArrayList; + +public final class EBOSplitScanner { + private EBOSplitScanner() {} + + public record EboSplit(int firstIndex, int count) {} + + public static EboSplit[] scanIndices(ByteBuffer shadow, int indexCount, int indexType, int sentinel) { + if (indexCount <= 0) return new EboSplit[0]; + final ArrayList runs = new ArrayList<>(4); + int runStart = 0; + switch (indexType) { + case GL11.GL_UNSIGNED_SHORT -> { + final short s = (short) sentinel; + final ShortBuffer sb = shadow.duplicate().order(ByteOrder.nativeOrder()).asShortBuffer(); + for (int i = 0; i < indexCount; i++) { + if (sb.get(i) == s) { + if (i > runStart) runs.add(new EboSplit(runStart, i - runStart)); + runStart = i + 1; + } + } + } + case GL11.GL_UNSIGNED_INT -> { + final IntBuffer ib = shadow.duplicate().order(ByteOrder.nativeOrder()).asIntBuffer(); + for (int i = 0; i < indexCount; i++) { + if (ib.get(i) == sentinel) { + if (i > runStart) runs.add(new EboSplit(runStart, i - runStart)); + runStart = i + 1; + } + } + } + default -> { + return new EboSplit[]{ new EboSplit(0, indexCount) }; + } + } + if (indexCount > runStart) runs.add(new EboSplit(runStart, indexCount - runStart)); + return runs.toArray(new EboSplit[0]); + } + + public static int sliceSplits(EboSplit[] full, int firstIndex, int count, int[] firstsOut, int[] countsOut) { + if (full.length == 0 || count <= 0) return 0; + final int drawEnd = firstIndex + count; + int n = 0; + for (EboSplit s : full) { + final int sStart = s.firstIndex(); + final int sEnd = sStart + s.count(); + if (sEnd <= firstIndex || sStart >= drawEnd) continue; + final int clippedStart = Math.max(sStart, firstIndex); + final int clippedEnd = Math.min(sEnd, drawEnd); + firstsOut[n] = clippedStart - firstIndex; + countsOut[n] = clippedEnd - clippedStart; + n++; + } + return n; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/Hashing.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/Hashing.java new file mode 100644 index 000000000..f36bd84e7 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/Hashing.java @@ -0,0 +1,64 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +public final class Hashing { + private Hashing() {} + + public static long fmix64(long h, long k) { + k ^= k >>> 33; + k *= 0xFF51AFD7ED558CCDL; + k ^= k >>> 33; + return (h ^ k) * 0xC4CEB9FE1A85EC53L; + } + + public static long packHiLo(int hi, int lo) { + return ((long) hi << 32) | (lo & 0xFFFFFFFFL); + } + + public static long hashBytes(ByteBuffer buf, int offset, int length) { + final long base = MemoryUtil.memAddress(buf) + offset; + long h = 0x9E3779B97F4A7C15L ^ ((long) length * 0xC2B2AE3D27D4EB4FL); + int i = 0; + for (; i + 8 <= length; i += 8) { + h = fmix64(h, MemoryAccess.getLong(base + i)); + } + if (i < length) { + long tail = 0; + int shift = 0; + for (; i < length; i++) { + tail |= (((long) (buf.get(offset + i) & 0xFF)) << shift); + shift += 8; + } + tail ^= tail >>> 33; + tail *= 0xFF51AFD7ED558CCDL; + h ^= tail; + } + h ^= h >>> 33; + h *= 0xFF51AFD7ED558CCDL; + h ^= h >>> 33; + return h; + } + + public static long hashFloats(float[] data) { + final int len = data.length; + long h = 0x9E3779B97F4A7C15L ^ ((long) len * 0xC2B2AE3D27D4EB4FL); + int i = 0; + for (; i + 1 < len; i += 2) { + h = fmix64(h, packHiLo(Float.floatToRawIntBits(data[i + 1]), Float.floatToRawIntBits(data[i]))); + } + if (i < len) { + long k = Float.floatToRawIntBits(data[i]) & 0xFFFFFFFFL; + k ^= k >>> 33; + k *= 0xFF51AFD7ED558CCDL; + h ^= k; + } + h ^= h >>> 33; + h *= 0xFF51AFD7ED558CCDL; + h ^= h >>> 33; + return h; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java new file mode 100644 index 000000000..4074f91fc --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java @@ -0,0 +1,806 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.sdl.SDL_FColor; +import org.lwjgl.sdl.SDL_GPUBufferBinding; +import org.lwjgl.sdl.SDL_GPUColorTargetInfo; +import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo; +import org.lwjgl.sdl.SDL_GPUViewport; +import org.lwjgl.sdl.SDL_Rect; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.FrameState; +import com.gtnewhorizons.angelica.sdlgpu.frame.StateSyncVerifier; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache; +import com.gtnewhorizons.angelica.sdlgpu.resource.FBOClearTracker; +import com.gtnewhorizons.angelica.sdlgpu.resource.FboState; +import com.gtnewhorizons.angelica.sdlgpu.resource.PersistentBufferSync; +import com.gtnewhorizons.angelica.sdlgpu.resource.PersistentMapping; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerBinder; +import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageBufferBinder; +import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageTextureBinder; +import com.gtnewhorizons.angelica.sdlgpu.shader.MatrixMarshal; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.Std140Writer; +import com.gtnewhorizons.angelica.sdlgpu.shader.UniformStaging; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.Arrays; +import java.util.HashSet; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class PipelineApplier { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final int PERSISTENT_DRAIN_INTERVAL = 16; + + private static final Tracy.ZoneId Z_SDL_APPLY_STATE = Tracy.zoneId("sdlApplyState", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_SDL_PUSH_UNIFORMS = Tracy.zoneId("sdlPushUniforms", Tracy.COLOR_CLIENT); + + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + private final PipelineStore pipelineStore; + private final FBOClearTracker fboClearTracker; + private final PersistentBufferSync persistentSync; + private final SamplerBinder samplerBinder; + private final StorageTextureBinder storageTextureBinder; + private final StorageBufferBinder storageBufferBinder; + + private DrawDispatch.FanUploadSink deferredUploadSink; + public void setDeferredUploadSink(DrawDispatch.FanUploadSink sink) { this.deferredUploadSink = sink; } + private boolean ringOverflowWarned; + + private final IntOpenHashSet pipelineZeroWarned = new IntOpenHashSet(); + private final IntOpenHashSet noRpWarned = new IntOpenHashSet(); + private final IntOpenHashSet cullAllWarned = new IntOpenHashSet(); + private final IntOpenHashSet dummyVboZeroWarned = new IntOpenHashSet(); + private final IntOpenHashSet staleFboWarned = new IntOpenHashSet(); + private final LongOpenHashSet bogusScissorWarned = new LongOpenHashSet(); + private final IntOpenHashSet pushUniformsNullCbWarned = new IntOpenHashSet(); + + public PipelineApplier(FrameManager frameManager, ResourceManager resourceManager, ShaderManager shaderManager, PipelineStore pipelineStore, FBOClearTracker fboClearTracker, PersistentBufferSync persistentSync, SamplerBinder samplerBinder, StorageTextureBinder storageTextureBinder, StorageBufferBinder storageBufferBinder) { + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + this.pipelineStore = pipelineStore; + this.fboClearTracker = fboClearTracker; + this.persistentSync = persistentSync; + this.samplerBinder = samplerBinder; + this.storageTextureBinder = storageTextureBinder; + this.storageBufferBinder = storageBufferBinder; + } + + public void ensureRenderPass(ContextState st) { + ensureRenderPass(st, frameManager.frame()); + } + + public void ensureRenderPass(ContextState st, FrameState f) { + if (!f.frameActive) return; + + fboClearTracker.flushPendingClearsForBoundSamplers(st); + + if (!st.deferUploads) { + persistentSync.uploadDirtyPersistentRegion(); + } else if (++st.drawsSincePersistentDrain >= PERSISTENT_DRAIN_INTERVAL) { + st.drawsSincePersistentDrain = 0; + persistentSync.enqueueDirtyPersistentRegions(); + } + + if (!st.deferUploads && f.renderPass != 0 && st.attribDefaultsDirtyMask != 0 && (st.attribDefaultsDirtyMask & ~st.currentVao.attribEnabledMask) != 0) { + frameManager.endRenderPassIfActive(f); + } + + if (f.renderPass != 0 && st.anyUniformBlockDirty()) { + frameManager.endRenderPassIfActive(f); + if (Tracy.ENABLED) frameManager.notePerFrameBlockPassBreak(); + } + + if (st.boundFboId == 0) { + if (st.pendingSwapchainClear) { + frameManager.ensureSwapchainRenderPass(f, st.pendingSwapchainR, st.pendingSwapchainG, st.pendingSwapchainB, st.pendingSwapchainA, true); + st.pendingSwapchainClear = false; + } else { + frameManager.ensureSwapchainRenderPass(f, st.clearR, st.clearG, st.clearB, st.clearA, false); + } + return; + } + + final FboState fbo = resourceManager.getFbo(st.boundFboId); + if (fbo == null) { + LOG.error("ensureRenderPass: FBO {} not found", st.boundFboId); + return; + } + + if (fbo.targetsDirty) fbo.recomputeTargets(); + if (!fbo.hasAnyColor && fbo.depthTexture == 0) return; + + final long primaryTarget = fbo.primaryTarget; + if (f.renderPass != 0 && f.activeLayoutHash == fbo.structuralLayoutHash && f.currentColorTarget == primaryTarget && f.currentDepthTarget == fbo.depthTexture && !FBOClearTracker.fboHasPendingClear(st, fbo)) { + return; + } + + final int totalTargets = fbo.drawBuffers.length; + final long dummyTex = totalTargets > 0 ? resourceManager.getOrCreateDummyColorTarget() : 0L; + + int proposedClearOps = 0; + long layoutHash = Hashing.fmix64(0xA5A5A5A5A5A5A5A5L, totalTargets); + for (int i = 0; i < totalTargets; i++) { + final int db = fbo.drawBuffers[i]; + final long tex; + if (db >= 0 && db < ContextState.MAX_COLOR_ATTACHMENTS && fbo.colorTextures[db] != 0) { + tex = fbo.colorTextures[db]; + } else { + tex = dummyTex; + } + final boolean pendingClear = tex != dummyTex && st.pendingColorTextures.contains(tex); + final boolean firstUse = !pendingClear && tex != dummyTex && !st.clearedTexturesThisFrame.contains(tex); + if (pendingClear || firstUse) proposedClearOps |= 1 << i; + layoutHash = Hashing.fmix64(layoutHash, tex); + layoutHash = Hashing.fmix64(layoutHash, db); + } + final boolean proposedDepthClear; + if (fbo.depthTexture != 0) { + final boolean pendingClear = st.pendingDepthTextures.contains(fbo.depthTexture); + final boolean firstUse = !pendingClear && !st.clearedTexturesThisFrame.contains(fbo.depthTexture); + proposedDepthClear = pendingClear || firstUse; + layoutHash = Hashing.fmix64(layoutHash, fbo.depthTexture); + } else { + proposedDepthClear = false; + } + layoutHash = Hashing.fmix64(layoutHash, Float.floatToRawIntBits(st.clearR)); + layoutHash = Hashing.fmix64(layoutHash, Float.floatToRawIntBits(st.clearG)); + layoutHash = Hashing.fmix64(layoutHash, Float.floatToRawIntBits(st.clearB)); + layoutHash = Hashing.fmix64(layoutHash, Float.floatToRawIntBits(st.clearA)); + layoutHash = Hashing.fmix64(layoutHash, Float.floatToRawIntBits(st.depthClearValue)); + + frameManager.endRenderPassIfActive(f); + + final boolean reuse = fbo.cachedTargetsValid && fbo.cachedTargetsLayoutHash == layoutHash && fbo.cachedTargetsCount == totalTargets && fbo.cachedClearOpFlags == proposedClearOps && fbo.cachedDepthClearLast == proposedDepthClear; + + SDL_GPUColorTargetInfo.Buffer colorTargets = null; + SDL_GPUDepthStencilTargetInfo depthTarget = null; + + if (reuse) { + for (int i = 0; i < totalTargets; i++) { + final int db = fbo.drawBuffers[i]; + final long tex = (db >= 0 && db < ContextState.MAX_COLOR_ATTACHMENTS) + ? fbo.colorTextures[db] : 0L; + if (tex != 0) { + st.pendingColorTextures.remove(tex); + if ((proposedClearOps & (1 << i)) != 0) st.clearedTexturesThisFrame.add(tex); + } + } + if (fbo.depthTexture != 0) { + st.pendingDepthTextures.remove(fbo.depthTexture); + if (proposedDepthClear) st.clearedTexturesThisFrame.add(fbo.depthTexture); + } + if (totalTargets > 0) colorTargets = fbo.cachedColorTargets.position(0).limit(totalTargets); + if (fbo.depthTexture != 0) depthTarget = fbo.cachedDepthTarget; + } else { + if (totalTargets > 0) { + colorTargets = fbo.cachedColorTargets.position(0).limit(totalTargets); + for (int i = 0; i < totalTargets; i++) { + final int db = fbo.drawBuffers[i]; + final long tex; + if (db >= 0 && db < ContextState.MAX_COLOR_ATTACHMENTS && fbo.colorTextures[db] != 0) { + tex = fbo.colorTextures[db]; + } else { + tex = dummyTex; + } + final boolean pendingClear = tex != dummyTex && st.pendingColorTextures.remove(tex); + final boolean firstUse = !pendingClear && tex != dummyTex && !st.clearedTexturesThisFrame.contains(tex); + final boolean clearThis = pendingClear || firstUse; + final long ctAddr = colorTargets.address() + (long) i * SDL_GPUColorTargetInfo.SIZEOF; + MemoryAccess.putAddress(ctAddr + SDL_GPUColorTargetInfo.TEXTURE, tex); + MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.LOAD_OP, clearThis ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD); + MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.STORE_OP, db >= 0 ? SDL_GPU_STOREOP_STORE : SDL_GPU_STOREOP_DONT_CARE); + if (clearThis) { + final long ccAddr = ctAddr + SDL_GPUColorTargetInfo.CLEAR_COLOR; + if (pendingClear) { + final float[] color = st.pendingColorValues.get(tex); + MemoryAccess.putFloat(ccAddr + SDL_FColor.R, color[0]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.G, color[1]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.B, color[2]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.A, color[3]); + } else { + MemoryAccess.putFloat(ccAddr + SDL_FColor.R, st.clearR); + MemoryAccess.putFloat(ccAddr + SDL_FColor.G, st.clearG); + MemoryAccess.putFloat(ccAddr + SDL_FColor.B, st.clearB); + MemoryAccess.putFloat(ccAddr + SDL_FColor.A, st.clearA); + } + if (tex != dummyTex) st.clearedTexturesThisFrame.add(tex); + } + } + } + if (fbo.depthTexture != 0) { + final boolean pendingClear = st.pendingDepthTextures.remove(fbo.depthTexture); + final boolean firstUse = !pendingClear && !st.clearedTexturesThisFrame.contains(fbo.depthTexture); + final boolean clearDepth = pendingClear || firstUse; + depthTarget = fbo.cachedDepthTarget; + final long dtAddr = depthTarget.address(); + MemoryAccess.putAddress(dtAddr + SDL_GPUDepthStencilTargetInfo.TEXTURE, fbo.depthTexture); + MemoryAccess.putInt(dtAddr + SDL_GPUDepthStencilTargetInfo.LOAD_OP, clearDepth ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD); + MemoryAccess.putInt(dtAddr + SDL_GPUDepthStencilTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + if (clearDepth) { + final float dv = pendingClear ? st.pendingDepthValues.get(fbo.depthTexture) : st.depthClearValue; + MemoryAccess.putFloat(dtAddr + SDL_GPUDepthStencilTargetInfo.CLEAR_DEPTH, dv); + st.clearedTexturesThisFrame.add(fbo.depthTexture); + } + } + fbo.cachedTargetsLayoutHash = layoutHash; + fbo.cachedTargetsCount = totalTargets; + fbo.cachedClearOpFlags = proposedClearOps; + fbo.cachedDepthClearLast = proposedDepthClear; + fbo.cachedTargetsValid = true; + } + + frameManager.beginRenderPass(colorTargets, depthTarget); + frameManager.setActiveLayoutHash(fbo.structuralLayoutHash); + } + + private static final int RING_BLOCK_BYTES = ContextState.MAX_VERTEX_ATTRIBS * 16; + private static final int RING_CHUNK_BYTES = ResourceManager.ATTRIB_RING_CHUNK_BLOCKS * RING_BLOCK_BYTES; + + private void advanceAttribDefaultsRing(ContextState st) { + final long dummyVBO = resourceManager.getOrCreateDummyVertexBuffer(); + if (dummyVBO == 0) return; + if (st.ringChunkStaging == null) { + st.ringChunkStaging = MemoryUtil.memAlloc(RING_CHUNK_BYTES); + } + if (st.ringChunkBaseOffset == 0) { + st.ringChunkBaseOffset = resourceManager.nextAttribRingChunkOffset(); + st.ringChunkUsedBlocks = 0; + } + final int blockInChunk = st.ringChunkUsedBlocks * RING_BLOCK_BYTES; + st.ringChunkStaging.position(blockInChunk); + st.ringChunkStaging.asFloatBuffer().put(st.attribDefaults, 0, ContextState.MAX_VERTEX_ATTRIBS * 4); + st.attribDefaultsRingBase = st.ringChunkBaseOffset + blockInChunk; + st.ringChunkUsedBlocks++; + if (st.ringChunkUsedBlocks == ResourceManager.ATTRIB_RING_CHUNK_BLOCKS) { + flushAttribRingChunk(st); + } + st.attribDefaultsDirtyMask = 0; + st.bumpAttribStateGen(); + if (++st.ringAdvancesThisFrame >= ResourceManager.ATTRIB_RING_BLOCKS - 2 * ResourceManager.ATTRIB_RING_CHUNK_BLOCKS && !ringOverflowWarned) { + ringOverflowWarned = true; + LOG.warn("Attrib-defaults ring wrapped within one frame ({} advances); earlier draws may read overwritten blocks", st.ringAdvancesThisFrame); + } + } + + public void flushAttribRingChunk(ContextState st) { + if (st.ringChunkBaseOffset == 0 || st.ringChunkUsedBlocks == 0) { + st.ringChunkBaseOffset = 0; + return; + } + final long dummyVBO = resourceManager.getOrCreateDummyVertexBuffer(); + if (dummyVBO != 0 && deferredUploadSink != null) { + st.ringChunkStaging.position(0).limit(st.ringChunkUsedBlocks * RING_BLOCK_BYTES); + deferredUploadSink.enqueuePreCopied(st.ringChunkStaging, dummyVBO, st.ringChunkBaseOffset, false); + st.ringChunkStaging.clear(); + } + st.ringChunkBaseOffset = 0; + st.ringChunkUsedBlocks = 0; + } + + public boolean applyPipelineAndState(ContextState st) { + return applyPipelineAndState(st, frameManager.frame()); + } + + public boolean applyPipelineAndState(ContextState st, FrameState f) { + if (!Tracy.FINE_ZONES) { + return applyPipelineAndStateImpl(st, f); + } + Tracy.beginZone(Z_SDL_APPLY_STATE); + try { + return applyPipelineAndStateImpl(st, f); + } finally { + Tracy.endZone(); + } + } + + private boolean applyPipelineAndStateImpl(ContextState st, FrameState f) { + if (Tracy.ENABLED) frameManager.noteStateApply(); + if (SystemProperties.SDL_VERIFY_STATE_SYNC && Thread.currentThread() == GLStateManager.getMainThread()) { + StateSyncVerifier.verify( + GLStateManager.getBoundVAO(), st.boundVAO, + GLStateManager.getDrawFramebuffer(), st.boundFboId, + GLStateManager.getReadFramebuffer(), st.boundReadFboId, + GLStateManager.getActiveTextureUnit(), st.activeTextureUnit); + } + final long rp = f.renderPass; + final long rpGeneration = f.renderPassGeneration; + if (rp == 0) { + if (noRpWarned.add(st.boundProgram)) { + LOG.warn("applyPipelineAndState: rp==0 for boundProgram={} boundFbo={}; draw skipped", st.boundProgram, st.boundFboId); + } + return false; + } + if (st.pipeline.cullEnabled && st.pipeline.cullAll) { + if (cullAllWarned.add(st.boundProgram)) { + LOG.warn("applyPipelineAndState: cullAll for boundProgram={} cullFaceMode=0x{}; draw skipped", st.boundProgram, Integer.toHexString(st.pipeline.cullFaceMode)); + } + return false; + } + + if (st.attribDefaultsDirtyMask != 0 && st.deferUploads && deferredUploadSink != null) { + advanceAttribDefaultsRing(st); + } + + final long rpGen = f.renderPassGeneration; + if (rpGen != st.lastAppliedRenderPassGen) { + st.lastAppliedRenderPassGen = rpGen; + st.viewportDirty = true; + st.scissorDirty = true; + st.blendColorDirty = true; + st.lastBoundPipeline = 0; + st.lastAppliedStencilRef = Integer.MIN_VALUE; + st.lastBoundEboHandle = 0; + st.lastBoundEboIndexSize = -1; + st.lastAppliedSamplerBindGen = -1; + st.lastAppliedSamplerProgram = 0; + st.lastFragSamplerProgram = 0; + st.lastVertSamplerProgram = 0; + st.lastAppliedStorageTexBindGen = -1; + st.lastAppliedStorageTexProgram = 0; + st.lastFragStorageTexProgram = 0; + st.lastVertStorageTexProgram = 0; + st.lastAppliedStorageBufBindGen = -1; + st.lastAppliedStorageBufProgram = 0; + st.lastFragStorageBufProgram = 0; + st.lastVertStorageBufProgram = 0; + st.lastAppliedVboBindGen = -1; + st.lastAppliedVboBindProgram = 0; + st.lastAppliedVboBindCb = 0; + } + + final boolean renderingToFbo = st.boundFboId != 0; + final FboState fboState = renderingToFbo ? resourceManager.getFbo(st.boundFboId) : null; + if (renderingToFbo && fboState == null && staleFboWarned.add(st.boundFboId)) { + LOG.warn("applyPipelineAndState: boundFboId={} but FboState is null - bound FBO was deleted; draws will use viewport-derived fallback height", st.boundFboId); + } + final long pipeline = st.pipeline.getOrCreatePipeline(pipelineStore, st, renderingToFbo); + if (pipeline == 0) { + if (pipelineZeroWarned.add(st.boundProgram)) { + LOG.warn("applyPipelineAndState: pipeline==0 for boundProgram={} vs={} fs={} inputMask=0x{}; draw skipped", + st.boundProgram, st.pipeline.vertexShader, st.pipeline.fragmentShader, + Integer.toHexString(st.pipeline.shaderInputMask)); + } + return false; + } + if (pipeline != st.lastBoundPipeline) { + if (Tracy.ENABLED) frameManager.noteBatchBreakPipeline(); + SDL_BindGPUGraphicsPipeline(rp, pipeline); + st.lastBoundPipeline = pipeline; + st.lastAppliedSamplerProgram = 0; + st.lastAppliedSamplerCb = 0; + st.lastAppliedStorageTexProgram = 0; + st.lastAppliedStorageTexCb = 0; + st.lastAppliedStorageBufProgram = 0; + st.lastAppliedStorageBufCb = 0; + } + + if (st.viewportDirty) { + float vpY = st.viewportY; + float vpH = st.viewportH; + if (renderingToFbo) { + vpY = st.viewportY + st.viewportH; + vpH = -st.viewportH; + } + final long addr = st.cachedViewport.address(); + MemoryAccess.putFloat(addr + SDL_GPUViewport.X, st.viewportX); + MemoryAccess.putFloat(addr + SDL_GPUViewport.Y, vpY); + MemoryAccess.putFloat(addr + SDL_GPUViewport.W, st.viewportW); + MemoryAccess.putFloat(addr + SDL_GPUViewport.H, vpH); + MemoryAccess.putFloat(addr + SDL_GPUViewport.MIN_DEPTH, st.viewportDepthNear); + MemoryAccess.putFloat(addr + SDL_GPUViewport.MAX_DEPTH, st.viewportDepthFar); + SDL_SetGPUViewport(rp, st.cachedViewport); + st.viewportDirty = false; + } + + if (st.scissorDirty) { + final long addr = st.cachedScissor.address(); + final int sx, sy, sw, sh; + final int fbHeight; + if (st.scissorEnabled) { + if (renderingToFbo) { + fbHeight = (fboState != null && fboState.height > 0) ? fboState.height : (int)(st.viewportY + st.viewportH); + } else { + fbHeight = (int)(st.viewportY + st.viewportH); + } + sx = st.scissorX; + sy = fbHeight - st.scissorY - st.scissorH; + sw = st.scissorW; + sh = st.scissorH; + MemoryAccess.putInt(addr + SDL_Rect.X, sx); + MemoryAccess.putInt(addr + SDL_Rect.Y, sy); + MemoryAccess.putInt(addr + SDL_Rect.W, sw); + MemoryAccess.putInt(addr + SDL_Rect.H, sh); + if ((sw <= 0 || sh <= 0) && bogusScissorWarned.add(Hashing.packHiLo(sw, sh))) { + LOG.warn("applyPipelineAndState: scissor degenerate (x={} y={} w={} h={}) - all fragments clipped; boundProgram={} boundFbo={} fbHeight={} scissorEn={} src=[{},{},{},{}]", sx, sy, sw, sh, st.boundProgram, st.boundFboId, fbHeight, st.scissorEnabled, st.scissorX, st.scissorY, st.scissorW, st.scissorH); + } + } else { + MemoryAccess.putInt(addr + SDL_Rect.X, (int) st.viewportX); + MemoryAccess.putInt(addr + SDL_Rect.Y, (int) st.viewportY); + MemoryAccess.putInt(addr + SDL_Rect.W, (int) st.viewportW); + MemoryAccess.putInt(addr + SDL_Rect.H, (int) st.viewportH); + } + SDL_SetGPUScissor(rp, st.cachedScissor); + st.scissorDirty = false; + } + + if (st.blendColorDirty) { + final long addr = st.cachedBlendColor.address(); + MemoryAccess.putFloat(addr + SDL_FColor.R, st.blendColorR); + MemoryAccess.putFloat(addr + SDL_FColor.G, st.blendColorG); + MemoryAccess.putFloat(addr + SDL_FColor.B, st.blendColorB); + MemoryAccess.putFloat(addr + SDL_FColor.A, st.blendColorA); + SDL_SetGPUBlendConstants(rp, st.cachedBlendColor); + st.blendColorDirty = false; + } + + if (st.pipeline.effectiveStencilTestEnabled() && st.stencilRef != st.lastAppliedStencilRef) { + SDL_SetGPUStencilReference(rp, (byte) st.stencilRef); + st.lastAppliedStencilRef = st.stencilRef; + } + + final int shaderMask = st.pipeline.shaderInputMask; + final ContextState.VAOState vao = st.currentVao; + final int usedMask = shaderMask | vao.attribEnabledMask; + final long applyCb = frameManager.getCommandBuffer(f); + if (usedMask != 0 && (st.attribStateGen != st.lastAppliedVboBindGen || st.boundProgram != st.lastAppliedVboBindProgram || applyCb != st.lastAppliedVboBindCb)) { + final int maxSlot = 31 - Integer.numberOfLeadingZeros(usedMask); + final long dummyVBO = resourceManager.getOrCreateDummyVertexBuffer(); + if (dummyVBO == 0) { + if (dummyVboZeroWarned.add(st.boundProgram)) { + LOG.warn("applyPipelineAndState: getOrCreateDummyVertexBuffer()==0 for boundProgram={}; draw skipped", st.boundProgram); + } + return false; + } + final int bindingSize = SDL_GPUBufferBinding.SIZEOF; + final int validRange = (1 << (maxSlot + 1)) - 1; + + int rem = ~vao.attribEnabledMask & validRange; + while (rem != 0) { + final int i = Integer.numberOfTrailingZeros(rem); + rem &= rem - 1; + final long elemAddr = st.vboBindingsAddr + (long) i * bindingSize; + MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, dummyVBO); + MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, st.attribDefaultsRingBase + i * 16); + } + + int enabled = vao.attribEnabledMask & validRange; + while (enabled != 0) { + final int i = Integer.numberOfTrailingZeros(enabled); + enabled &= enabled - 1; + final int b = vao.attribBinding[i]; + final long vboHandle = resourceManager.getBufferHandle(vao.bindingBuffer[b]); + final long elemAddr = st.vboBindingsAddr + (long) i * bindingSize; + if (vboHandle != 0) { + MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, vboHandle); + MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, (int) vao.bindingOffset[b]); + } else { + MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, dummyVBO); + MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, i * 16); + } + } + + nSDL_BindGPUVertexBuffers(rp, 0, st.vboBindingsAddr, maxSlot + 1); + st.lastAppliedVboBindGen = st.attribStateGen; + st.lastAppliedVboBindProgram = st.boundProgram; + st.lastAppliedVboBindCb = applyCb; + } + + if (Tracy.ENABLED && st.boundProgram != 0 + && (st.boundProgram != st.lastAppliedSamplerProgram || st.samplerBindGen != st.lastAppliedSamplerBindGen || applyCb != st.lastAppliedSamplerCb)) { + frameManager.noteBatchBreakSampler(); + } + samplerBinder.bindSamplers(rp, st, applyCb); + storageTextureBinder.bindStorageTextures(rp, st, applyCb); + storageBufferBinder.bindStorageBuffers(rp, st, applyCb); + + if (st.boundProgram != 0) pushUniforms(rp, st, f); + + if (SystemProperties.SDL_ENCODER_ASSERTIONS && f.renderPassGeneration != rpGeneration) { + final String msg = "render pass ended during applyPipelineAndState (generation " + rpGeneration + " -> " + f.renderPassGeneration + "); the captured pass handle is dead"; + if (SystemProperties.SDL_ENCODER_ASSERTIONS_FATAL) throw new IllegalStateException(msg); + LOG.error(msg); + } + + return true; + } + + public void pushUniforms(long renderPass, ContextState st) { + pushUniforms(renderPass, st, frameManager.frame()); + } + + public void pushUniforms(long renderPass, ContextState st, FrameState f) { + if (!Tracy.FINE_ZONES) { + pushUniformsImpl(renderPass, st, f); + return; + } + Tracy.beginZone(Z_SDL_PUSH_UNIFORMS); + try { + pushUniformsImpl(renderPass, st, f); + } finally { + Tracy.endZone(); + } + } + + private void pushUniformsImpl(long renderPass, ContextState st, FrameState f) { + final ShaderManager.ProgramObject prog = st.boundProgramObj; + if (prog == null) return; + final long cb = frameManager.getCommandBuffer(f); + if (cb == 0) { + if (pushUniformsNullCbWarned.add(st.boundProgram)) { + LOG.warn("pushUniforms: getCommandBuffer()==0 for boundProgram={}; uniforms not pushed", st.boundProgram); + } + return; + } + final int program = st.boundProgram; + if (prog.externalUboBinding >= 0) { + pushExternalUboBlock(cb, st, prog, program); + return; + } + final UniformStaging us = st.uniformStaging(prog); + final boolean vsNeeds = us.vsUniformBuf != null && (us.vsUniformDirty || cb != st.lastPushedCbVs || program != st.lastPushedProgramVs); + final boolean fsNeeds = us.fsUniformBuf != null && (us.fsUniformDirty || cb != st.lastPushedCbFs || program != st.lastPushedProgramFs); + if (!vsNeeds && !fsNeeds) { + if (Tracy.ENABLED) frameManager.noteUniformPushSkipped(); + return; + } + if (vsNeeds) { + us.vsUniformBuf.position(0).limit(prog.vertexUboSize); + SDL_PushGPUVertexUniformData(cb, 0, us.vsUniformBuf); + us.vsUniformDirty = false; + st.lastPushedCbVs = cb; + st.lastPushedProgramVs = program; + if (Tracy.ENABLED) frameManager.noteUniformPushBytes(prog.vertexUboSize); + } + if (fsNeeds) { + us.fsUniformBuf.position(0).limit(prog.fragmentUboSize); + SDL_PushGPUFragmentUniformData(cb, 0, us.fsUniformBuf); + us.fsUniformDirty = false; + st.lastPushedCbFs = cb; + st.lastPushedProgramFs = program; + if (Tracy.ENABLED) frameManager.noteUniformPushBytes(prog.fragmentUboSize); + } + } + + private void pushExternalUboBlock(long cb, ContextState st, ShaderManager.ProgramObject prog, int program) { + final int binding = prog.externalUboBinding; + if (binding < 0 || binding >= ContextState.MAX_INDEXED_BUFFERS) return; + final int gen = st.uboRangeGen; + final boolean vsNeeds = prog.vertexUboSize > 0 && (gen != st.lastPushedUboGenVs || cb != st.lastPushedCbVs || program != st.lastPushedProgramVs); + final boolean fsNeeds = prog.fragmentUboSize > 0 && (gen != st.lastPushedUboGenFs || cb != st.lastPushedCbFs || program != st.lastPushedProgramFs); + if (!vsNeeds && !fsNeeds) { + if (Tracy.ENABLED) frameManager.noteExternalUboPushSkipped(); + return; + } + if (vsNeeds) { + final long addr = uboRangeAddress(st, binding, prog.vertexUboSize); + if (addr != 0L) { + if (Tracy.ENABLED) frameManager.noteExternalUboPush(); + nSDL_PushGPUVertexUniformData(cb, 0, addr, prog.vertexUboSize); + st.lastPushedCbVs = cb; + st.lastPushedProgramVs = program; + st.lastPushedUboGenVs = gen; + if (Tracy.ENABLED) frameManager.noteUniformPushBytes(prog.vertexUboSize); + } + } + if (fsNeeds) { + final long addr = uboRangeAddress(st, binding, prog.fragmentUboSize); + if (addr != 0L) { + if (Tracy.ENABLED) frameManager.noteExternalUboPush(); + nSDL_PushGPUFragmentUniformData(cb, 0, addr, prog.fragmentUboSize); + st.lastPushedCbFs = cb; + st.lastPushedProgramFs = program; + st.lastPushedUboGenFs = gen; + if (Tracy.ENABLED) frameManager.noteUniformPushBytes(prog.fragmentUboSize); + } + } + } + + private long uboRangeAddress(ContextState st, int binding, int size) { + final int glId = st.boundUboByIndex[binding]; + if (glId == 0) return 0L; + final int offset = st.uboRangeOffset[binding]; + final PersistentMapping pm = resourceManager.getPersistentMapping(glId); + if (pm != null) { + if (offset < 0 || offset + size > pm.staging.capacity()) return 0L; + return MemoryUtil.memAddress0(pm.staging) + offset; + } + final ByteBuffer shadow = resourceManager.getUboShadow(glId); + if (shadow != null) { + if (offset < 0 || offset + size > shadow.capacity()) return 0L; + return MemoryUtil.memAddress0(shadow) + offset; + } + return 0L; + } + + public float[] reuseOrAlloc(ContextState st, int location, int length) { + final ShaderManager.ProgramObject prog = st.boundProgramObj; + if (prog != null && location >= 0 && location < prog.uniformSlotCount) { + final float[] existing = st.uniformStaging(prog).uniformDataBySlot[location]; + if (existing != null && existing.length == length) return existing; + } + return new float[length]; + } + + public void putUniformFv(ContextState st, int location, FloatBuffer value) { + final ShaderManager.ProgramObject prog = st.boundProgramObj; + if (prog == null || location < 0 || location >= prog.uniformSlotCount) return; + final int n = value.remaining(); + final int pos = value.position(); + final float[] existing = st.uniformStaging(prog).uniformDataBySlot[location]; + if (existing != null && existing.length == n) { + if (contentEquals(existing, value, pos, n)) { + return; + } + value.get(pos, existing); + putUniform(st, location, existing); + return; + } + final float[] v = new float[n]; + value.get(pos, v); + putUniform(st, location, v); + } + + static boolean contentEquals(float[] existing, FloatBuffer value, int pos, int n) { + for (int i = 0; i < n; i++) { + if (Float.floatToRawIntBits(existing[i]) != Float.floatToRawIntBits(value.get(pos + i))) return false; + } + return true; + } + + public void flushUniformBlocks(ContextState st) { + for (int b = 0; b < ShaderManager.BLOCK_COUNT; b++) { + flushUniformBlock(st, b); + } + } + + private void flushUniformBlock(ContextState st, int b) { + final ContextState.UniformBlockState block = st.uniformBlocks[b]; + final int size = block.size; + if (size == 0) return; + if (block.glId == 0 || block.allocSize < size) { + block.glId = resourceManager.genBuffer(); + resourceManager.createBuffer(block.glId, SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ, size); + block.allocSize = size; + + st.boundSsboByIndex[ShaderManager.BLOCK_BINDINGS[b]] = block.glId; + st.ssboBindGen++; + + block.staging(size); + block.dirty = true; + } + + if (!block.dirty) return; + final ByteBuffer bytes = block.bytes(); + if (bytes == null) return; + final long handle = resourceManager.getBufferHandle(block.glId); + if (handle == 0) return; + final long copyPass = frameManager.ensureCopyPass(); + if (copyPass == 0) return; + + bytes.position(0).limit(Math.min(size, bytes.capacity())); + + resourceManager.uploadToBuffer(copyPass, bytes, handle, 0, true); + frameManager.endCopyPassIfActive(); + block.dirty = false; + block.flushedThisFrame = true; + if (Tracy.ENABLED) frameManager.noteUniformBlockFlush(b, size); + } + + private static final boolean VERIFY_PER_FRAME_BLOCK = SystemProperties.SDL_VERIFY_PER_FRAME_UNIFORM_BLOCK; + private final HashSet perFrameBlockDriftWarned = new HashSet<>(); + + private void notePerFrameBlockDrift(ShaderManager.ProgramObject prog, int location) { + final String name = prog.locationToName.getOrDefault(location, "?"); + if (perFrameBlockDriftWarned.add(name)) { + LOG.warn("per-frame block member '{}' changed after this frame's upload; it is not frame-global and must be excluded from the block", name); + } + } + + public void putUniform(ContextState st, int location, float[] data) { + final ShaderManager.ProgramObject prog = st.boundProgramObj; + if (prog == null || location < 0 || location >= prog.uniformSlotCount) return; + final UniformStaging us = st.uniformStaging(prog); + final int len = data.length; + final long valueKey; + if (len == 1) { + valueKey = Float.floatToRawIntBits(data[0]) & 0xFFFFFFFFL; + } else if (len == 2) { + valueKey = Hashing.packHiLo(Float.floatToRawIntBits(data[1]), Float.floatToRawIntBits(data[0])); + } else { + valueKey = Hashing.hashFloats(data); + } + if (Tracy.ENABLED) st.slotWrites++; + if (us.uniformValueHashBySlot[location] == valueKey) { + final float[] existing = us.uniformDataBySlot[location]; + if (existing == data) { + if (Tracy.ENABLED) st.slotWritesElided++; + return; + } + if (existing != null && existing.length == len && Arrays.equals(existing, data)) { + us.uniformDataBySlot[location] = data; + if (Tracy.ENABLED) st.slotWritesElided++; + return; + } + } + us.uniformDataBySlot[location] = data; + us.uniformValueHashBySlot[location] = valueKey; + for (int b = 0; b < ShaderManager.BLOCK_COUNT; b++) { + final ShaderManager.UniformMemberInfo info = prog.blockInfoBySlot[b][location]; + if (info == null) continue; + final ContextState.UniformBlockState block = st.uniformBlocks[b]; + if (prog.blockSize[b] > block.size) block.size = prog.blockSize[b]; + final FloatBuffer blockFb = block.staging(prog.blockSize[b]); + + final int hashSlot = block.hashSlot(info.offset()); + if (hashSlot >= 0) { + if (block.hash(hashSlot) == valueKey) { + if (Tracy.ENABLED) st.slotWritesElided++; + return; + } + block.setHash(hashSlot, valueKey); + } + writeMember(st, prog, blockFb, prog.blockSize[b], info, data, location, false); + block.dirty = true; + if (VERIFY_PER_FRAME_BLOCK && b == ShaderManager.BLOCK_PER_FRAME && block.flushedThisFrame) { + notePerFrameBlockDrift(prog, location); + } + return; + } + final ShaderManager.UniformMemberInfo vs = prog.vsInfoBySlot[location]; + if (vs != null && us.vsUniformFb != null) { + writeMember(st, prog, us.vsUniformFb, prog.vertexUboSize, vs, data, location, true); + us.vsUniformDirty = true; + } + final ShaderManager.UniformMemberInfo fs = prog.fsInfoBySlot[location]; + if (fs != null && us.fsUniformFb != null) { + writeMember(st, prog, us.fsUniformFb, prog.fragmentUboSize, fs, data, location, false); + us.fsUniformDirty = true; + } + } + + public void storeMatrix(ContextState st, int location, boolean transpose, FloatBuffer value, int size) { + if (location < 0) return; + final int n = value.remaining(); + final int floatsPerMatrix = size * size; + final int count = n / floatsPerMatrix; + if (count == 0) { + final float[] v = reuseOrAlloc(st, location, n); + value.get(value.position(), v); + putUniform(st, location, v); + return; + } + final float[] out = reuseOrAlloc(st, location, count * floatsPerMatrix); + MatrixMarshal.marshalMatrixToColumnMajor(value, value.position(), count, size, transpose, out, 0); + putUniform(st, location, out); + } + + private void writeMember(ContextState st, ShaderManager.ProgramObject prog, FloatBuffer ubo, int uboSize, ShaderManager.UniformMemberInfo info, float[] data, int loc, boolean isVs) { + final int floatsPerElement = info.vectorSize() * info.columns(); + if (floatsPerElement <= 0) return; + final int srcCount = data.length / floatsPerElement; + if (srcCount <= 0) return; + final int dataBytes = srcCount * floatsPerElement * 4; + final int avail = uboSize - info.offset(); + if (dataBytes > avail) { + throw new IllegalStateException("Uniform overflows UBO: prog=" + st.boundProgram + " loc=" + loc + " name='" + prog.locationToName.getOrDefault(loc, "?") + "' dataBytes=" + dataBytes + " availFromOffset=" + avail + " stage=" + (isVs ? "VS" : "FS")); + } + Std140Writer.write(ubo, info, data, srcCount); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java new file mode 100644 index 000000000..a7bb15068 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java @@ -0,0 +1,935 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.sdl.SDL_GPUColorTargetDescription; +import org.lwjgl.sdl.SDL_GPUDepthStencilState; +import org.lwjgl.sdl.SDL_GPUGraphicsPipelineCreateInfo; +import org.lwjgl.sdl.SDL_GPUGraphicsPipelineTargetInfo; +import org.lwjgl.sdl.SDL_GPUMultisampleState; +import org.lwjgl.sdl.SDL_GPURasterizerState; +import org.lwjgl.sdl.SDL_GPUVertexAttribute; +import org.lwjgl.sdl.SDL_GPUVertexBufferDescription; +import org.lwjgl.sdl.SDL_GPUVertexInputState; +import org.lwjgl.sdl.SDLError; +import com.gtnewhorizons.angelica.glsm.GLTypes; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.PixelOps; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.UscaledRetype; + +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.IntToLongFunction; +import java.util.function.LongSupplier; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.*; + +public final class PipelineCache { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final Tracy.ZoneId Z_SDL_PIPELINE_CREATE = Tracy.zoneId("sdlPipelineCreate", Tracy.COLOR_CLIENT); + + private static final long OUTPUT_SEED = 0x9E3779B97F4A7C15L; + private static final long SHADER_SEED = 0xBB67AE8584CAA73BL; + private static final long INPUT_SEED = 0x3C6EF372FE94F82BL; + + public int keyRecomputes; + public int fastPathHits; + + private long lastKey; + private long lastPipeline; + + private boolean outputDirty = true; + private boolean shaderDirty = true; + private boolean inputDirty = true; + + private long cachedOutputHash; + private long cachedShaderHash; + private long cachedInputHash; + + public int primitiveType = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + + public final boolean[] blendEnabledPerAttachment = new boolean[ContextState.MAX_COLOR_ATTACHMENTS]; + public int srcColorFactor = SDL_GPU_BLENDFACTOR_ONE; + public int dstColorFactor = SDL_GPU_BLENDFACTOR_ZERO; + public int srcAlphaFactor = SDL_GPU_BLENDFACTOR_ONE; + public int dstAlphaFactor = SDL_GPU_BLENDFACTOR_ZERO; + public int colorBlendOp = SDL_GPU_BLENDOP_ADD; + public int alphaBlendOp = SDL_GPU_BLENDOP_ADD; + + public boolean depthTestEnabled; + public boolean depthWriteEnabled = true; + public int depthCompareOp = SDL_GPU_COMPAREOP_LESS; + + public boolean stencilTestEnabled; + public boolean effectiveStencilTestEnabled() { + return stencilTestEnabled && hasDepthTarget && PixelOps.isDepthStencilFormat(depthTargetFormat); + } + public int stencilFrontCompareOp = SDL_GPU_COMPAREOP_ALWAYS; + public int stencilFrontFailOp = SDL_GPU_STENCILOP_KEEP; + public int stencilFrontDepthFailOp = SDL_GPU_STENCILOP_KEEP; + public int stencilFrontPassOp = SDL_GPU_STENCILOP_KEEP; + public int stencilBackCompareOp = SDL_GPU_COMPAREOP_ALWAYS; + public int stencilBackFailOp = SDL_GPU_STENCILOP_KEEP; + public int stencilBackDepthFailOp = SDL_GPU_STENCILOP_KEEP; + public int stencilBackPassOp = SDL_GPU_STENCILOP_KEEP; + public int stencilCompareMask = 0xFF; + public int stencilWriteMask = 0xFF; + + public boolean cullEnabled = false; + public int cullFaceMode = SDL_GPU_CULLMODE_BACK; + public int frontFace = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + public boolean cullAll = false; + + public int getEffectiveCullMode() { + return cullEnabled ? cullFaceMode : SDL_GPU_CULLMODE_NONE; + } + public int fillMode = SDL_GPU_FILLMODE_FILL; + public float depthBiasConstant; + public float depthBiasSlopeFactor; + public float depthBiasClamp; + + public int colorWriteMask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A; + + public long vertexShader; + public long fragmentShader; + public int programId; + public int maxFragOutputLocation = -1; + private int debugFboId; + private int debugFboAttachments; + + public void setFboDebug(int fboId, int colorAttachmentCount) { + this.debugFboId = fboId; + this.debugFboAttachments = colorAttachmentCount; + } + + private static volatile int[] swapchainFormats; + + public static void setSwapchainFormats(int[] formats) { + swapchainFormats = formats; + } + + private int[] colorTargetFormats; + public int depthTargetFormat; + public boolean hasDepthTarget; + + public void setColorTargetFormats(int[] formats) { + this.colorTargetFormats = formats != null && formats.length > 0 ? formats : null; + } + + private int[] colorTargetFormats() { + final int[] explicit = colorTargetFormats; + if (explicit != null) return explicit; + final int[] swapchain = swapchainFormats; + if (swapchain == null) throw new IllegalStateException("pipeline built before the swapchain format was known"); + return swapchain; + } + + private int[] drawBuffers; + + public void setDrawBuffers(int[] drawBuffers) { + this.drawBuffers = drawBuffers; + } + + private int attachmentForSlot(int slot) { + final int[] db = drawBuffers; + if (db == null || slot < 0 || slot >= db.length) return 0; + final int idx = db[slot]; + return (idx >= 0 && idx < ContextState.MAX_COLOR_ATTACHMENTS) ? idx : 0; + } + + private boolean blendEnabledForSlot(int slot) { + return blendEnabledPerAttachment[attachmentForSlot(slot)]; + } + + public int maxAttribs; + + private static final int[] EMPTY_INT = new int[0]; + private static final String[] EMPTY_STR = new String[0]; + + public int shaderInputMask; + public int[] shaderInputVecSize = EMPTY_INT; + public int[] shaderInputBaseType = EMPTY_INT; + public String[] shaderInputName = EMPTY_STR; + + public PipelineCache() { + this.maxAttribs = ContextState.MAX_VERTEX_ATTRIBS; + } + + public void markInputDirty() { inputDirty = true; lastKey = 0L; } + + public boolean markInputDirtyIfLivenessChanged(PipelineStore store, int oldBuffer, int newBuffer) { + final IntToLongFunction resolver = store.bufferHandleResolver(); + if (resolver == null) return false; + if ((resolver.applyAsLong(oldBuffer) == 0L) == (resolver.applyAsLong(newBuffer) == 0L)) return false; + markInputDirty(); + return true; + } + + public void markOutputDirty() { outputDirty = true; lastKey = 0L; } + public void markShaderDirty() { shaderDirty = true; lastKey = 0L; } + + public void invalidateShaderHandles() { + vertexShader = 0; + fragmentShader = 0; + programId = 0; + markShaderDirty(); + } + + private boolean zeroShaderWarned; + + private boolean buildFlipFrontFace; + private int effectiveFrontFace() { + if (!buildFlipFrontFace) return frontFace; + return (frontFace == SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE) + ? SDL_GPU_FRONTFACE_CLOCKWISE : SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + } + + public long getOrCreatePipeline(PipelineStore store, ContextState cs, boolean fboFlipFrontFace) { + if (this.buildFlipFrontFace != fboFlipFrontFace) { + this.buildFlipFrontFace = fboFlipFrontFace; + this.outputDirty = true; + this.lastKey = 0L; + } + return getOrCreatePipeline(store, cs); + } + + public long getOrCreatePipeline(PipelineStore store, ContextState cs) { + if (vertexShader == 0 || fragmentShader == 0) { + if (!zeroShaderWarned) { + zeroShaderWarned = true; + LOG.warn("PipelineCache.getOrCreatePipeline: vs={} fs={} - one or both shaders missing, returning 0", vertexShader, fragmentShader); + } + return 0; + } + final long lk = lastKey; + if (lk != 0L && !outputDirty && !shaderDirty && !inputDirty) { + final long lp = lastPipeline; + if (lp != 0L) { + if (Tracy.ENABLED) fastPathHits++; + return lp; + } + } + if (Tracy.ENABLED) keyRecomputes++; + final long key = currentKey(store, cs); + if (key == lastKey && lastPipeline != 0L) return lastPipeline; + builder.store = store; + builder.cs = cs; + final long hit = store.getOrBuild(key, builder); + if (hit != 0L) { + lastPipeline = hit; + lastKey = key; + } + return hit; + } + + private final Builder builder = new Builder(); + + private final class Builder implements LongSupplier { + PipelineStore store; + ContextState cs; + + @Override + public long getAsLong() { + return createPipeline(store, cs); + } + } + + private long currentKey(PipelineStore store, ContextState cs) { + if (outputDirty) { cachedOutputHash = computeOutputHash(); outputDirty = false; } + if (shaderDirty) { cachedShaderHash = computeShaderHash(); shaderDirty = false; } + if (inputDirty) { cachedInputHash = computeInputHash(store, cs); inputDirty = false; } + return cachedOutputHash ^ cachedShaderHash ^ cachedInputHash; + } + + public long computeKey(PipelineStore store, ContextState cs) { + return computeOutputHash() ^ computeShaderHash() ^ computeInputHash(store, cs); + } + + private long computeOutputHash() { + final boolean depthOn = depthTestEnabled && hasDepthTarget; + final boolean depthWriteOn = depthOn && depthWriteEnabled; + final boolean stencilOn = effectiveStencilTestEnabled(); + final int ctfLen = colorTargetFormats().length; + int blendBits = 0; + for (int i = 0; i < ctfLen && i < 32; i++) { + if (blendEnabledForSlot(i)) blendBits |= 1 << i; + } + final long bits = + ((depthOn ? 1L : 0L) << 1) + | ((depthWriteOn ? 1L : 0L) << 2) + | ((stencilOn ? 1L : 0L) << 3) + | ((hasDepthTarget ? 1L : 0L) << 4) + | (((long) blendBits & 0xFFFFFFFFL) << 32); + long h = OUTPUT_SEED; + h = Hashing.fmix64(h, bits); + h = Hashing.fmix64(h, Hashing.packHiLo(primitiveType, srcColorFactor)); + h = Hashing.fmix64(h, Hashing.packHiLo(dstColorFactor, srcAlphaFactor)); + h = Hashing.fmix64(h, Hashing.packHiLo(dstAlphaFactor, colorBlendOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(alphaBlendOp, depthCompareOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(stencilFrontCompareOp, stencilFrontFailOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(stencilFrontDepthFailOp, stencilFrontPassOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(stencilBackCompareOp, stencilBackFailOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(stencilBackDepthFailOp, stencilBackPassOp)); + h = Hashing.fmix64(h, Hashing.packHiLo(stencilCompareMask, stencilWriteMask)); + h = Hashing.fmix64(h, Hashing.packHiLo(getEffectiveCullMode(), effectiveFrontFace())); + h = Hashing.fmix64(h, Hashing.packHiLo(fillMode, colorWriteMask)); + h = Hashing.fmix64(h, Hashing.packHiLo(Float.floatToRawIntBits(depthBiasConstant), Float.floatToRawIntBits(depthBiasSlopeFactor))); + h = Hashing.fmix64(h, Float.floatToRawIntBits(depthBiasClamp)); + h = Hashing.fmix64(h, Hashing.packHiLo(ctfLen, hasDepthTarget ? depthTargetFormat : 0)); + for (int i = 0; i < ctfLen; i++) { + h = Hashing.fmix64(h, colorTargetFormats()[i]); + } + return h; + } + + private long computeShaderHash() { + long h = SHADER_SEED; + h = Hashing.fmix64(h, vertexShader); + h = Hashing.fmix64(h, fragmentShader); + h = Hashing.fmix64(h, programId); + return h; + } + + private long computeInputHash(PipelineStore store, ContextState cs) { + long h = INPUT_SEED; + h = Hashing.fmix64(h, Hashing.packHiLo(shaderInputMask, maxAttribs)); + if (cs == null) return h; + final ContextState.VAOState vao = cs.currentVao; + final int sibtLen = shaderInputBaseType.length; + final int sivsLen = shaderInputVecSize.length; + + for (int i = 0; i < maxAttribs; i++) { + if ((shaderInputMask & (1 << i)) == 0) continue; + if (attribLive(store, cs, vao, i)) { + final int b = vao.attribBinding[i]; + final long w0 = + ((long) i & 0xFF) + | (((long) vao.attribSize[i] & 0xFF) << 8) + | (((long) vao.attribType[i] & 0xFFFFL) << 16) + | ((vao.attribNormalized[i] ? 1L : 0L) << 32) + | ((vao.attribIsInteger[i] ? 1L : 0L) << 33) + | (((long) b & 0xFF) << 40) + | (((long) vao.attribStride[i] & 0xFFFFL) << 48); + final long w1 = + ((long) vao.attribRelativeOffset[i] & 0xFFFFL) + | (((long) vao.bindingStride[b] & 0xFFFFL) << 16) + | (((long) vao.bindingDivisor[b] & 0xFFFFL) << 32) + | ((i < sibtLen ? (long) shaderInputBaseType[i] & 0xFFFFL : 0L) << 48); + h = Hashing.fmix64(h, w0); + h = Hashing.fmix64(h, w1); + } else if (i < sivsLen) { + h = Hashing.fmix64(h, Hashing.packHiLo(i, shaderInputVecSize[i])); + } + } + return h; + } + + private static final LongOpenHashSet loggedUnconsumedFragOutput = new LongOpenHashSet(); + + private void warnOnceOnUnconsumedFragOutput(int numColorTargets) { + if (maxFragOutputLocation < numColorTargets) return; + if (!loggedUnconsumedFragOutput.add(Hashing.packHiLo(programId, numColorTargets))) return; + LOG.warn("[PipelineCache] program {} declares fragment output location {} but framebuffer {} ({} colour attachment(s)) has {} draw buffer(s) {}; writes past location {} are discarded", programId, maxFragOutputLocation, debugFboId, debugFboAttachments, numColorTargets, Arrays.toString(drawBuffers), numColorTargets - 1); + } + + private long createPipeline(PipelineStore store, ContextState cs) { + if (Tracy.ENABLED) Tracy.beginZone(Z_SDL_PIPELINE_CREATE); + try { + return createPipelineInner(store, cs); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private long createPipelineInner(PipelineStore store, ContextState cs) { + if (vertexShader == 0 || fragmentShader == 0) { + return 0; + } + + try (var stack = stackPush()) { + final int numColorTargets = colorTargetFormats().length; + warnOnceOnUnconsumedFragOutput(numColorTargets); + final SDL_GPUColorTargetDescription.Buffer colorDesc = SDL_GPUColorTargetDescription.calloc(numColorTargets, stack); + for (int i = 0; i < numColorTargets; i++) { + final var desc = colorDesc.get(i); + desc.format(colorTargetFormats()[i]); + desc.blend_state() + .enable_blend(blendEnabledForSlot(i)) + .src_color_blendfactor(srcColorFactor) + .dst_color_blendfactor(dstColorFactor) + .color_blend_op(colorBlendOp) + .src_alpha_blendfactor(srcAlphaFactor) + .dst_alpha_blendfactor(dstAlphaFactor) + .alpha_blend_op(alphaBlendOp) + .color_write_mask((byte) colorWriteMask) + .enable_color_write_mask(true); + } + + final boolean depthOn = depthTestEnabled && hasDepthTarget; + final boolean stencilOn = effectiveStencilTestEnabled(); + final SDL_GPUDepthStencilState depthStencil = SDL_GPUDepthStencilState.calloc(stack) + .enable_depth_test(depthOn) + .enable_depth_write(depthOn && depthWriteEnabled) + .compare_op(depthCompareOp) + .enable_stencil_test(stencilOn) + .compare_mask((byte) stencilCompareMask) + .write_mask((byte) stencilWriteMask); + if (stencilOn) { + depthStencil.front_stencil_state() + .fail_op(stencilFrontFailOp) + .pass_op(stencilFrontPassOp) + .depth_fail_op(stencilFrontDepthFailOp) + .compare_op(stencilFrontCompareOp); + depthStencil.back_stencil_state() + .fail_op(stencilBackFailOp) + .pass_op(stencilBackPassOp) + .depth_fail_op(stencilBackDepthFailOp) + .compare_op(stencilBackCompareOp); + } + + final SDL_GPURasterizerState rasterizer = SDL_GPURasterizerState.calloc(stack) + .cull_mode(getEffectiveCullMode()) + .front_face(effectiveFrontFace()) + .fill_mode(fillMode) + .depth_bias_constant_factor(depthBiasConstant) + .depth_bias_slope_factor(depthBiasSlopeFactor) + .depth_bias_clamp(depthBiasClamp); + + final SDL_GPUMultisampleState multisample = SDL_GPUMultisampleState.calloc(stack) + .sample_count(SDL_GPU_SAMPLECOUNT_1); + + final SDL_GPUGraphicsPipelineTargetInfo targetInfo = SDL_GPUGraphicsPipelineTargetInfo.calloc(stack) + .num_color_targets(numColorTargets) + .color_target_descriptions(colorDesc); + if (hasDepthTarget) { + targetInfo.depth_stencil_format(depthTargetFormat) + .has_depth_stencil_target(true); + } + + final SDL_GPUVertexInputState vertexInput = SDL_GPUVertexInputState.calloc(stack); + final VertexInputResult vi = buildVertexInput(store, cs, stack); + if (vi == null) return PipelineStore.BAD_PIPELINE_SENTINEL; + if (vi.numAttributes() > 0) { + vertexInput + .num_vertex_buffers(vi.numBuffers()) + .vertex_buffer_descriptions(vi.bindings()) + .num_vertex_attributes(vi.numAttributes()) + .vertex_attributes(vi.attrs()); + } + + final SDL_GPUGraphicsPipelineCreateInfo ci = SDL_GPUGraphicsPipelineCreateInfo.calloc(stack) + .vertex_shader(vi.vertexShaderOverride() != 0L ? vi.vertexShaderOverride() : vertexShader) + .fragment_shader(fragmentShader) + .primitive_type(primitiveType) + .rasterizer_state(rasterizer) + .multisample_state(multisample) + .depth_stencil_state(depthStencil) + .target_info(targetInfo) + .vertex_input_state(vertexInput); + + final long pipeline = SDL_CreateGPUGraphicsPipeline(store.device().getDevice(), ci); + if (pipeline == 0) { + final int diagInputMask = computeInputMask(); + logPipelineCreateFailure(cs, diagInputMask, Integer.bitCount(diagInputMask), depthOn, stencilOn); + return PipelineStore.BAD_PIPELINE_SENTINEL; + } + LOG.debug("Pipeline created: {}", pipeline); + return pipeline; + } + } + + private void logPipelineCreateFailure(ContextState cs, int inputMask, int totalInputs, boolean depthOn, boolean stencilOn) { + final String sdlErr = SDLError.SDL_GetError(); + final int boundProgram = cs != null ? cs.boundProgram : -1; + final StringBuilder sb = new StringBuilder(2048); + sb.append("Failed to create graphics pipeline (D3D12/Vulkan/Metal PSO rejected):\n"); + sb.append(" SDL error: ").append(sdlErr).append('\n'); + sb.append(" Program: boundProgram=").append(boundProgram) + .append(" vs=0x").append(Long.toHexString(vertexShader)) + .append(" fs=0x").append(Long.toHexString(fragmentShader)).append('\n'); + sb.append(" Primitive: type=").append(primitiveType).append('\n'); + sb.append(" Targets: numColor=").append(colorTargetFormats().length) + .append(" hasDepth=").append(hasDepthTarget) + .append(" depthFormat=").append(depthTargetFormat) + .append(" (").append(textureFormatName(depthTargetFormat)).append(")\n"); + for (int i = 0; i < colorTargetFormats().length; i++) { + sb.append(" color[").append(i).append("]: format=").append(colorTargetFormats()[i]) + .append(" (").append(textureFormatName(colorTargetFormats()[i])).append(")\n"); + } + sb.append(" Sample count: 1\n"); + sb.append(" Depth/stencil: depthOn=").append(depthOn) + .append(" rawDepthTest=").append(depthTestEnabled) + .append(" rawDepthWrite=").append(depthWriteEnabled) + .append(" compareOp=").append(depthCompareOp) + .append(" stencilOn=").append(stencilOn).append('\n'); + if (stencilOn) { + sb.append(" Stencil: cmpMask=0x").append(Integer.toHexString(stencilCompareMask)) + .append(" wrMask=0x").append(Integer.toHexString(stencilWriteMask)) + .append(" frontCmp=").append(stencilFrontCompareOp) + .append(" backCmp=").append(stencilBackCompareOp).append('\n'); + } + sb.append(" Blend: enabled=").append(blendEnabledForSlot(0)) + .append(" srcColor=").append(srcColorFactor).append(" dstColor=").append(dstColorFactor).append(" colorOp=").append(colorBlendOp) + .append(" srcAlpha=").append(srcAlphaFactor).append(" dstAlpha=").append(dstAlphaFactor).append(" alphaOp=").append(alphaBlendOp) + .append(" mask=0x").append(Integer.toHexString(colorWriteMask)).append('\n'); + sb.append(" Rasterizer: cull=").append(getEffectiveCullMode()) + .append(" front=").append(effectiveFrontFace()) + .append(" fill=").append(fillMode) + .append(" biasConst=").append(depthBiasConstant) + .append(" biasSlope=").append(depthBiasSlopeFactor) + .append(" biasClamp=").append(depthBiasClamp).append('\n'); + sb.append(" ShaderInputs: mask=0x").append(Integer.toHexString(shaderInputMask)) + .append(" baseTypes=").append(intArrayToString(shaderInputBaseType)) + .append(" vecSizes=").append(intArrayToString(shaderInputVecSize)).append('\n'); + sb.append(" VertexInput: totalInputs=").append(totalInputs) + .append(" inputMask=0x").append(Integer.toHexString(inputMask)).append('\n'); + final ContextState.VAOState vao = (cs != null) ? cs.currentVao : null; + final int dumpMask = inputMask | (vao != null ? vao.attribEnabledMask : 0); + for (int i = 0; i < maxAttribs; i++) { + if ((dumpMask & (1 << i)) == 0) continue; + final boolean enabled = vao != null && vao.attribEnabled[i]; + final boolean shaderExpects = (shaderInputMask & (1 << i)) != 0; + if (enabled) { + final int b = vao.attribBinding[i]; + final int boundStride = vao.bindingStride[b]; + final int stride = boundStride != 0 ? boundStride : (vao.attribStride[i] != 0 ? vao.attribStride[i] : vao.attribSize[i] * GLTypes.sizeBytes(vao.attribType[i])); + int fmt = mapVertexFormat(vao.attribSize[i], vao.attribType[i], vao.attribNormalized[i], vao.attribIsInteger[i]); + if (i < shaderInputBaseType.length) fmt = correctSignedness(fmt, shaderInputBaseType[i]); + final String tag = shaderExpects ? "VAO-enabled" : "VAO-enabled shader-extra (dropped)"; + sb.append(" attr[loc=").append(i).append("] ").append(tag).append(':') + .append(" size=").append(vao.attribSize[i]) + .append(" type=0x").append(Integer.toHexString(vao.attribType[i])) + .append(" norm=").append(vao.attribNormalized[i]) + .append(" iPtr=").append(vao.attribIsInteger[i]) + .append(" relOff=").append(vao.attribRelativeOffset[i]) + .append(" stride=").append(stride) + .append(" divisor=").append(vao.bindingDivisor[b]) + .append(" sdlFmt=").append(fmt) + .append(" (").append(vertexFormatName(fmt)).append(")\n"); + } else if (shaderExpects) { + final int vecSize = i < shaderInputVecSize.length ? shaderInputVecSize[i] : 4; + final int fmt = mapVertexFormat(vecSize, GL11.GL_FLOAT, false, false); + sb.append(" attr[loc=").append(i).append("] expansion-default:") + .append(" vecSize=").append(vecSize) + .append(" sdlFmt=").append(fmt) + .append(" (").append(vertexFormatName(fmt)).append(")\n"); + } + } + LOG.error(sb.toString()); + } + + private static String textureFormatName(int sdlFormat) { + return switch (sdlFormat) { + case 0 -> "INVALID"; + case SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM -> "R8G8B8A8_UNORM"; + case SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM -> "B8G8R8A8_UNORM"; + case SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB -> "R8G8B8A8_UNORM_SRGB"; + case SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB -> "B8G8R8A8_UNORM_SRGB"; + case SDL_GPU_TEXTUREFORMAT_R8_UNORM -> "R8_UNORM"; + case SDL_GPU_TEXTUREFORMAT_R8G8_UNORM -> "R8G8_UNORM"; + case SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT -> "R16G16B16A16_FLOAT"; + case SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT -> "R32G32B32A32_FLOAT"; + case SDL_GPU_TEXTUREFORMAT_D16_UNORM -> "D16_UNORM"; + case SDL_GPU_TEXTUREFORMAT_D24_UNORM -> "D24_UNORM"; + case SDL_GPU_TEXTUREFORMAT_D32_FLOAT -> "D32_FLOAT"; + case SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT -> "D24_UNORM_S8_UINT"; + case SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT -> "D32_FLOAT_S8_UINT"; + default -> "format#" + sdlFormat; + }; + } + + private static String vertexFormatName(int sdlFormat) { + return switch (sdlFormat) { + case SDL_GPU_VERTEXELEMENTFORMAT_INVALID -> "INVALID"; + case SDL_GPU_VERTEXELEMENTFORMAT_FLOAT -> "FLOAT"; + case SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2 -> "FLOAT2"; + case SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3 -> "FLOAT3"; + case SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4 -> "FLOAT4"; + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE2 -> "BYTE2"; + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE4 -> "BYTE4"; + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2 -> "UBYTE2"; + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4 -> "UBYTE4"; + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE2_NORM -> "BYTE2_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE4_NORM -> "BYTE4_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2_NORM -> "UBYTE2_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM -> "UBYTE4_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT2 -> "SHORT2"; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT4 -> "SHORT4"; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT2 -> "USHORT2"; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT4 -> "USHORT4"; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT2_NORM -> "SHORT2_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT4_NORM -> "SHORT4_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT2_NORM -> "USHORT2_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT4_NORM -> "USHORT4_NORM"; + case SDL_GPU_VERTEXELEMENTFORMAT_HALF2 -> "HALF2"; + case SDL_GPU_VERTEXELEMENTFORMAT_HALF4 -> "HALF4"; + case SDL_GPU_VERTEXELEMENTFORMAT_INT -> "INT"; + case SDL_GPU_VERTEXELEMENTFORMAT_INT2 -> "INT2"; + case SDL_GPU_VERTEXELEMENTFORMAT_INT3 -> "INT3"; + case SDL_GPU_VERTEXELEMENTFORMAT_INT4 -> "INT4"; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT -> "UINT"; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT2 -> "UINT2"; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT3 -> "UINT3"; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT4 -> "UINT4"; + default -> "vfmt#" + sdlFormat; + }; + } + + private static String intArrayToString(int[] arr) { + if (arr == null || arr.length == 0) return "[]"; + final StringBuilder sb = new StringBuilder(arr.length * 4 + 2); + sb.append('['); + for (int i = 0; i < arr.length; i++) { + if (i > 0) sb.append(','); + sb.append(arr[i]); + } + sb.append(']'); + return sb.toString(); + } + + private static final int GL_TYPE_BASE = GL11.GL_BYTE; + static final int INVALID_FMT = -1; + private static final int[][] VTX_FMT = buildVertexFormatTable(); + + private static int[] fmtSame(int s1, int s2, int s3, int s4) { + return new int[] { INVALID_FMT, s1, s2, s3, s4, INVALID_FMT, s1, s2, s3, s4 }; + } + + private static int[] fmt(int s1, int s2, int s3, int s4, int n1, int n2, int n3, int n4) { + return new int[] { INVALID_FMT, s1, s2, s3, s4, INVALID_FMT, n1, n2, n3, n4 }; + } + + private static int[][] buildVertexFormatTable() { + final int[][] t = new int[GL30.GL_HALF_FLOAT - GL_TYPE_BASE + 1][]; + // Float / int / uint -- all sizes 1..4 supported; normalized flag irrelevant for these + t[GL11.GL_FLOAT - GL_TYPE_BASE] = fmtSame( + SDL_GPU_VERTEXELEMENTFORMAT_FLOAT, SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, + SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4); + t[GL11.GL_INT - GL_TYPE_BASE] = fmtSame( + SDL_GPU_VERTEXELEMENTFORMAT_INT, SDL_GPU_VERTEXELEMENTFORMAT_INT2, + SDL_GPU_VERTEXELEMENTFORMAT_INT3, SDL_GPU_VERTEXELEMENTFORMAT_INT4); + t[GL11.GL_UNSIGNED_INT - GL_TYPE_BASE] = fmtSame( + SDL_GPU_VERTEXELEMENTFORMAT_UINT, SDL_GPU_VERTEXELEMENTFORMAT_UINT2, + SDL_GPU_VERTEXELEMENTFORMAT_UINT3, SDL_GPU_VERTEXELEMENTFORMAT_UINT4); + // Half float -- only sizes 2 and 4 (no HALF1/HALF3 in SDL); normalized irrelevant + t[GL30.GL_HALF_FLOAT - GL_TYPE_BASE] = fmtSame( + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_HALF2, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_HALF4); + // Byte / ushort etc -- only sizes 2 and 4; raw and normalized halves differ + t[GL11.GL_BYTE - GL_TYPE_BASE] = fmt( + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_BYTE2, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_BYTE4, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_BYTE2_NORM, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_BYTE4_NORM); + t[GL11.GL_UNSIGNED_BYTE - GL_TYPE_BASE] = fmt( + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2_NORM, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM); + t[GL11.GL_SHORT - GL_TYPE_BASE] = fmt( + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_SHORT2, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_SHORT4, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_SHORT2_NORM, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_SHORT4_NORM); + t[GL11.GL_UNSIGNED_SHORT - GL_TYPE_BASE] = fmt( + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_USHORT2, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_USHORT4, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_USHORT2_NORM, + INVALID_FMT, SDL_GPU_VERTEXELEMENTFORMAT_USHORT4_NORM); + return t; + } + + record VertexInputResult(SDL_GPUVertexBufferDescription.Buffer bindings, SDL_GPUVertexAttribute.Buffer attrs, int numBuffers, int numAttributes, long vertexShaderOverride) {} + + private static boolean isConvertibleIntegerType(int glType) { + return glType == GL11.GL_BYTE || glType == GL11.GL_UNSIGNED_BYTE || glType == GL11.GL_SHORT || glType == GL11.GL_UNSIGNED_SHORT || glType == GL11.GL_INT || glType == GL11.GL_UNSIGNED_INT; + } + + private static boolean isSignedType(int glType) { + return glType == GL11.GL_BYTE || glType == GL11.GL_SHORT || glType == GL11.GL_INT; + } + + private static int boundComponentCount(int size, int glType) { + final int typeIdx = glType - GL_TYPE_BASE; + if (typeIdx < 0 || typeIdx >= VTX_FMT.length || VTX_FMT[typeIdx] == null) return size; + if (VTX_FMT[typeIdx][size] != INVALID_FMT) return size; + return size == 1 ? 2 : 4; + } + + private boolean isCoercedAttrib(ContextState.VAOState vao, int i) { + if (vao.attribNormalized[i] || vao.attribIsInteger[i]) return false; + if (!isConvertibleIntegerType(vao.attribType[i])) return false; + if (i >= shaderInputBaseType.length) return false; + return shaderInputScalarKind(shaderInputBaseType[i]) == ScalarKind.FLOAT; + } + + private boolean attribLive(PipelineStore store, ContextState cs, ContextState.VAOState vao, int i) { + if (!vao.attribEnabled[i]) return false; + if (vao.attribType[i] == 0) { + if (store.loggedTypeZeroAttrib.add(Hashing.packHiLo(cs.boundProgram, i))) { + LOG.warn("[PipelineCache] vertex attrib location={} enabled with no pointer set (program={}); treating as disabled", i, cs.boundProgram); + } + return false; + } + final IntToLongFunction resolver = store.bufferHandleResolver(); + if (resolver != null) { + final int bindingBuffer = vao.bindingBuffer[vao.attribBinding[i]]; + if (resolver.applyAsLong(bindingBuffer) == 0) { + if (store.loggedDeadBufferAttrib.add(Hashing.packHiLo(cs.boundProgram, i))) { + LOG.warn("[PipelineCache] vertex attrib location={} enabled but binding buffer {} has no live handle (program={}); treating as disabled", i, bindingBuffer, cs.boundProgram); + } + return false; + } + } + return true; + } + + int computeInputMask() { + return shaderInputMask; + } + + VertexInputResult buildVertexInput(PipelineStore store, ContextState cs, MemoryStack stack) { + final ContextState.VAOState vao = (cs != null) ? cs.currentVao : null; + final int inputMask = computeInputMask(); + final int totalInputs = Integer.bitCount(inputMask); + if (totalInputs == 0) { + return new VertexInputResult(null, null, 0, 0, 0L); + } + + int coercedMask = 0; + long variantKey = 0L; + if (vao != null) { + for (int i = 0; i < maxAttribs; i++) { + if ((inputMask & (1 << i)) == 0) continue; + if (!attribLive(store, cs, vao, i)) continue; + if (!isCoercedAttrib(vao, i)) continue; + coercedMask |= (1 << i); + variantKey = Hashing.fmix64(variantKey, + ((long) i << 40) | ((long) vao.attribType[i] << 8) | vao.attribSize[i]); + } + } + + long variantShader = 0L; + int[] variantBaseType = null; + if (coercedMask != 0) { + final PipelineStore.VertexVariantResolver resolver = store.vertexVariantResolver(); + if (resolver != null) { + final List attribs = new ArrayList<>(Integer.bitCount(coercedMask)); + for (int i = 0; i < maxAttribs; i++) { + if ((coercedMask & (1 << i)) == 0) continue; + final String name = i < shaderInputName.length ? shaderInputName[i] : null; + if (name == null) { attribs.clear(); break; } + attribs.add(new UscaledRetype.Attrib(name, i, + i < shaderInputVecSize.length ? shaderInputVecSize[i] : 4, + boundComponentCount(vao.attribSize[i], vao.attribType[i]), + isSignedType(vao.attribType[i]))); + } + if (!attribs.isEmpty()) { + final ShaderManager.VertexVariant v = resolver.resolve(cs.boundProgram, variantKey, attribs); + if (v != null) { + variantShader = v.sdlShader; + variantBaseType = v.inputBaseType; + } + } + } + if (variantShader == 0L) { + for (int i = 0; i < maxAttribs; i++) { + if ((coercedMask & (1 << i)) == 0) continue; + warnUnconvertedAttrib(store, cs, vao, i); + } + coercedMask = 0; + } + } + + // Bindings array must stay dense, indexed by slot + final int maxSlot = 31 - Integer.numberOfLeadingZeros(inputMask); + final int numBuffers = maxSlot + 1; + final int numAttributes = numBuffers; + final SDL_GPUVertexAttribute.Buffer attrs = SDL_GPUVertexAttribute.calloc(numAttributes, stack); + final SDL_GPUVertexBufferDescription.Buffer bindings = SDL_GPUVertexBufferDescription.calloc(numBuffers, stack); + + for (int i = 0; i < numBuffers; i++) { + if ((inputMask & (1 << i)) == 0) { + bindings.get(i) + .slot(i).pitch(16) + .input_rate(SDL_GPU_VERTEXINPUTRATE_INSTANCE).instance_step_rate(0); + attrs.get(i) + .location(i).buffer_slot(i) + .format(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4) + .offset(0); + continue; + } + final boolean enabled = vao != null && attribLive(store, cs, vao, i); + + if (enabled) { + final int b = vao.attribBinding[i]; + final int boundStride = vao.bindingStride[b]; + final int stride = boundStride != 0 ? boundStride : (vao.attribStride[i] != 0 ? vao.attribStride[i] : vao.attribSize[i] * GLTypes.sizeBytes(vao.attribType[i])); + final int divisor = vao.bindingDivisor[b]; + final int relOff = vao.attribRelativeOffset[i]; + final int attribAlign = GLTypes.sizeBytes(vao.attribType[i]); + if (attribAlign > 0 && (stride % attribAlign) != 0) { + LOG.warn("[PipelineCache] unaligned vertex stride: location={} stride={} type=0x{} size={} -- attribAddress will not satisfy format alignment; fix producer", i, stride, Integer.toHexString(vao.attribType[i]), vao.attribSize[i]); + } + bindings.get(i) + .slot(i).pitch(stride) + .input_rate(divisor > 0 ? SDL_GPU_VERTEXINPUTRATE_INSTANCE : SDL_GPU_VERTEXINPUTRATE_VERTEX) + .instance_step_rate(0); + final boolean coerced = (coercedMask & (1 << i)) != 0; + int fmt = mapVertexFormat(vao.attribSize[i], vao.attribType[i], vao.attribNormalized[i], coerced || vao.attribIsInteger[i]); + final int[] baseTypes = (coerced && variantBaseType != null) ? variantBaseType : shaderInputBaseType; + if (i < baseTypes.length) { + fmt = correctSignedness(fmt, baseTypes[i]); + final ScalarKind shaderKind = shaderInputScalarKind(baseTypes[i]); + if (shaderKind != null && shaderKind != formatScalarKind(fmt)) { + final long key = Hashing.packHiLo(cs.boundProgram, i); + if (store.loggedMismatch.add(key)) { + LOG.warn("Vertex format mismatch: program={} location={} producer-format=0x{} (size={} type=0x{} norm={} iPtr={}) shader expects baseType={} vecSize={}; skipping draw", + cs.boundProgram, i, Integer.toHexString(fmt), + vao.attribSize[i], Integer.toHexString(vao.attribType[i]), + vao.attribNormalized[i], vao.attribIsInteger[i], + baseTypes[i], + i < shaderInputVecSize.length ? shaderInputVecSize[i] : -1); + } + return null; + } + } + if (attribAlign > 0) { + final int span = boundComponentCount(vao.attribSize[i], vao.attribType[i]) * attribAlign; + if (relOff + span > stride) { + final long key = Hashing.packHiLo(cs.boundProgram, i); + if (store.loggedFormatSubstitution.add(key)) { + LOG.warn("[PipelineCache] vertex attribute size promoted past the vertex: program={} location={} requested size={} type={} -> bound {} reading {} bytes at offset {} with stride {}", + cs.boundProgram, i, vao.attribSize[i], GLTypes.name(vao.attribType[i]), vertexFormatName(fmt), span, relOff, stride); + } + } + } + attrs.get(i) + .location(i).buffer_slot(i) + .format(fmt) + .offset(relOff); + } else { + final int vecSize = i < shaderInputVecSize.length ? shaderInputVecSize[i] : 4; + bindings.get(i) + .slot(i).pitch(16) // sizeof(vec4), one element + .input_rate(SDL_GPU_VERTEXINPUTRATE_INSTANCE).instance_step_rate(0); + attrs.get(i) + .location(i).buffer_slot(i) + .format(mapVertexFormat(vecSize, GL11.GL_FLOAT, false, false)) + .offset(0); + } + } + return new VertexInputResult(bindings, attrs, numBuffers, numAttributes, variantShader); + } + + private void warnUnconvertedAttrib(PipelineStore store, ContextState cs, ContextState.VAOState vao, int i) { + final long key = Hashing.packHiLo(cs.boundProgram, i); + if (!store.loggedFormatSubstitution.add(key)) return; + final int used = mapVertexFormat(vao.attribSize[i], vao.attribType[i], vao.attribNormalized[i], false); + LOG.warn("[PipelineCache] vertex attribute coerced to normalized: program={} location={} name={} requested size={} type={} normalized=false -> using {}. SDL GPU has no USCALED format and the integer-conversion variant could not be built, so the shader sees values divided by the type maximum instead of the original range. Declare the attribute GL_FLOAT, or use glVertexAttribIPointer with an integer shader input.", + cs.boundProgram, i, i < shaderInputName.length ? shaderInputName[i] : "?", vao.attribSize[i], GLTypes.name(vao.attribType[i]), vertexFormatName(used)); + } + + public static int mapVertexFormat(int size, int glType, boolean normalized, boolean isInteger) { + if (size < 1 || size > 4) { + throw new IllegalArgumentException("Invalid vertex attrib size " + size + " (must be 1-4)"); + } + if (!isInteger && !normalized && glType != GL11.GL_FLOAT && glType != GL30.GL_HALF_FLOAT) { + normalized = true; + } + final int typeIdx = glType - GL_TYPE_BASE; + if (typeIdx < 0 || typeIdx >= VTX_FMT.length || VTX_FMT[typeIdx] == null) { + throw new IllegalArgumentException("Unsupported vertex attrib GL type 0x" + Integer.toHexString(glType) + " (size=" + size + ", normalized=" + normalized + ")"); + } + final int idxBase = normalized ? 5 : 0; + int fmt = VTX_FMT[typeIdx][idxBase + size]; + if (fmt == INVALID_FMT) { + final int promoted = size == 1 ? 2 : 4; + fmt = VTX_FMT[typeIdx][idxBase + promoted]; + if (fmt == INVALID_FMT) { + throw new IllegalArgumentException("SDL GPU has no format for size=" + size + " type=0x" + Integer.toHexString(glType) + " normalized=" + normalized); + } + } + return fmt; + } + + public static int requestedVertexFormat(int size, int glType, boolean normalized) { + if (size < 1 || size > 4) return INVALID_FMT; + final int typeIdx = glType - GL_TYPE_BASE; + if (typeIdx < 0 || typeIdx >= VTX_FMT.length || VTX_FMT[typeIdx] == null) return INVALID_FMT; + return VTX_FMT[typeIdx][(normalized ? 5 : 0) + size]; + } + + /** Correct vertex format signedness to match the shader's expected base type. */ + public static int correctSignedness(int sdlFormat, int shaderBaseType) { + if (shaderBaseType == Spvc.SPVC_BASETYPE_INT32) { + return switch (sdlFormat) { + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2 -> SDL_GPU_VERTEXELEMENTFORMAT_BYTE2; + case SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4 -> SDL_GPU_VERTEXELEMENTFORMAT_BYTE4; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT2 -> SDL_GPU_VERTEXELEMENTFORMAT_SHORT2; + case SDL_GPU_VERTEXELEMENTFORMAT_USHORT4 -> SDL_GPU_VERTEXELEMENTFORMAT_SHORT4; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT -> SDL_GPU_VERTEXELEMENTFORMAT_INT; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT2 -> SDL_GPU_VERTEXELEMENTFORMAT_INT2; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT3 -> SDL_GPU_VERTEXELEMENTFORMAT_INT3; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT4 -> SDL_GPU_VERTEXELEMENTFORMAT_INT4; + default -> sdlFormat; + }; + } else if (shaderBaseType == Spvc.SPVC_BASETYPE_UINT32) { + return switch (sdlFormat) { + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE2 -> SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2; + case SDL_GPU_VERTEXELEMENTFORMAT_BYTE4 -> SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT2 -> SDL_GPU_VERTEXELEMENTFORMAT_USHORT2; + case SDL_GPU_VERTEXELEMENTFORMAT_SHORT4 -> SDL_GPU_VERTEXELEMENTFORMAT_USHORT4; + case SDL_GPU_VERTEXELEMENTFORMAT_INT -> SDL_GPU_VERTEXELEMENTFORMAT_UINT; + case SDL_GPU_VERTEXELEMENTFORMAT_INT2 -> SDL_GPU_VERTEXELEMENTFORMAT_UINT2; + case SDL_GPU_VERTEXELEMENTFORMAT_INT3 -> SDL_GPU_VERTEXELEMENTFORMAT_UINT3; + case SDL_GPU_VERTEXELEMENTFORMAT_INT4 -> SDL_GPU_VERTEXELEMENTFORMAT_UINT4; + default -> sdlFormat; + }; + } + return sdlFormat; + } + + private enum ScalarKind { FLOAT, SINT, UINT } + + private static ScalarKind formatScalarKind(int sdlFormat) { + return switch (sdlFormat) { + case SDL_GPU_VERTEXELEMENTFORMAT_INT, + SDL_GPU_VERTEXELEMENTFORMAT_INT2, + SDL_GPU_VERTEXELEMENTFORMAT_INT3, + SDL_GPU_VERTEXELEMENTFORMAT_INT4, + SDL_GPU_VERTEXELEMENTFORMAT_BYTE2, + SDL_GPU_VERTEXELEMENTFORMAT_BYTE4, + SDL_GPU_VERTEXELEMENTFORMAT_SHORT2, + SDL_GPU_VERTEXELEMENTFORMAT_SHORT4 -> ScalarKind.SINT; + case SDL_GPU_VERTEXELEMENTFORMAT_UINT, + SDL_GPU_VERTEXELEMENTFORMAT_UINT2, + SDL_GPU_VERTEXELEMENTFORMAT_UINT3, + SDL_GPU_VERTEXELEMENTFORMAT_UINT4, + SDL_GPU_VERTEXELEMENTFORMAT_UBYTE2, + SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, + SDL_GPU_VERTEXELEMENTFORMAT_USHORT2, + SDL_GPU_VERTEXELEMENTFORMAT_USHORT4 -> ScalarKind.UINT; + default -> ScalarKind.FLOAT; + }; + } + + private static ScalarKind shaderInputScalarKind(int spvcBaseType) { + if (spvcBaseType == Spvc.SPVC_BASETYPE_INT32) return ScalarKind.SINT; + if (spvcBaseType == Spvc.SPVC_BASETYPE_UINT32) return ScalarKind.UINT; + if (spvcBaseType == Spvc.SPVC_BASETYPE_FP32 || spvcBaseType == Spvc.SPVC_BASETYPE_FP16) return ScalarKind.FLOAT; + return null; + } + +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineStore.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineStore.java new file mode 100644 index 000000000..2456b7f7e --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineStore.java @@ -0,0 +1,74 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.UscaledRetype; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongIterator; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntToLongFunction; +import java.util.function.LongSupplier; + +import static org.lwjgl.sdl.SDLGPU.SDL_ReleaseGPUGraphicsPipeline; + +public final class PipelineStore { + static final long BAD_PIPELINE_SENTINEL = -1L; + + private final Device device; + private final Long2LongOpenHashMap map = new Long2LongOpenHashMap(); + private volatile IntToLongFunction bufferHandleResolver; + + final Set loggedMismatch = ConcurrentHashMap.newKeySet(); + final Set loggedTypeZeroAttrib = ConcurrentHashMap.newKeySet(); + final Set loggedDeadBufferAttrib = ConcurrentHashMap.newKeySet(); + final Set loggedFormatSubstitution = ConcurrentHashMap.newKeySet(); + + public PipelineStore(Device device) { + this.device = device; + map.defaultReturnValue(0L); + } + + Device device() { return device; } + + public void setBufferHandleResolver(IntToLongFunction resolver) { this.bufferHandleResolver = resolver; } + IntToLongFunction bufferHandleResolver() { return bufferHandleResolver; } + + public interface VertexVariantResolver { + ShaderManager.VertexVariant resolve(int program, long key, List attribs); + } + + private volatile VertexVariantResolver vertexVariantResolver; + + public void setVertexVariantResolver(VertexVariantResolver resolver) { this.vertexVariantResolver = resolver; } + VertexVariantResolver vertexVariantResolver() { return vertexVariantResolver; } + + public long getOrBuild(long key, LongSupplier builder) { + synchronized (this) { + final long hit = map.get(key); + if (hit == BAD_PIPELINE_SENTINEL) return 0L; + if (hit != 0L) return hit; + final long built = builder.getAsLong(); + if (built == BAD_PIPELINE_SENTINEL) { map.put(key, BAD_PIPELINE_SENTINEL); return 0L; } + if (built != 0L) map.put(key, built); + return built; + } + } + + public void shutdown() { + synchronized (this) { + final LongIterator it = map.values().iterator(); + while (it.hasNext()) { + final long v = it.nextLong(); + if (v != BAD_PIPELINE_SENTINEL) SDL_ReleaseGPUGraphicsPipeline(device.getDevice(), v); + } + map.clear(); + } + loggedMismatch.clear(); + loggedTypeZeroAttrib.clear(); + loggedDeadBufferAttrib.clear(); + loggedFormatSubstitution.clear(); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/VertexAttribs.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/VertexAttribs.java new file mode 100644 index 000000000..3f4b98636 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/VertexAttribs.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public final class VertexAttribs { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private final Set warnedDivisorKeys = ConcurrentHashMap.newKeySet(); + + public VertexAttribs() { + } + + public void applyVertexAttribPointer(ContextState st, int index, int size, int type, boolean normalized, boolean isInteger, int stride, long pointer) { + if (index >= ContextState.MAX_VERTEX_ATTRIBS) return; + final ContextState.VAOState vao = st.currentVao; + final int vbo = st.boundArrayBuffer; + if (vao.attribSize[index] == size && vao.attribType[index] == type && vao.attribNormalized[index] == normalized + && vao.attribIsInteger[index] == isInteger && vao.attribStride[index] == stride && vao.attribOffset[index] == pointer + && vao.attribVBO[index] == vbo && vao.attribBinding[index] == index && vao.attribRelativeOffset[index] == 0 + && vao.bindingBuffer[index] == vbo && vao.bindingOffset[index] == pointer && vao.bindingStride[index] == stride) + return; + vao.attribSize[index] = size; + vao.attribType[index] = type; + vao.attribNormalized[index] = normalized; + vao.attribIsInteger[index] = isInteger; + vao.attribStride[index] = stride; + vao.attribOffset[index] = pointer; + vao.attribVBO[index] = vbo; + vao.attribBinding[index] = index; + vao.attribRelativeOffset[index] = 0; + vao.bindingBuffer[index] = vbo; + vao.bindingOffset[index] = pointer; + vao.bindingStride[index] = stride; + st.bumpAttribStateGen(); + st.pipeline.markInputDirty(); + } + + public void warnDivisorClamp(int program, int attribIndex, int divisor) { + final long key = Hashing.packHiLo(program, attribIndex); + if (warnedDivisorKeys.add(key)) { + LOG.warn("vertexAttribDivisor(prog={}, index={}, divisor={}): clamped to 1; SDL has no step>1.", program, attribIndex, divisor); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParams.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParams.java new file mode 100644 index 000000000..8f6fe869b --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParams.java @@ -0,0 +1,52 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL44; + +public final class BufferParams { + private BufferParams() {} + + public static final int MUTABLE_STORE = -1; + + public static int resolve(int pname, long size, int glUsage, int storageFlags, boolean mapped, int accessFlags, long mapOffset, long mapLength) { + return switch (pname) { + case GL15.GL_BUFFER_SIZE -> (int) size; + case GL15.GL_BUFFER_USAGE -> glUsage; + case GL44.GL_BUFFER_IMMUTABLE_STORAGE -> storageFlags >= 0 ? GL11.GL_TRUE : GL11.GL_FALSE; + case GL44.GL_BUFFER_STORAGE_FLAGS -> storageFlags >= 0 ? storageFlags : 0; + case GL15.GL_BUFFER_MAPPED -> mapped ? GL11.GL_TRUE : GL11.GL_FALSE; + case GL15.GL_BUFFER_ACCESS -> accessBitsToEnum(mapped ? accessFlags : 0); + case GL30.GL_BUFFER_ACCESS_FLAGS -> mapped ? accessFlags : 0; + case GL30.GL_BUFFER_MAP_OFFSET -> mapped ? (int) mapOffset : 0; + case GL30.GL_BUFFER_MAP_LENGTH -> mapped ? (int) mapLength : 0; + default -> 0; + }; + } + + public static boolean isUnknownPname(int pname) { + return switch (pname) { + case GL15.GL_BUFFER_SIZE, GL15.GL_BUFFER_USAGE, GL15.GL_BUFFER_MAPPED, GL15.GL_BUFFER_ACCESS, + GL30.GL_BUFFER_ACCESS_FLAGS, GL30.GL_BUFFER_MAP_OFFSET, GL30.GL_BUFFER_MAP_LENGTH, + GL44.GL_BUFFER_IMMUTABLE_STORAGE, GL44.GL_BUFFER_STORAGE_FLAGS -> false; + default -> true; + }; + } + + public static int accessEnumToBits(int access) { + return switch (access) { + case GL15.GL_READ_ONLY -> GL30.GL_MAP_READ_BIT; + case GL15.GL_WRITE_ONLY -> GL30.GL_MAP_WRITE_BIT; + default -> GL30.GL_MAP_READ_BIT | GL30.GL_MAP_WRITE_BIT; + }; + } + + public static int accessBitsToEnum(int accessFlags) { + return switch (accessFlags & (GL30.GL_MAP_READ_BIT | GL30.GL_MAP_WRITE_BIT)) { + case GL30.GL_MAP_READ_BIT -> GL15.GL_READ_ONLY; + case GL30.GL_MAP_WRITE_BIT -> GL15.GL_WRITE_ONLY; + default -> GL15.GL_READ_WRITE; + }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FBOClearTracker.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FBOClearTracker.java new file mode 100644 index 000000000..2af9eb459 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FBOClearTracker.java @@ -0,0 +1,302 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerLookup; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.lwjgl.sdl.SDL_FColor; +import org.lwjgl.sdl.SDL_GPUColorTargetInfo; +import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo; +import org.lwjgl.system.MemoryStack; + +import java.util.Arrays; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class FBOClearTracker { + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + + public FBOClearTracker(FrameManager frameManager, ResourceManager resourceManager, ShaderManager shaderManager) { + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + } + + public static void recordPendingColorClear(ContextState st, long tex, float r, float g, float b, float a) { + float[] cur = st.pendingColorValues.get(tex); + if (cur == null) { + cur = new float[4]; + st.pendingColorValues.put(tex, cur); + } + cur[0] = r; cur[1] = g; cur[2] = b; cur[3] = a; + if (st.pendingColorTextures.add(tex)) { + st.pendingMutationGen++; + } + st.clearedTexturesThisFrame.remove(tex); + } + + public static void recordPendingDepthClear(ContextState st, long tex, float value) { + st.pendingDepthValues.put(tex, value); + if (st.pendingDepthTextures.add(tex)) { + st.pendingMutationGen++; + } + st.clearedTexturesThisFrame.remove(tex); + } + + public static boolean fboHasPendingClear(ContextState st, FboState fbo) { + if (fbo.depthTexture != 0 && st.pendingDepthTextures.contains(fbo.depthTexture)) return true; + if (st.pendingColorTextures.isEmpty()) return false; + for (int db : fbo.drawBuffers) { + if (db < 0 || db >= ContextState.MAX_COLOR_ATTACHMENTS) continue; + final long tex = fbo.colorTextures[db]; + if (tex != 0 && st.pendingColorTextures.contains(tex)) return true; + } + return false; + } + + public static void snapshotFlushGenerations(ContextState st) { + st.lastFlushedSamplerBindGen = st.samplerBindGen; + st.lastFlushedProgram = st.boundProgram; + st.lastFlushedPendingMutationGen = st.pendingMutationGen; + } + + public void flushPendingClearsForBoundSamplers(ContextState st) { + if (st.pendingColorTextures.isEmpty() && st.pendingDepthTextures.isEmpty()) return; + + if (st.lastFlushedSamplerBindGen == st.samplerBindGen && st.lastFlushedProgram == st.boundProgram && st.lastFlushedPendingMutationGen == st.pendingMutationGen) { + return; + } + + if (st.boundProgram == 0) { + snapshotFlushGenerations(st); + return; + } + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (prog == null || !prog.linked) { + snapshotFlushGenerations(st); + return; + } + + final LongArrayList colorHandles = st.samplerFlushColorHandles; + final IntArrayList colorGlIds = st.samplerFlushColorGlIds; + final LongArrayList depthHandles = st.samplerFlushDepthHandles; + final IntArrayList depthGlIds = st.samplerFlushDepthGlIds; + colorHandles.clear(); + colorGlIds.clear(); + depthHandles.clear(); + depthGlIds.clear(); + + final int fragSamplers = Math.min(prog.fragmentResources.numSamplers(), ContextState.MAX_SAMPLERS); + collectSamplerFlush(st, SamplerLookup.resolvedUnits(prog, true), fragSamplers, colorHandles, colorGlIds, depthHandles, depthGlIds); + + final int vertSamplers = Math.min(prog.vertexResources.numSamplers(), ContextState.MAX_SAMPLERS); + collectSamplerFlush(st, SamplerLookup.resolvedUnits(prog, false), vertSamplers, colorHandles, colorGlIds, depthHandles, depthGlIds); + + if (!colorHandles.isEmpty() || !depthHandles.isEmpty()) { + materializeFlush(st, colorHandles, colorGlIds, depthHandles, depthGlIds); + } + snapshotFlushGenerations(st); + } + + private void collectSamplerFlush(ContextState st, int[] samplerUnits, int samplerCount, LongArrayList colorHandles, IntArrayList colorGlIds, LongArrayList depthHandles, IntArrayList depthGlIds) { + for (int i = 0; i < samplerCount; i++) { + final int glUnit = samplerUnits[i]; + if (glUnit < 0 || glUnit >= st.boundTextures.length) continue; + final int glTexId = st.boundTextures[glUnit]; + if (glTexId == 0) continue; + final long handle = resourceManager.getTextureHandle(glTexId); + if (handle == 0) continue; + if (st.pendingColorTextures.remove(handle)) { + colorHandles.add(handle); + colorGlIds.add(glTexId); + } else if (st.pendingDepthTextures.remove(handle)) { + depthHandles.add(handle); + depthGlIds.add(glTexId); + } + } + } + + private void materializeFlush(ContextState st, LongArrayList colorHandles, IntArrayList colorGlIds, LongArrayList depthHandles, IntArrayList depthGlIds) { + frameManager.endRenderPassIfActive(); + + final int n = colorHandles.size(); + boolean[] consumed = null; + if (n > 0) { + if (st.materializeFlushConsumed.length < n) st.materializeFlushConsumed = new boolean[Math.max(n, st.materializeFlushConsumed.length * 2)]; + consumed = st.materializeFlushConsumed; + Arrays.fill(consumed, 0, n, false); + } + final int[] batchIdx = st.materializeFlushBatchIdx; + for (int i = 0; i < n; i++) { + if (consumed[i]) continue; + final ResourceManager.TextureMeta metaI = resourceManager.getTextureMeta(colorGlIds.getInt(i)); + if (metaI == null) { + consumed[i] = true; + continue; + } + final int fmt = metaI.sdlFormat(); + final int w = metaI.width(); + final int h = metaI.height(); + int batchCount = 0; + for (int j = i; j < n && batchCount < ContextState.MAX_COLOR_ATTACHMENTS; j++) { + if (consumed[j]) continue; + final ResourceManager.TextureMeta mj = (j == i) ? metaI : resourceManager.getTextureMeta(colorGlIds.getInt(j)); + if (mj == null) { consumed[j] = true; continue; } + if (mj.sdlFormat() == fmt && mj.width() == w && mj.height() == h) { + batchIdx[batchCount++] = j; + } + } + if (batchCount == 0) continue; + try (var stack = MemoryStack.stackPush()) { + final SDL_GPUColorTargetInfo.Buffer targets = SDL_GPUColorTargetInfo.calloc(batchCount, stack); + for (int k = 0; k < batchCount; k++) { + final int idx = batchIdx[k]; + final long handle = colorHandles.getLong(idx); + final float[] color = st.pendingColorValues.get(handle); + final long addr = targets.get(k).address(); + MemoryAccess.putAddress(addr + SDL_GPUColorTargetInfo.TEXTURE, handle); + MemoryAccess.putInt(addr + SDL_GPUColorTargetInfo.LOAD_OP, SDL_GPU_LOADOP_CLEAR); + MemoryAccess.putInt(addr + SDL_GPUColorTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + final long ccAddr = addr + SDL_GPUColorTargetInfo.CLEAR_COLOR; + MemoryAccess.putFloat(ccAddr + SDL_FColor.R, color[0]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.G, color[1]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.B, color[2]); + MemoryAccess.putFloat(ccAddr + SDL_FColor.A, color[3]); + st.clearedTexturesThisFrame.add(handle); + consumed[idx] = true; + } + frameManager.noteClearPass(); + frameManager.beginRenderPass(targets, null); + frameManager.endRenderPassIfActive(); + } + } + + final int dn = depthHandles.size(); + for (int i = 0; i < dn; i++) { + final long handle = depthHandles.getLong(i); + final float val = st.pendingDepthValues.get(handle); + try (var stack = MemoryStack.stackPush()) { + final SDL_GPUDepthStencilTargetInfo dt = SDL_GPUDepthStencilTargetInfo.calloc(stack); + final long addr = dt.address(); + MemoryAccess.putAddress(addr + SDL_GPUDepthStencilTargetInfo.TEXTURE, handle); + MemoryAccess.putInt(addr + SDL_GPUDepthStencilTargetInfo.LOAD_OP, SDL_GPU_LOADOP_CLEAR); + MemoryAccess.putInt(addr + SDL_GPUDepthStencilTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + MemoryAccess.putFloat(addr + SDL_GPUDepthStencilTargetInfo.CLEAR_DEPTH, val); + frameManager.noteClearPass(); + frameManager.beginRenderPass(null, dt); + frameManager.endRenderPassIfActive(); + st.clearedTexturesThisFrame.add(handle); + } + } + } + + public boolean discardPendingClearIfFullyCovered(ContextState st, long handle, int dstX, int dstY, int dstLevel, int width, int height, ResourceManager.TextureMeta meta) { + if (handle == 0 || meta == null) return false; + if (dstLevel != 0 || dstX != 0 || dstY != 0) return false; + if (width != meta.width() || height != meta.height() || meta.depth() > 1) return false; + final boolean depth = st.pendingDepthTextures.remove(handle); + final boolean color = !depth && st.pendingColorTextures.remove(handle); + if (!depth && !color) return false; + if (depth) st.pendingDepthValues.remove(handle); + else st.pendingColorValues.remove(handle); + st.clearedTexturesThisFrame.add(handle); + st.pendingMutationGen++; + return true; + } + + public void materializePendingClearForTexture(ContextState st, long handle) { + if (handle == 0) return; + if (st.pendingDepthTextures.remove(handle)) { + final float val = st.pendingDepthValues.remove(handle); + frameManager.endRenderPassIfActive(); + try (var stack = MemoryStack.stackPush()) { + final SDL_GPUDepthStencilTargetInfo dt = SDL_GPUDepthStencilTargetInfo.calloc(stack); + final long addr = dt.address(); + MemoryAccess.putAddress(addr + SDL_GPUDepthStencilTargetInfo.TEXTURE, handle); + MemoryAccess.putInt(addr + SDL_GPUDepthStencilTargetInfo.LOAD_OP, SDL_GPU_LOADOP_CLEAR); + MemoryAccess.putInt(addr + SDL_GPUDepthStencilTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + MemoryAccess.putFloat(addr + SDL_GPUDepthStencilTargetInfo.CLEAR_DEPTH, val); + frameManager.noteClearPass(); + frameManager.noteMaterializedClearPass(); + frameManager.beginRenderPass(null, dt); + frameManager.endRenderPassIfActive(); + st.clearedTexturesThisFrame.add(handle); + } + st.pendingMutationGen++; + return; + } + if (st.pendingColorTextures.remove(handle)) { + final float[] color = st.pendingColorValues.remove(handle); + frameManager.endRenderPassIfActive(); + try (var stack = MemoryStack.stackPush()) { + final SDL_GPUColorTargetInfo.Buffer targets = SDL_GPUColorTargetInfo.calloc(1, stack); + final long addr = targets.get(0).address(); + MemoryAccess.putAddress(addr + SDL_GPUColorTargetInfo.TEXTURE, handle); + MemoryAccess.putInt(addr + SDL_GPUColorTargetInfo.LOAD_OP, SDL_GPU_LOADOP_CLEAR); + MemoryAccess.putInt(addr + SDL_GPUColorTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE); + final long ccAddr = addr + SDL_GPUColorTargetInfo.CLEAR_COLOR; + MemoryAccess.putFloat(ccAddr + SDL_FColor.R, color != null ? color[0] : 0f); + MemoryAccess.putFloat(ccAddr + SDL_FColor.G, color != null ? color[1] : 0f); + MemoryAccess.putFloat(ccAddr + SDL_FColor.B, color != null ? color[2] : 0f); + MemoryAccess.putFloat(ccAddr + SDL_FColor.A, color != null ? color[3] : 0f); + frameManager.noteClearPass(); + frameManager.noteMaterializedClearPass(); + frameManager.beginRenderPass(targets, null); + frameManager.endRenderPassIfActive(); + st.clearedTexturesThisFrame.add(handle); + } + st.pendingMutationGen++; + } + } + + public void scrubPendingClearsForTexture(ContextState st, int glId) { + final long handle = resourceManager.getTextureHandle(glId); + if (handle == 0) return; + st.pendingColorTextures.remove(handle); + st.pendingColorValues.remove(handle); + st.pendingDepthTextures.remove(handle); + st.pendingDepthValues.remove(handle); + st.clearedTexturesThisFrame.remove(handle); + } + + public boolean fbosHaveSameAttachments(ContextState st, int a, int b) { + final FboState fa = resourceManager.getFbo(a); + final FboState fb = resourceManager.getFbo(b); + if (fa == null || fb == null) return false; + if (fa.depthTexture != fb.depthTexture) return false; + if (fa.depthFormat != fb.depthFormat) return false; + if (fa.colorAttachmentCount != fb.colorAttachmentCount) return false; + if (fa.drawBuffers.length != fb.drawBuffers.length) return false; + for (int i = 0; i < fa.drawBuffers.length; i++) { + if (fa.drawBuffers[i] != fb.drawBuffers[i]) return false; + } + for (int i = 0; i < ContextState.MAX_COLOR_ATTACHMENTS; i++) { + if (fa.colorTextures[i] != fb.colorTextures[i]) return false; + if (fa.colorFormats[i] != fb.colorFormats[i]) return false; + } + if (fboHasPendingClear(st, fb)) return false; + return true; + } + + public void updatePipelineCacheColorFormats(ContextState st, FboState fbo) { + final boolean reshape = fbo.cachedColorFormats == null || fbo.cachedColorFormats.length != fbo.drawBuffers.length; + if (fbo.cachedFormatsDirty || reshape) { + if (reshape) fbo.cachedColorFormats = new int[fbo.drawBuffers.length]; + final int[] formats = fbo.cachedColorFormats; + for (int i = 0; i < formats.length; i++) { + final int db = fbo.drawBuffers[i]; + formats[i] = (db >= 0 && db < ContextState.MAX_COLOR_ATTACHMENTS) ? fbo.colorFormats[db] : SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + } + fbo.cachedFormatsDirty = false; + } + st.pipeline.setColorTargetFormats(fbo.cachedColorFormats); + st.pipeline.setDrawBuffers(fbo.drawBuffers); + st.pipeline.setFboDebug(st.boundFboId, fbo.colorAttachmentCount); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FboState.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FboState.java new file mode 100644 index 000000000..c1dcab6df --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FboState.java @@ -0,0 +1,95 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.Hashing; +import org.lwjgl.sdl.SDL_GPUColorTargetInfo; +import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo; + +import static com.gtnewhorizons.angelica.sdlgpu.frame.ContextState.MAX_COLOR_ATTACHMENTS; + +public final class FboState { + public final long[] colorTextures = new long[MAX_COLOR_ATTACHMENTS]; + public final int[] colorGlIds = new int[MAX_COLOR_ATTACHMENTS]; + public final int[] colorFormats = new int[MAX_COLOR_ATTACHMENTS]; + public int colorAttachmentCount; + + public int[] drawBuffers = {0}; + public int readBufferIndex; + + public long depthTexture; + public int depthGlId; + public int depthFormat; + public int width, height; + + public int[] cachedColorFormats; + public boolean cachedFormatsDirty = true; + + public long primaryTarget; + public boolean hasAnyColor; + public boolean targetsDirty = true; + + public final SDL_GPUColorTargetInfo.Buffer cachedColorTargets = SDL_GPUColorTargetInfo.calloc(MAX_COLOR_ATTACHMENTS); + public final SDL_GPUDepthStencilTargetInfo cachedDepthTarget = SDL_GPUDepthStencilTargetInfo.calloc(); + public long cachedTargetsLayoutHash; + public long structuralLayoutHash; + public int cachedTargetsCount = -1; + public int cachedClearOpFlags; + public boolean cachedDepthClearLast; + public boolean cachedTargetsValid; + + public long getColorTexture() { return colorTextures[0]; } + public int getColorGlId() { return colorGlIds[0]; } + public int getColorFormat() { return colorFormats[0]; } + + public void recomputeTargets() { + boolean anyColor = false; + long firstColor = 0; + for (int db : drawBuffers) { + if (db >= 0 && db < MAX_COLOR_ATTACHMENTS && colorTextures[db] != 0) { + anyColor = true; + firstColor = colorTextures[db]; + break; + } + } + hasAnyColor = anyColor; + primaryTarget = anyColor ? firstColor : depthTexture; + targetsDirty = false; + + long h = Hashing.fmix64(0x9E3779B97F4A7C15L, drawBuffers.length); + for (int i = 0; i < drawBuffers.length; i++) { + final int db = drawBuffers[i]; + final long tex = (db >= 0 && db < MAX_COLOR_ATTACHMENTS) ? colorTextures[db] : 0L; + h = Hashing.fmix64(h, tex); + h = Hashing.fmix64(h, db); + } + h = Hashing.fmix64(h, depthTexture); + if (h == 0L || h == FrameManager.SWAPCHAIN_LAYOUT_HASH) h = 0xD1CE5EEDL; + structuralLayoutHash = h; + } + + public void detachColor(int colorIdx) { + if (colorIdx < 0 || colorIdx >= MAX_COLOR_ATTACHMENTS) return; + colorTextures[colorIdx] = 0L; + colorGlIds[colorIdx] = 0; + colorFormats[colorIdx] = 0; + int newCount = 0; + for (int i = 0; i < MAX_COLOR_ATTACHMENTS; i++) { + if (colorTextures[i] != 0L) newCount = i + 1; + } + colorAttachmentCount = newCount; + targetsDirty = true; + cachedFormatsDirty = true; + } + + public void detachDepth() { + depthTexture = 0L; + depthGlId = 0; + depthFormat = 0; + targetsDirty = true; + } + + public void free() { + cachedColorTargets.free(); + cachedDepthTarget.free(); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMap.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMap.java new file mode 100644 index 000000000..90949d479 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMap.java @@ -0,0 +1,207 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.glsm.GLTypes; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; +import org.lwjgl.util.spvc.Spvc; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class FormatMap { + private FormatMap() {} + + public static int mapPrimitiveType(int glMode) { + return switch (glMode) { + case GL11.GL_TRIANGLES -> SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + case GL11.GL_TRIANGLE_STRIP -> SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP; + case GL11.GL_LINES -> SDL_GPU_PRIMITIVETYPE_LINELIST; + case GL11.GL_LINE_STRIP -> SDL_GPU_PRIMITIVETYPE_LINESTRIP; + case GL11.GL_POINTS -> SDL_GPU_PRIMITIVETYPE_POINTLIST; + case GL11.GL_TRIANGLE_FAN -> SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + case GL11.GL_QUADS -> SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + default -> SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + }; + } + + public static int mapIndexElementSize(int glType) { + return switch (glType) { + case GL11.GL_UNSIGNED_SHORT -> SDL_GPU_INDEXELEMENTSIZE_16BIT; + case GL11.GL_UNSIGNED_INT -> SDL_GPU_INDEXELEMENTSIZE_32BIT; + default -> SDL_GPU_INDEXELEMENTSIZE_32BIT; + }; + } + + public static int indexElementSize(int glType) { + return GLTypes.sizeBytes(glType); + } + + public static int mapFilter(int glFilter) { + return switch (glFilter) { + case GL11.GL_NEAREST, GL11.GL_NEAREST_MIPMAP_NEAREST, GL11.GL_NEAREST_MIPMAP_LINEAR -> SDL_GPU_FILTER_NEAREST; + default -> SDL_GPU_FILTER_LINEAR; + }; + } + + public static int mapMipmapMode(int glMinFilter) { + return switch (glMinFilter) { + case GL11.GL_NEAREST_MIPMAP_NEAREST, GL11.GL_LINEAR_MIPMAP_NEAREST -> SDL_GPU_SAMPLERMIPMAPMODE_NEAREST; + case GL11.GL_NEAREST_MIPMAP_LINEAR, GL11.GL_LINEAR_MIPMAP_LINEAR -> SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; + default -> SDL_GPU_SAMPLERMIPMAPMODE_NEAREST; + }; + } + + public static boolean isMipmapMinFilter(int glMinFilter) { + return switch (glMinFilter) { + case GL11.GL_NEAREST_MIPMAP_NEAREST, + GL11.GL_LINEAR_MIPMAP_NEAREST, + GL11.GL_NEAREST_MIPMAP_LINEAR, + GL11.GL_LINEAR_MIPMAP_LINEAR -> true; + default -> false; + }; + } + + public static int mapAddressMode(int glWrap) { + return switch (glWrap) { + case GL12.GL_CLAMP_TO_EDGE -> SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + case GL14.GL_MIRRORED_REPEAT -> SDL_GPU_SAMPLERADDRESSMODE_MIRRORED_REPEAT; + default -> SDL_GPU_SAMPLERADDRESSMODE_REPEAT; + }; + } + + private static final int GEOMETRY_USAGE = SDL_GPU_BUFFERUSAGE_VERTEX | SDL_GPU_BUFFERUSAGE_INDEX | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ; + + public static int mapBufferUsage(int glTarget) { + return switch (glTarget) { + case GL15.GL_ARRAY_BUFFER -> GEOMETRY_USAGE; + case GL15.GL_ELEMENT_ARRAY_BUFFER -> GEOMETRY_USAGE; + case GL40.GL_DRAW_INDIRECT_BUFFER -> SDL_GPU_BUFFERUSAGE_INDIRECT; + case GL31.GL_UNIFORM_BUFFER -> SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ; + case GL43.GL_SHADER_STORAGE_BUFFER -> SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ + | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ + | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE + | SDL_GPU_BUFFERUSAGE_INDIRECT; + default -> SDL_GPU_BUFFERUSAGE_VERTEX | SDL_GPU_BUFFERUSAGE_INDEX | SDL_GPU_BUFFERUSAGE_INDIRECT; + }; + } + + public static int mapStencilOp(int glOp) { + return switch (glOp) { + case GL11.GL_KEEP -> SDL_GPU_STENCILOP_KEEP; + case GL11.GL_ZERO -> SDL_GPU_STENCILOP_ZERO; + case GL11.GL_REPLACE -> SDL_GPU_STENCILOP_REPLACE; + case GL11.GL_INCR -> SDL_GPU_STENCILOP_INCREMENT_AND_CLAMP; + case GL11.GL_DECR -> SDL_GPU_STENCILOP_DECREMENT_AND_CLAMP; + case GL11.GL_INVERT -> SDL_GPU_STENCILOP_INVERT; + case GL14.GL_INCR_WRAP -> SDL_GPU_STENCILOP_INCREMENT_AND_WRAP; + case GL14.GL_DECR_WRAP -> SDL_GPU_STENCILOP_DECREMENT_AND_WRAP; + default -> SDL_GPU_STENCILOP_KEEP; + }; + } + + public static int mapBlendFactor(int glFactor) { + return switch (glFactor) { + case GL11.GL_ZERO -> SDL_GPU_BLENDFACTOR_ZERO; + case GL11.GL_ONE -> SDL_GPU_BLENDFACTOR_ONE; + case GL11.GL_SRC_COLOR -> SDL_GPU_BLENDFACTOR_SRC_COLOR; + case GL11.GL_ONE_MINUS_SRC_COLOR -> SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_COLOR; + case GL11.GL_SRC_ALPHA -> SDL_GPU_BLENDFACTOR_SRC_ALPHA; + case GL11.GL_ONE_MINUS_SRC_ALPHA -> SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + case GL11.GL_DST_ALPHA -> SDL_GPU_BLENDFACTOR_DST_ALPHA; + case GL11.GL_ONE_MINUS_DST_ALPHA -> SDL_GPU_BLENDFACTOR_ONE_MINUS_DST_ALPHA; + case GL11.GL_DST_COLOR -> SDL_GPU_BLENDFACTOR_DST_COLOR; + case GL11.GL_ONE_MINUS_DST_COLOR -> SDL_GPU_BLENDFACTOR_ONE_MINUS_DST_COLOR; + case GL11.GL_SRC_ALPHA_SATURATE -> SDL_GPU_BLENDFACTOR_SRC_ALPHA_SATURATE; + case GL14.GL_CONSTANT_COLOR -> SDL_GPU_BLENDFACTOR_CONSTANT_COLOR; + case GL14.GL_ONE_MINUS_CONSTANT_COLOR -> SDL_GPU_BLENDFACTOR_ONE_MINUS_CONSTANT_COLOR; + default -> SDL_GPU_BLENDFACTOR_ONE; + }; + } + + public static int mapBlendOp(int glMode) { + return switch (glMode) { + case GL14.GL_FUNC_ADD -> SDL_GPU_BLENDOP_ADD; + case GL14.GL_FUNC_SUBTRACT -> SDL_GPU_BLENDOP_SUBTRACT; + case GL14.GL_FUNC_REVERSE_SUBTRACT -> SDL_GPU_BLENDOP_REVERSE_SUBTRACT; + case GL14.GL_MIN -> SDL_GPU_BLENDOP_MIN; + case GL14.GL_MAX -> SDL_GPU_BLENDOP_MAX; + default -> SDL_GPU_BLENDOP_ADD; + }; + } + + public static int mapCompareOp(int glFunc) { + return switch (glFunc) { + case GL11.GL_NEVER -> SDL_GPU_COMPAREOP_NEVER; + case GL11.GL_LESS -> SDL_GPU_COMPAREOP_LESS; + case GL11.GL_EQUAL -> SDL_GPU_COMPAREOP_EQUAL; + case GL11.GL_LEQUAL -> SDL_GPU_COMPAREOP_LESS_OR_EQUAL; + case GL11.GL_GREATER -> SDL_GPU_COMPAREOP_GREATER; + case GL11.GL_NOTEQUAL -> SDL_GPU_COMPAREOP_NOT_EQUAL; + case GL11.GL_GEQUAL -> SDL_GPU_COMPAREOP_GREATER_OR_EQUAL; + case GL11.GL_ALWAYS -> SDL_GPU_COMPAREOP_ALWAYS; + default -> SDL_GPU_COMPAREOP_LESS; + }; + } + + public static int mapMemberInfoToGlType(ShaderManager.UniformMemberInfo umi) { + final int base = umi.baseType(); + final int v = umi.vectorSize(); + final int c = umi.columns(); + if (base == Spvc.SPVC_BASETYPE_FP32 || base == Spvc.SPVC_BASETYPE_FP16) { + if (c == 1) return switch (v) { + case 1 -> GL11.GL_FLOAT; + case 2 -> GL20.GL_FLOAT_VEC2; + case 3 -> GL20.GL_FLOAT_VEC3; + default -> GL20.GL_FLOAT_VEC4; + }; + if (c == v) return switch (v) { + case 2 -> GL20.GL_FLOAT_MAT2; + case 3 -> GL20.GL_FLOAT_MAT3; + default -> GL20.GL_FLOAT_MAT4; + }; + return GL20.GL_FLOAT_MAT4; + } + if (base == Spvc.SPVC_BASETYPE_INT32) { + return switch (v) { + case 1 -> GL11.GL_INT; + case 2 -> GL20.GL_INT_VEC2; + case 3 -> GL20.GL_INT_VEC3; + default -> GL20.GL_INT_VEC4; + }; + } + if (base == Spvc.SPVC_BASETYPE_UINT32) { + return switch (v) { + case 1 -> GL30.GL_UNSIGNED_INT; + case 2 -> GL30.GL_UNSIGNED_INT_VEC2; + case 3 -> GL30.GL_UNSIGNED_INT_VEC3; + default -> GL30.GL_UNSIGNED_INT_VEC4; + }; + } + if (base == Spvc.SPVC_BASETYPE_BOOLEAN) { + return switch (v) { + case 1 -> GL20.GL_BOOL; + case 2 -> GL20.GL_BOOL_VEC2; + case 3 -> GL20.GL_BOOL_VEC3; + default -> GL20.GL_BOOL_VEC4; + }; + } + return GL20.GL_FLOAT_VEC4; + } + + public static int remapUnsignedIntToBool(int glType) { + return switch (glType) { + case GL11.GL_UNSIGNED_INT -> GL20.GL_BOOL; + case GL30.GL_UNSIGNED_INT_VEC2 -> GL20.GL_BOOL_VEC2; + case GL30.GL_UNSIGNED_INT_VEC3 -> GL20.GL_BOOL_VEC3; + case GL30.GL_UNSIGNED_INT_VEC4 -> GL20.GL_BOOL_VEC4; + default -> glType; + }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/Image3DClear.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/Image3DClear.java new file mode 100644 index 000000000..6dbed69ee --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/Image3DClear.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.ImageUnitBinding; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; + +public final class Image3DClear { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final String SOURCE = "angelica:sdlgpu/clear_image3d.csh"; + private static final int LOCAL_SIZE = 4; + + private int program; + private int extentLocation = -1; + private boolean failed; + + private boolean ensureProgram() { + if (program != 0) return true; + if (failed) return false; + failed = true; + + final int shader = GLStateManager.glCreateShader(GL43.GL_COMPUTE_SHADER); + if (shader == 0) return false; + try { + GLStateManager.glShaderSource(shader, ShaderLoader.getShaderSource(SOURCE)); + GLStateManager.glCompileShader(shader); + + final int created = GLStateManager.glCreateProgram(); + if (created == 0) return false; + GLStateManager.glAttachShader(created, shader); + GLStateManager.glLinkProgram(created); + if (GLStateManager.glGetProgrami(created, GL20.GL_LINK_STATUS) != GL11.GL_TRUE) { + LOG.error("3D image clear program failed to link: {}", GLStateManager.glGetProgramInfoLog(created, 4096)); + GLStateManager.glDeleteProgram(created); + return false; + } + program = created; + extentLocation = GLStateManager.glGetUniformLocation(created, "u_extent"); + failed = false; + return true; + } catch (RuntimeException e) { + LOG.error("3D image clear program could not be built; 3D images will not be cleared", e); + return false; + } finally { + GLStateManager.glDeleteShader(shader); + } + } + + public boolean clear(int glTexture, int width, int height, int depth) { + if (width <= 0 || height <= 0 || depth <= 0) return true; + if (!ensureProgram()) return false; + + final int previousProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); + final ImageUnitBinding previousImage = GLStateManager.getImageUnitBinding(0); + final ImageUnitBinding savedImage = previousImage == null ? null : previousImage.copy(); + GLStateManager.glUseProgram(program); + try { + GLStateManager.glBindImageTexture(0, glTexture, 0, true, 0, GL15.GL_WRITE_ONLY, 0); + if (extentLocation >= 0) GLStateManager.glUniform3i(extentLocation, width, height, depth); + GLStateManager.glDispatchCompute(groups(width), groups(height), groups(depth)); + } finally { + if (savedImage == null) { + GLStateManager.glBindImageTexture(0, 0, 0, true, 0, GL15.GL_WRITE_ONLY, 0); + } else { + GLStateManager.glBindImageTexture(0, savedImage.getTexture(), savedImage.getLevel(), savedImage.isLayered(), savedImage.getLayer(), savedImage.getAccess(), savedImage.getFormat()); + } + GLStateManager.glUseProgram(previousProgram); + } + return true; + } + + private static int groups(int extent) { + return (extent + LOCAL_SIZE - 1) / LOCAL_SIZE; + } + + public void delete() { + if (program != 0) { + GLStateManager.glDeleteProgram(program); + program = 0; + } + extentLocation = -1; + failed = false; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSync.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSync.java new file mode 100644 index 000000000..7eb9859de --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSync.java @@ -0,0 +1,113 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.ArrayList; + +public final class PersistentBufferSync { + public interface UploadSink { + public void enqueue(TransferThread.DeferredUpload upload); + public long nextSeq(); + } + + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final UploadSink sink; + + private static final class Snapshot { + final IntArrayList keys = new IntArrayList(); + final ArrayList vals = new ArrayList<>(); + int version = -1; + } + + private final ThreadLocal snapshotTL = ThreadLocal.withInitial(Snapshot::new); + + public PersistentBufferSync(FrameManager frameManager, ResourceManager resourceManager, UploadSink sink) { + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.sink = sink; + } + + public void onPersistentBufferWrite(int glId, long offset, long size) { + final PersistentMapping pm = resourceManager.getPersistentMapping(glId); + if (pm != null && pm.markDirty(offset, size)) { + resourceManager.trackPersistentDirty(); + } + } + + public void uploadDirtyPersistentRegion() { processDirtyPersistentRegions(false); } + public void enqueueDirtyPersistentRegions() { processDirtyPersistentRegions(true); } + + private void processDirtyPersistentRegions(boolean defer) { + if (!resourceManager.hasDirtyPersistentRegions()) return; + if (!defer && frameManager.getCommandBuffer() == 0) return; + final Snapshot snap = snapshotTL.get(); + final IntArrayList keys = snap.keys; + final ArrayList vals = snap.vals; + final int version = resourceManager.getMappingsVersion(); + if (snap.version != version) { + resourceManager.snapshotPersistentMappingsInto(keys, vals); + snap.version = version; + } + final int n = keys.size(); + for (int i = 0; i < n; i++) { + final PersistentMapping pm = vals.get(i); + if (!pm.isDirty()) continue; + final long gpuHandle = resourceManager.getBufferHandle(keys.getInt(i)); + if (gpuHandle == 0) continue; + final long claimed = pm.claimDirty(); + if (PersistentMapping.isClean(claimed)) continue; + final long off = PersistentMapping.rangeOffset(claimed); + final long size = PersistentMapping.rangeSize(claimed); + if (Tracy.ENABLED) frameManager.notePersistentDrain(); + if (defer) { + final long seq = sink.nextSeq(); + pm.lastEnqueuedSeq = seq; + sink.enqueue(TransferThread.StagingReadUpload.acquire(pm.staging, off, size, gpuHandle, off, seq, false)); + } else { + pm.staging.position((int) off).limit((int) (off + size)); + resourceManager.uploadToBuffer(frameManager.ensureCopyPass(), pm.staging, gpuHandle, off, false); + pm.staging.clear(); + } + resourceManager.clearPersistentDirty(); + } + } + + public static void mirrorPersistentCopy(ByteBuffer srcStaging, long srcOffset, ByteBuffer dstStaging, long dstOffset, long size) { + copyByteRegion(srcStaging, (int) srcOffset, dstStaging, (int) dstOffset, (int) size); + } + + public void mirrorEboShadow(int glId, ByteBuffer src, int dstOffset, int len) { + ByteBuffer shadow = resourceManager.getEboShadow(glId); + final int requiredCap = dstOffset + len; + if (shadow == null || shadow.capacity() < requiredCap) { + final int growHint; + if (dstOffset == 0) growHint = len; + else if (shadow == null) growHint = requiredCap; + else growHint = shadow.capacity() * 2; + shadow = resourceManager.getOrAllocEboShadow(glId, Math.max(requiredCap, growHint)); + } + copyByteRegion(src, src.position(), shadow, dstOffset, len); + shadow.position(0); + resourceManager.bumpEboShadowVersion(glId); + resourceManager.invalidateSplitCacheFor(glId); + } + + private static void copyByteRegion(ByteBuffer src, int srcOff, ByteBuffer dst, int dstOff, int len) { + if (src.isDirect() && dst.isDirect()) { + MemoryUtil.memCopy(MemoryUtil.memAddress(src) + srcOff, MemoryUtil.memAddress(dst) + dstOff, len); + return; + } + final ByteBuffer s = src.duplicate(); + s.position(srcOff).limit(srcOff + len); + final ByteBuffer d = dst.duplicate(); + d.position(dstOff); + d.put(s); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMapping.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMapping.java new file mode 100644 index 000000000..b7552bd1f --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMapping.java @@ -0,0 +1,48 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicLong; + +public final class PersistentMapping { + public final ByteBuffer staging; + public final long offset; + public final long length; + public final int accessFlags; + private final AtomicLong dirtyRange = new AtomicLong(CLEAN); + public static final long CLEAN = -1L; + + public volatile long lastEnqueuedSeq = 0L; + public PersistentMapping(ByteBuffer staging, long offset, long length, int accessFlags) { + this.staging = staging; + this.offset = offset; + this.length = length; + this.accessFlags = accessFlags; + } + + public static boolean isClean(long packed) { return packed == CLEAN; } + public static long rangeOffset(long packed) { return packed >>> 32; } + public static long rangeSize(long packed) { return (packed & 0xFFFFFFFFL) - (packed >>> 32); } + static long packRange(long min, long max) { return (min << 32) | (max & 0xFFFFFFFFL); } + + public boolean isDirty() { return dirtyRange.get() != CLEAN; } + + public long claimDirty() { return dirtyRange.getAndSet(CLEAN); } + + public boolean markDirty(long offset, long size) { + final long end = offset + size; + if (end <= offset) return false; + for (;;) { + final long prev = dirtyRange.get(); + final long next; + if (prev == CLEAN) { + next = packRange(offset, end); + } else { + final long min = Math.min(rangeOffset(prev), offset); + final long max = Math.max((prev & 0xFFFFFFFFL), end); + next = packRange(min, max); + if (next == prev) return false; + } + if (dirtyRange.compareAndSet(prev, next)) return prev == CLEAN; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PixelOps.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PixelOps.java new file mode 100644 index 000000000..24893e8b0 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/PixelOps.java @@ -0,0 +1,223 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.glsm.GLTypes; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class PixelOps { + private PixelOps() {} + + public static int defaultMipLevels(int width, int height) { + final int max = Math.max(1, Math.max(width, height)); + return Math.max(1, 32 - Integer.numberOfLeadingZeros(max)); + } + + public static boolean isBgraSdlFormat(int sdlFormat) { + return sdlFormat == SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM || sdlFormat == SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB; + } + + public static boolean isDepthFormat(int sdlFormat) { + return sdlFormat == SDL_GPU_TEXTUREFORMAT_D16_UNORM + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D24_UNORM + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D32_FLOAT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT; + } + + public static boolean isDepthStencilFormat(int sdlFormat) { + return sdlFormat == SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT || sdlFormat == SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT; + } + + public static int glPixelSize(int format, int type) { + final int packed = GLTypes.packedTexelBytes(type); + if (packed != 0) return packed; + final int components = switch (format) { + case GL11.GL_RED, GL11.GL_ALPHA, GL11.GL_LUMINANCE -> 1; + case GL11.GL_LUMINANCE_ALPHA -> 2; + case GL11.GL_RGB -> 3; + case GL11.GL_RGBA, GL12.GL_BGRA -> 4; + default -> 4; + }; + return components * GLTypes.sizeBytes(type); + } + + public static int sdlFormatTexelBytes(int sdlFormat) { + return switch (sdlFormat) { + case SDL_GPU_TEXTUREFORMAT_R8_UNORM, SDL_GPU_TEXTUREFORMAT_R8_SNORM, + SDL_GPU_TEXTUREFORMAT_R8_UINT, SDL_GPU_TEXTUREFORMAT_R8_INT, + SDL_GPU_TEXTUREFORMAT_A8_UNORM -> 1; + case SDL_GPU_TEXTUREFORMAT_R8G8_UNORM, SDL_GPU_TEXTUREFORMAT_R8G8_SNORM, + SDL_GPU_TEXTUREFORMAT_R16_UNORM, SDL_GPU_TEXTUREFORMAT_R16_SNORM, + SDL_GPU_TEXTUREFORMAT_R16_FLOAT, SDL_GPU_TEXTUREFORMAT_R16_UINT, + SDL_GPU_TEXTUREFORMAT_R16_INT, SDL_GPU_TEXTUREFORMAT_R8G8_UINT, + SDL_GPU_TEXTUREFORMAT_R8G8_INT, SDL_GPU_TEXTUREFORMAT_D16_UNORM -> 2; + case SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, SDL_GPU_TEXTUREFORMAT_R8G8B8A8_SNORM, + SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, SDL_GPU_TEXTUREFORMAT_R32_FLOAT, + SDL_GPU_TEXTUREFORMAT_R32_UINT, SDL_GPU_TEXTUREFORMAT_R32_INT, + SDL_GPU_TEXTUREFORMAT_R16G16_UNORM, SDL_GPU_TEXTUREFORMAT_R16G16_SNORM, + SDL_GPU_TEXTUREFORMAT_R16G16_FLOAT, SDL_GPU_TEXTUREFORMAT_R16G16_UINT, + SDL_GPU_TEXTUREFORMAT_R16G16_INT, SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT, + SDL_GPU_TEXTUREFORMAT_R8G8B8A8_INT, SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM, + SDL_GPU_TEXTUREFORMAT_R11G11B10_UFLOAT, + SDL_GPU_TEXTUREFORMAT_D24_UNORM, SDL_GPU_TEXTUREFORMAT_D32_FLOAT, + SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT -> 4; + case SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UNORM, SDL_GPU_TEXTUREFORMAT_R16G16B16A16_SNORM, + SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT, SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UINT, + SDL_GPU_TEXTUREFORMAT_R16G16B16A16_INT, SDL_GPU_TEXTUREFORMAT_R32G32_FLOAT, + SDL_GPU_TEXTUREFORMAT_R32G32_UINT, SDL_GPU_TEXTUREFORMAT_R32G32_INT, + SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT -> 8; + case SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT, SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT, + SDL_GPU_TEXTUREFORMAT_R32G32B32A32_INT -> 16; + default -> 4; + }; + } + + public static boolean isSdlFormatUnsignedInteger(int sdlFormat) { + return switch (sdlFormat) { + case SDL_GPU_TEXTUREFORMAT_R8_UINT, SDL_GPU_TEXTUREFORMAT_R16_UINT, SDL_GPU_TEXTUREFORMAT_R32_UINT, + SDL_GPU_TEXTUREFORMAT_R8G8_UINT, SDL_GPU_TEXTUREFORMAT_R16G16_UINT, + SDL_GPU_TEXTUREFORMAT_R32G32_UINT, SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT, + SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UINT, SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT -> true; + default -> false; + }; + } + + public static ByteBuffer expandToRGBA(int format, ByteBuffer src, int width, int height) { + if (src == null) return null; + final int pixelCount = width * height; + return switch (format) { + case GL11.GL_ALPHA -> { + final ByteBuffer dst = MemoryUtil.memAlloc(pixelCount * 4); + for (int i = 0; i < pixelCount; i++) { + final byte a = src.get(src.position() + i); + dst.put((byte) 0xFF).put((byte) 0xFF).put((byte) 0xFF).put(a); + } + dst.flip(); + yield dst; + } + case GL11.GL_LUMINANCE -> { + final ByteBuffer dst = MemoryUtil.memAlloc(pixelCount * 4); + for (int i = 0; i < pixelCount; i++) { + final byte l = src.get(src.position() + i); + dst.put(l).put(l).put(l).put((byte) 0xFF); + } + dst.flip(); + yield dst; + } + case GL11.GL_LUMINANCE_ALPHA -> { + final ByteBuffer dst = MemoryUtil.memAlloc(pixelCount * 4); + for (int i = 0; i < pixelCount; i++) { + final byte l = src.get(src.position() + i * 2); + final byte a = src.get(src.position() + i * 2 + 1); + dst.put(l).put(l).put(l).put(a); + } + dst.flip(); + yield dst; + } + default -> null; + }; + } + + public static ByteBuffer swapRedBlueCopy(ByteBuffer src, int width, int height) { + final int pixelCount = width * height; + final ByteBuffer dst = MemoryUtil.memAlloc(pixelCount * 4); + final int srcPos = src.position(); + for (int i = 0; i < pixelCount; i++) { + final int o = i * 4; + final byte c0 = src.get(srcPos + o); + final byte c1 = src.get(srcPos + o + 1); + final byte c2 = src.get(srcPos + o + 2); + final byte c3 = src.get(srcPos + o + 3); + dst.put(c2).put(c1).put(c0).put(c3); + } + dst.flip(); + return dst; + } + + public static void swapRedBlueIfNeeded(ByteBuffer pixels, int width, int height, boolean swap) { + if (!swap) return; + final int pos = pixels.position(); + final int pixelCount = width * height; + for (int i = 0; i < pixelCount; i++) { + final int offset = pos + i * 4; + final byte r = pixels.get(offset); + final byte b = pixels.get(offset + 2); + pixels.put(offset, b); + pixels.put(offset + 2, r); + } + pixels.position(pos); + } + + public static ByteBuffer prepareUploadBuffer(int format, int dstSdlFormat, ByteBuffer src, int width, int height) { + if (src == null) return null; + final boolean storageBgra = isBgraSdlFormat(dstSdlFormat); + final ByteBuffer expanded = expandToRGBA(format, src, width, height); + if (expanded != null) { + swapRedBlueIfNeeded(expanded, width, height, storageBgra); + return expanded; + } + final boolean sourceBgra = (format == GL12.GL_BGRA); + if (sourceBgra != storageBgra) { + return swapRedBlueCopy(src, width, height); + } + return src; + } + + public static ByteBuffer applyUnpackPixelStore(ByteBuffer src, int width, int height, int format, int type, ContextState.PixelStoreState ps) { + if (src == null || ps == null || ps.isDefault()) return src; + final int pixelBytes = glPixelSize(format, type); + if (pixelBytes <= 0) return src; + final int rowPixels = ps.unpackRowLength > 0 ? ps.unpackRowLength : width; + final int unalignedRowBytes = rowPixels * pixelBytes; + final int align = Math.max(1, ps.unpackAlignment); + final int srcStride = ((unalignedRowBytes + align - 1) / align) * align; + final int dstStride = width * pixelBytes; + final int totalDst = dstStride * height; + final ByteBuffer dst = MemoryUtil.memAlloc(totalDst); + final int basePos = src.position() + + ps.unpackSkipRows * srcStride + + ps.unpackSkipPixels * pixelBytes; + for (int row = 0; row < height; row++) { + final int srcRowPos = basePos + row * srcStride; + for (int b = 0; b < dstStride; b++) { + dst.put(row * dstStride + b, src.get(srcRowPos + b)); + } + } + dst.position(0).limit(totalDst); + return dst; + } + + public static void postProcessReadback(ByteBuffer pixels, int width, int height, int format, int srcSdlFormat, boolean flipRows) { + final int rowBytes = width * 4; + final int pos = pixels.position(); + + if (flipRows) { + final byte[] rowA = new byte[rowBytes]; + final byte[] rowB = new byte[rowBytes]; + for (int top = 0, bot = height - 1; top < bot; top++, bot--) { + pixels.position(pos + top * rowBytes); + pixels.get(rowA); + pixels.position(pos + bot * rowBytes); + pixels.get(rowB); + pixels.position(pos + top * rowBytes); + pixels.put(rowB); + pixels.position(pos + bot * rowBytes); + pixels.put(rowA); + } + } + + pixels.position(pos); + final boolean storageBgra = isBgraSdlFormat(srcSdlFormat); + final boolean requestBgra = (format == GL12.GL_BGRA); + swapRedBlueIfNeeded(pixels, width, height, storageBgra != requestBgra); + + pixels.position(pos); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadows.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadows.java new file mode 100644 index 000000000..4d028ce72 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadows.java @@ -0,0 +1,139 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDL_GPUBufferRegion; +import org.lwjgl.sdl.SDL_GPUTransferBufferCreateInfo; +import org.lwjgl.sdl.SDL_GPUTransferBufferLocation; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.stackPush; + +public final class ReadbackShadows { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final class Slot { + long transferBuffer; + int capacity; + boolean valid; + } + + private final Device device; + private final Long2ObjectOpenHashMap slots = new Long2ObjectOpenHashMap<>(); + + public ReadbackShadows(Device device) { + this.device = device; + } + + private static long key(int glId, long offset) { + return ((long) glId << 32) | (offset & 0xFFFFFFFFL); + } + + public boolean scheduleDownload(long copyPass, long srcHandle, long srcOffset, int dstGlId, long dstOffset, long size) { + if (copyPass == 0 || srcHandle == 0 || size <= 0 || size > Integer.MAX_VALUE) return false; + + final Slot slot = ensureSlot(dstGlId, dstOffset, (int) size); + if (slot == null) return false; + + try (MemoryStack stack = stackPush()) { + final SDL_GPUBufferRegion src = SDL_GPUBufferRegion.calloc(stack) + .buffer(srcHandle) + .offset((int) srcOffset) + .size((int) size); + final SDL_GPUTransferBufferLocation dst = SDL_GPUTransferBufferLocation.calloc(stack) + .transfer_buffer(slot.transferBuffer) + .offset(0); + SDL_DownloadFromGPUBuffer(copyPass, src, dst); + } + slot.valid = true; + return true; + } + + public void invalidate(int glId, long offset) { + final Slot slot = slots.get(key(glId, offset)); + if (slot != null) slot.valid = false; + } + + public boolean serve(int glId, long offset, ByteBuffer out, int len) { + final Slot slot = slots.get(key(glId, offset)); + if (slot == null || !slot.valid || slot.transferBuffer == 0 || slot.capacity < len) return false; + + final long mapped = nSDL_MapGPUTransferBuffer(device.getDevice(), slot.transferBuffer, false); + if (mapped == 0) { + LOG.error("Failed to map readback transfer buffer for glId={} offset={}: {}", glId, offset, SDLError.SDL_GetError()); + return false; + } + MemoryUtil.memCopy(mapped, MemoryUtil.memAddress(out), len); + SDL_UnmapGPUTransferBuffer(device.getDevice(), slot.transferBuffer); + out.position(out.position() + len); + return true; + } + + public boolean hasSlotsFor(int glId) { + for (long k : slots.keySet()) { + if ((int) (k >>> 32) == glId) return true; + } + return false; + } + + public void release(int glId) { + final LongArrayList doomed = new LongArrayList(); + for (long k : slots.keySet()) { + if ((int) (k >>> 32) == glId) doomed.add(k); + } + for (int i = 0; i < doomed.size(); i++) { + final Slot slot = slots.remove(doomed.getLong(i)); + if (slot != null) releaseSlot(slot); + } + } + + public void dispose() { + for (Slot slot : slots.values()) releaseSlot(slot); + slots.clear(); + } + + private Slot ensureSlot(int glId, long offset, int size) { + final long k = key(glId, offset); + Slot slot = slots.get(k); + if (slot != null && slot.capacity >= size) return slot; + + if (slot == null) { + slot = new Slot(); + slots.put(k, slot); + } else { + releaseSlot(slot); + } + + try (MemoryStack stack = stackPush()) { + final SDL_GPUTransferBufferCreateInfo ci = SDL_GPUTransferBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD) + .size(size); + slot.transferBuffer = SDL_CreateGPUTransferBuffer(device.getDevice(), ci); + } + if (slot.transferBuffer == 0) { + LOG.error("Failed to create readback transfer buffer size={}: {}", size, SDLError.SDL_GetError()); + slots.remove(k); + return null; + } + slot.capacity = size; + slot.valid = false; + return slot; + } + + private void releaseSlot(Slot slot) { + if (slot.transferBuffer != 0 && device.getDevice() != 0) { + SDL_ReleaseGPUTransferBuffer(device.getDevice(), slot.transferBuffer); + } + slot.transferBuffer = 0; + slot.capacity = 0; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java new file mode 100644 index 000000000..d812c3f57 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java @@ -0,0 +1,2255 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import java.util.function.LongConsumer; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.Hashing; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL21; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.sdl.SDL_GPUBufferCreateInfo; +import org.lwjgl.sdl.SDL_GPUSamplerCreateInfo; +import org.lwjgl.sdl.SDL_GPUTextureCreateInfo; +import org.lwjgl.sdl.SDL_GPUTransferBufferCreateInfo; +import org.lwjgl.sdl.SDL_GPUTransferBufferLocation; +import org.lwjgl.sdl.SDL_GPUBufferRegion; +import org.lwjgl.sdl.SDL_GPUTextureRegion; +import org.lwjgl.sdl.SDL_GPUTextureTransferInfo; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDL_GPUTextureLocation; +import org.lwjgl.sdl.SDLProperties; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.*; +import static org.lwjgl.system.MemoryUtil.memAlloc; +import static org.lwjgl.system.MemoryUtil.memFree; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.EBOSplitScanner; +import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerCache; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; + +/** + * GPU resource lifecycle: buffers, textures, samplers, FBO state, transfer pool. + */ +public final class ResourceManager { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private static final String D3D12_CLEAR_DEPTH_PROP = SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_DEPTH_FLOAT; + private static final String D3D12_CLEAR_STENCIL_PROP = SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_STENCIL_NUMBER; + + private final Device device; + private final FrameManager frameManager; + + private final Int2LongOpenHashMap textureHandles = new Int2LongOpenHashMap(); + private final Int2ObjectOpenHashMap textureMetas = new Int2ObjectOpenHashMap<>(); + private final IntOpenHashSet fboAttachedGlIds = new IntOpenHashSet(); + private final Int2LongOpenHashMap bufferHandles = new Int2LongOpenHashMap(); + private final Int2LongOpenHashMap bufferSizes = new Int2LongOpenHashMap(); + private final Int2IntOpenHashMap bufferUsages = new Int2IntOpenHashMap(); + private final Int2IntOpenHashMap bufferGlUsages = new Int2IntOpenHashMap(); + private final Int2IntOpenHashMap bufferStorageFlags = new Int2IntOpenHashMap(); + private final IntOpenHashSet undefinedContentBuffers = new IntOpenHashSet(); + private final Int2LongOpenHashMap samplerHandles = new Int2LongOpenHashMap(); + + private final LongOpenHashSet liveBufferHandles = new LongOpenHashSet(); + private final LongOpenHashSet liveTextureHandles = new LongOpenHashSet(); + + private final AtomicInteger nextTextureId = new AtomicInteger(1); + private final AtomicInteger nextBufferId = new AtomicInteger(1); + private final AtomicInteger nextSamplerId = new AtomicInteger(1); + private final AtomicInteger nextFboId = new AtomicInteger(1); + + private final Int2ObjectOpenHashMap vaoStates = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap persistentMappings = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap uboShadows = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap eboShadows = new Int2ObjectOpenHashMap<>(); + private final IntOpenHashSet eboShadowWanted = new IntOpenHashSet(); + private static final int MAX_ARRAY_SHADOW_BUFFER_BYTES = 8 << 20; + private final Int2ObjectOpenHashMap arrayShadows = new Int2ObjectOpenHashMap<>(); + private final IntOpenHashSet arrayShadowWanted = new IntOpenHashSet(); + private final ArrayDeque pendingFreeShadows = new ArrayDeque<>(); + private final Int2LongOpenHashMap eboShadowVersions = new Int2LongOpenHashMap(); + private long nextEboShadowVersion = 1; + + private record EboSplitKey(int glId, long version, int indexType, int sentinel) {} + private final ConcurrentHashMap splitCache = new ConcurrentHashMap<>(); + private final Int2ObjectOpenHashMap texSamplerStates = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap samplerObjectStates = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap fboStates = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap pboStagingData = new Int2ObjectOpenHashMap<>(); + + private final SamplerCache samplerCache = new SamplerCache(); + + private final ReentrantReadWriteLock handleLock = new ReentrantReadWriteLock(); + private final ReentrantReadWriteLock.ReadLock rLock = handleLock.readLock(); + private final ReentrantReadWriteLock.WriteLock wLock = handleLock.writeLock(); + + public SamplerCache samplerCache() { return samplerCache; } + + private volatile TransferThread transferThread; + public void setTransferThread(TransferThread t) { this.transferThread = t; } + + public void markFboAttachment(int glId) { fboAttachedGlIds.add(glId); } + public boolean isFboAttachment(int glId) { return fboAttachedGlIds.contains(glId); } + + private int preferredD24 = SDL_GPU_TEXTUREFORMAT_D24_UNORM; + private int preferredD24S8 = SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT; + + private static final Supplier VAO_FACTORY = ContextState.VAOState::new; + private static final Supplier TEX_SAMPLER_FACTORY = TextureSamplerState::new; + + public ResourceManager(Device device, FrameManager frameManager) { + this.device = device; + this.frameManager = frameManager; + textureHandles.defaultReturnValue(0); + bufferHandles.defaultReturnValue(0); + samplerHandles.defaultReturnValue(0); + bufferGlUsages.defaultReturnValue(GL15.GL_STATIC_DRAW); + bufferStorageFlags.defaultReturnValue(BufferParams.MUTABLE_STORE); + } + + public void cachePreferredDepthFormats() { + final long dev = device.getDevice(); + final int texType = SDL_GPU_TEXTURETYPE_2D; + final int depthUsage = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET; + + if (!SDL_GPUTextureSupportsFormat(dev, SDL_GPU_TEXTUREFORMAT_D24_UNORM, texType, depthUsage)) { + preferredD24 = SDL_GPU_TEXTUREFORMAT_D32_FLOAT; + LOG.info("D24_UNORM not supported for depth+sampler, using D32_FLOAT"); + } + if (!SDL_GPUTextureSupportsFormat(dev, SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, texType, depthUsage)) { + preferredD24S8 = SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT; + LOG.info("D24_UNORM_S8_UINT not supported for depth+sampler, using D32_FLOAT_S8_UINT"); + } + } + + public int genTexture() { + return nextTextureId.getAndIncrement(); + } + + public long createTexture(int glId, int glTarget, int glFormat, int width, int height, int depth, int levels) { + final int sdlFormat = mapTextureFormat(glFormat); + return createTextureCore(glId, glTarget, sdlFormat, glFormat, width, height, depth, levels, defaultUsage(sdlFormat)); + } + + public long createTexture(int glId, int glTarget, int glFormat, int width, int height, int depth, int levels, int usage) { + return createTextureCore(glId, glTarget, mapTextureFormat(glFormat), glFormat, width, height, depth, levels, usage); + } + + public long createTextureWithSdlFormat(int glId, int glTarget, int sdlFormat, int glFormat, int width, int height, int depth, int levels) { + return createTextureCore(glId, glTarget, sdlFormat, glFormat, width, height, depth, levels, defaultUsage(sdlFormat)); + } + + public long createTextureWithSdlFormat(int glId, int glTarget, int sdlFormat, int glFormat, int width, int height, int depth, int levels, int usage) { + return createTextureCore(glId, glTarget, sdlFormat, glFormat, width, height, depth, levels, usage); + } + + private static int defaultUsage(int sdlFormat) { + if (isDepthFormat(sdlFormat)) { + return SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; + } + if (isIntegerFormat(sdlFormat)) { + return SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ + | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE + | SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ; + } + return SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; + } + + private long createTextureCore(int glId, int glTarget, int sdlFormat, int glFormat, int width, int height, int depth, int levels, int usage) { + usage = reconcileUsageAndWarn(glId, usage); + final int sdlType = mapTextureType(glTarget); + if (!SDL_GPUTextureSupportsFormat(device.getDevice(), sdlFormat, sdlType, usage)) { + final int fallback = findSupportedDepthFallback(sdlFormat, sdlType, usage); + if (fallback != sdlFormat) { + LOG.info("Format 0x{} unsupported for usage 0x{}, falling back to 0x{}", Integer.toHexString(sdlFormat), Integer.toHexString(usage), Integer.toHexString(fallback)); + sdlFormat = fallback; + } else { + LOG.error("No supported format found for GL format 0x{} usage 0x{}", Integer.toHexString(glFormat), Integer.toHexString(usage)); + } + } + + final int dCount = Math.max(1, depth); + final int lCount = Math.max(1, levels); + try (var stack = stackPush()) { + final SDL_GPUTextureCreateInfo ci = SDL_GPUTextureCreateInfo.calloc(stack) + .type(sdlType).format(sdlFormat).usage(usage) + .width(width).height(height) + .layer_count_or_depth(dCount).num_levels(lCount); + final int props; + if ((usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) != 0) { + props = SDLProperties.SDL_CreateProperties(); + SDLProperties.SDL_SetFloatProperty(props, D3D12_CLEAR_DEPTH_PROP, 1.0f); + SDLProperties.SDL_SetNumberProperty(props, D3D12_CLEAR_STENCIL_PROP, 0L); + ci.props(props); + } else { + props = 0; + } + final long handle = SDL_CreateGPUTexture(device.getDevice(), ci); + if (props != 0) SDLProperties.SDL_DestroyProperties(props); + if (handle == 0) { + LOG.error("Failed to create texture {}x{} fmt=0x{} sdlFmt=0x{} usage=0x{}: {}", width, height, Integer.toHexString(glFormat), Integer.toHexString(sdlFormat), Integer.toHexString(usage), SDLError.SDL_GetError()); + return 0; + } + wLock.lock(); + try { + textureHandles.put(glId, handle); + liveTextureHandles.add(handle); + textureMetas.put(glId, new TextureMeta(glTarget, glFormat, sdlFormat, width, height, dCount, lCount, usage)); + } finally { + wLock.unlock(); + } + return handle; + } + } + + private int findSupportedDepthFallback(int sdlFormat, int sdlType, int usage) { + final int[] depthFallbacks = switch (sdlFormat) { + case SDL_GPU_TEXTUREFORMAT_D24_UNORM -> new int[]{ SDL_GPU_TEXTUREFORMAT_D32_FLOAT, SDL_GPU_TEXTUREFORMAT_D16_UNORM }; + case SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT -> new int[]{ SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT }; + case SDL_GPU_TEXTUREFORMAT_D16_UNORM -> new int[]{ SDL_GPU_TEXTUREFORMAT_D32_FLOAT }; + default -> new int[0]; + }; + for (int fallback : depthFallbacks) { + if (SDL_GPUTextureSupportsFormat(device.getDevice(), fallback, sdlType, usage)) { + return fallback; + } + } + return sdlFormat; + } + + public void deleteTexture(int glId) { + final long handle; + wLock.lock(); + try { + handle = textureHandles.remove(glId); + textureMetas.remove(glId); + fboAttachedGlIds.remove(glId); + for (FboState fbo : fboStates.values()) { + for (int i = 0; i < ContextState.MAX_COLOR_ATTACHMENTS; i++) { + if (fbo.colorGlIds[i] == glId) { + fbo.colorTextures[i] = 0; + fbo.colorGlIds[i] = 0; + fbo.colorFormats[i] = 0; + fbo.targetsDirty = true; + } + } + if (fbo.depthGlId == glId) { + fbo.depthTexture = 0; + fbo.depthGlId = 0; + fbo.depthFormat = 0; + fbo.targetsDirty = true; + } + } + texSamplerStates.remove(glId); + } finally { + wLock.unlock(); + } + releaseTextureHandle(handle); + } + + public void releaseTextureHandleForRealloc(int glId) { + final long handle; + wLock.lock(); + try { + handle = textureHandles.remove(glId); + textureMetas.remove(glId); + } finally { + wLock.unlock(); + } + releaseTextureHandle(handle); + } + + public void trackBufferHandle(long handle) { + if (handle == 0) return; + wLock.lock(); + try { liveBufferHandles.add(handle); } finally { wLock.unlock(); } + } + + public void trackTextureHandle(long handle) { + if (handle == 0) return; + wLock.lock(); + try { liveTextureHandles.add(handle); } finally { wLock.unlock(); } + } + + public void releaseBufferHandle(long handle) { + if (handle == 0) return; + final boolean live; + wLock.lock(); + try { + live = liveBufferHandles.remove(handle); + } finally { + wLock.unlock(); + } + if (live) { + if (Tracy.ENABLED) bufferDeletes.incrementAndGet(); + SDL_ReleaseGPUBuffer(device.getDevice(), handle); + } else { + LOG.error("Double release of GPU buffer handle {} - skipped", handle, new Throwable("double-release call site")); + } + } + + public void releaseTextureHandle(long handle) { + if (handle == 0) return; + final boolean live; + wLock.lock(); + try { + live = liveTextureHandles.remove(handle); + } finally { + wLock.unlock(); + } + if (live) { + SDL_ReleaseGPUTexture(device.getDevice(), handle); + } else { + LOG.error("Double release of GPU texture handle {} - skipped", handle, new Throwable("double-release call site")); + } + } + + public void refreshTextureReferences(int glId) { + wLock.lock(); + try { + final long newHandle = textureHandles.get(glId); + final TextureMeta meta = textureMetas.get(glId); + for (FboState fbo : fboStates.values()) { + for (int i = 0; i < ContextState.MAX_COLOR_ATTACHMENTS; i++) { + if (fbo.colorGlIds[i] == glId) { + fbo.colorTextures[i] = newHandle; + fbo.targetsDirty = true; + if (meta != null) { + fbo.colorFormats[i] = meta.sdlFormat(); + if (i == 0) { + fbo.width = meta.width(); + fbo.height = meta.height(); + } + } + } + } + if (fbo.depthGlId == glId) { + fbo.depthTexture = newHandle; + fbo.targetsDirty = true; + if (meta != null) fbo.depthFormat = meta.sdlFormat(); + } + } + } finally { + wLock.unlock(); + } + } + + public long getTextureHandle(int glId) { + if (fastRead()) return textureHandles.get(glId); + rLock.lock(); + try { return textureHandles.get(glId); } finally { rLock.unlock(); } + } + + public TextureMeta getTextureMeta(int glId) { + if (fastRead()) return textureMetas.get(glId); + rLock.lock(); + try { return textureMetas.get(glId); } finally { rLock.unlock(); } + } + + static int reconcileUsage(int usage) { + if ((usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) == 0) return usage; + final int illegal = usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE); + if (illegal == 0) return usage; + return usage & ~illegal; + } + + private int reconcileUsageAndWarn(int glId, int usage) { + final int reconciled = reconcileUsage(usage); + if (reconciled != usage) warnUsageConflict(glId, usage & ~reconciled, reconciled); + return reconciled; + } + + private final IntOpenHashSet loggedUsageConflict = new IntOpenHashSet(); + + private void warnUsageConflict(int glId, int illegal, int reconciled) { + synchronized (loggedUsageConflict) { + if (!loggedUsageConflict.add(glId)) return; + } + LOG.warn("[ResourceManager] texture {} requested SAMPLER together with storage usage 0x{}; SDL cannot resolve a default layout for that combination, dropping to 0x{}. The texture stays sampleable; image-load/store on it may lose coherence.", glId, Integer.toHexString(illegal), Integer.toHexString(reconciled)); + } + + public long ensureTextureUsage(int glId, int requiredUsage) { + final TextureMeta meta; + final long oldHandle; + if (fastRead()) { + meta = textureMetas.get(glId); + if (meta == null) return textureHandles.get(glId); + if ((meta.usage & requiredUsage) == requiredUsage) { + return textureHandles.get(glId); + } + oldHandle = textureHandles.get(glId); + } else { + rLock.lock(); + try { + meta = textureMetas.get(glId); + if (meta == null) return textureHandles.get(glId); + if ((meta.usage & requiredUsage) == requiredUsage) { + return textureHandles.get(glId); + } + oldHandle = textureHandles.get(glId); + } finally { + rLock.unlock(); + } + } + + final int newUsage = reconcileUsageAndWarn(glId, meta.usage | requiredUsage); + if ((meta.usage & newUsage) == newUsage) return oldHandle; + + final long newHandle = createTexture(glId, meta.glTarget, meta.glFormat, meta.width, meta.height, meta.depth, meta.levels, newUsage); + if (newHandle == 0) return oldHandle; + if (oldHandle != 0 && !copyAllMips(oldHandle, newHandle, meta.glTarget, meta.width, meta.height, meta.depth, meta.levels)) { + LOG.warn("[ResourceManager] texture {} usage promote 0x{} -> 0x{} had no copy pass available; restoring the populated texture and skipping the promote. Image load/store on it will not work this frame.", glId, Integer.toHexString(meta.usage), Integer.toHexString(newUsage)); + releaseTextureDeferred(newHandle); + restoreTextureHandle(glId, oldHandle, meta); + return oldHandle; + } + + frameManager.frame().pendingMipGen.remove(glId); + releaseTextureDeferred(oldHandle); + refreshTextureReferences(glId); + LOG.debug("Recreated texture {} with usage 0x{} -> 0x{} ({}x{})", glId, + Integer.toHexString(meta.usage), Integer.toHexString(newUsage), meta.width, meta.height); + return newHandle; + } + + private boolean copyAllMips(long srcTex, long dstTex, int glTarget, int width, int height, int depth, int levels) { + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return false; + final boolean volume = glTarget == GL12.GL_TEXTURE_3D; + final int layers = volume ? 1 : Math.max(1, depth); + try (var stack = stackPush()) { + final SDL_GPUTextureLocation src = SDL_GPUTextureLocation.calloc(stack); + final SDL_GPUTextureLocation dst = SDL_GPUTextureLocation.calloc(stack); + for (int level = 0; level < Math.max(1, levels); level++) { + final int w = Math.max(1, width >> level); + final int h = Math.max(1, height >> level); + final int d = volume ? Math.max(1, depth >> level) : 1; + for (int layer = 0; layer < layers; layer++) { + src.texture(srcTex).mip_level(level).layer(layer).x(0).y(0).z(0); + dst.texture(dstTex).mip_level(level).layer(layer).x(0).y(0).z(0); + SDL_CopyGPUTextureToTexture(cp, src, dst, w, h, d, false); + } + } + } + return true; + } + + private void restoreTextureHandle(int glId, long handle, TextureMeta meta) { + wLock.lock(); + try { + textureHandles.put(glId, handle); + textureMetas.put(glId, meta); + } finally { + wLock.unlock(); + } + } + + private static final long[] GPU_BUFFER_BUCKET_SIZES = { + 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216 + }; + + private static final class GpuBucket { + public final LongArrayList handles = new LongArrayList(); + public final LongArrayList frames = new LongArrayList(); + } + + private final Long2ObjectOpenHashMap gpuBufferPool = new Long2ObjectOpenHashMap<>(); + private long gpuPoolCurrentFrame; + + private static int findGpuBucketIndex(long size) { + for (int i = 0; i < GPU_BUFFER_BUCKET_SIZES.length; i++) { + if (size <= GPU_BUFFER_BUCKET_SIZES[i]) return i; + } + return -1; + } + + private long acquirePooledBuffer(int usage, long size) { + final int bucket = findGpuBucketIndex(size); + if (bucket < 0) return 0; + final GpuBucket b = gpuBufferPool.get(Hashing.packHiLo(usage, bucket)); + if (b == null || b.handles.isEmpty()) return 0; + for (int i = 0, n = b.handles.size(); i < n; i++) { + if (gpuPoolCurrentFrame - b.frames.getLong(i) >= Device.FRAMES_IN_FLIGHT) { + final long handle = b.handles.getLong(i); + final int last = n - 1; + if (i != last) { + b.handles.set(i, b.handles.getLong(last)); + b.frames.set(i, b.frames.getLong(last)); + } + b.handles.removeLong(last); + b.frames.removeLong(last); + return handle; + } + } + return 0; + } + + private void returnBufferToPool(long handle, int usage, long size) { + final int bucket = findGpuBucketIndex(size); + if (bucket < 0) { + deferredBufferReleases.add(handle); + return; + } + final long key = Hashing.packHiLo(usage, bucket); + GpuBucket b = gpuBufferPool.get(key); + if (b == null) { + b = new GpuBucket(); + gpuBufferPool.put(key, b); + } + b.handles.add(handle); + b.frames.add(gpuPoolCurrentFrame); + } + + public void recycleGpuBufferPool(long currentFrame) { + gpuPoolCurrentFrame = currentFrame; + recycleBatchSegments(currentFrame); + } + + private void drainGpuBufferPool() { + for (GpuBucket b : gpuBufferPool.values()) { + for (int i = 0, n = b.handles.size(); i < n; i++) { + releaseBufferHandle(b.handles.getLong(i)); + } + b.handles.clear(); + b.frames.clear(); + } + gpuBufferPool.clear(); + } + + public int genBuffer() { + return nextBufferId.getAndIncrement(); + } + + private Runnable bufferLivenessListener; + + public void setBufferLivenessListener(Runnable listener) { + this.bufferLivenessListener = listener; + } + + private void notifyBufferLiveness() { + final Runnable l = bufferLivenessListener; + if (l != null) l.run(); + } + + public long createBuffer(int glId, int usage, long size) { + wLock.lock(); + try { + final long pooled = acquirePooledBuffer(usage, size); + if (pooled != 0) { + if (Tracy.ENABLED) bufferPoolHits.incrementAndGet(); + bufferHandles.put(glId, pooled); + bufferSizes.put(glId, size); + bufferUsages.put(glId, usage); + undefinedContentBuffers.add(glId); + notifyBufferLiveness(); + return pooled; + } + final int bucket = findGpuBucketIndex(size); + final long allocSize = bucket >= 0 ? GPU_BUFFER_BUCKET_SIZES[bucket] : size; + try (var stack = stackPush()) { + final SDL_GPUBufferCreateInfo ci = SDL_GPUBufferCreateInfo.calloc(stack) + .usage(usage) + .size((int) allocSize); + + final long handle = SDL_CreateGPUBuffer(device.getDevice(), ci); + if (handle == 0) { + LOG.error("Failed to create buffer size={} usage={}: {}", allocSize, usage, SDLError.SDL_GetError()); + return 0; + } + if (Tracy.ENABLED) bufferCreates.incrementAndGet(); + bufferHandles.put(glId, handle); + liveBufferHandles.add(handle); + bufferSizes.put(glId, size); + bufferUsages.put(glId, usage); + undefinedContentBuffers.add(glId); + notifyBufferLiveness(); + return handle; + } + } finally { + wLock.unlock(); + } + } + + private final LongArrayList deferredBufferReleases = new LongArrayList(); + private final LongArrayList deferredTextureReleases = new LongArrayList(); + + public void deleteBuffer(int glId) { + final ByteBuffer droppedPboStaging; + final PersistentMapping droppedPm; + wLock.lock(); + try { + final long handle = bufferHandles.remove(glId); + final long size = bufferSizes.remove(glId); + final int usage = bufferUsages.remove(glId); + bufferGlUsages.remove(glId); + bufferStorageFlags.remove(glId); + undefinedContentBuffers.remove(glId); + droppedPm = persistentMappings.remove(glId); + if (droppedPm != null) mappingsVersion++; + droppedPboStaging = pboStagingData.remove(glId); + deleteUboShadow(glId); + deleteEboShadow(glId); + deleteArrayShadow(glId); + if (handle != 0) { + returnBufferToPool(handle, usage, size); + notifyBufferLiveness(); + } + } finally { + wLock.unlock(); + } + if (droppedPboStaging != null) { + memFree(droppedPboStaging); + } + untrackPersistentDirty(droppedPm); + releasePersistentStaging(droppedPm); + } + + public void flushDeferredReleases() { + wLock.lock(); + try { + for (int i = 0, n = deferredBufferReleases.size(); i < n; i++) { + releaseBufferHandle(deferredBufferReleases.getLong(i)); + } + deferredBufferReleases.clear(); + for (int i = 0, n = deferredTextureReleases.size(); i < n; i++) { + releaseTextureHandle(deferredTextureReleases.getLong(i)); + } + deferredTextureReleases.clear(); + } finally { + wLock.unlock(); + } + } + + public void releaseBufferDeferred(long handle) { + if (handle == 0) return; + wLock.lock(); + try { + deferredBufferReleases.add(handle); + } finally { + wLock.unlock(); + } + } + + public void releaseTextureDeferred(long handle) { + if (handle == 0) return; + wLock.lock(); + try { + deferredTextureReleases.add(handle); + } finally { + wLock.unlock(); + } + } + + private static volatile boolean singleThreadedReads; + private static volatile boolean workersActive; + private final AtomicInteger lockedReads = new AtomicInteger(); + private final AtomicInteger bufferCreates = new AtomicInteger(); + private final AtomicInteger bufferDeletes = new AtomicInteger(); + private final AtomicInteger bufferPoolHits = new AtomicInteger(); + + public int takeBufferCreateCount() { return bufferCreates.getAndSet(0); } + + public int takeBufferDeleteCount() { return bufferDeletes.getAndSet(0); } + + public int takeBufferPoolHitCount() { return bufferPoolHits.getAndSet(0); } + + public int takeLockedReadCount() { return lockedReads.getAndSet(0); } + + public static void setSingleThreadedReads(boolean value) { singleThreadedReads = value; } + public static void setWorkersActive(boolean value) { workersActive = value; } + + private boolean fastRead() { + if (singleThreadedReads && !workersActive) return true; + if (Tracy.ENABLED) lockedReads.incrementAndGet(); + return false; + } + + public long getBufferHandle(int glId) { + if (fastRead()) return bufferHandles.get(glId); + rLock.lock(); + try { return bufferHandles.get(glId); } finally { rLock.unlock(); } + } + + public long getBufferSize(int glId) { + if (fastRead()) return bufferSizes.get(glId); + rLock.lock(); + try { return bufferSizes.get(glId); } finally { rLock.unlock(); } + } + + public void recordBufferGlParams(int glId, int glUsage, int storageFlags) { + wLock.lock(); + try { + bufferGlUsages.put(glId, glUsage); + bufferStorageFlags.put(glId, storageFlags); + } finally { + wLock.unlock(); + } + } + + public int getBufferGlUsage(int glId) { + if (fastRead()) return bufferGlUsages.get(glId); + rLock.lock(); + try { return bufferGlUsages.get(glId); } finally { rLock.unlock(); } + } + + public int getBufferStorageFlags(int glId) { + if (fastRead()) return bufferStorageFlags.get(glId); + rLock.lock(); + try { return bufferStorageFlags.get(glId); } finally { rLock.unlock(); } + } + + public void markBufferContentsDefined(int glId) { + if (glId == 0 || !hasUndefinedContents(glId)) return; + wLock.lock(); + try { undefinedContentBuffers.remove(glId); } finally { wLock.unlock(); } + } + + public boolean hasUndefinedContents(int glId) { + if (fastRead()) return undefinedContentBuffers.contains(glId); + rLock.lock(); + try { return undefinedContentBuffers.contains(glId); } finally { rLock.unlock(); } + } + + public int genSampler() { + return nextSamplerId.getAndIncrement(); + } + + public long createSampler(int glId, SDL_GPUSamplerCreateInfo ci) { + final long handle = SDL_CreateGPUSampler(device.getDevice(), ci); + if (handle == 0) { + LOG.error("Failed to create sampler: {}", SDLError.SDL_GetError()); + return 0; + } + wLock.lock(); + try { + samplerHandles.put(glId, handle); + } finally { + wLock.unlock(); + } + return handle; + } + + public void deleteSampler(int glId) { + final long handle; + wLock.lock(); + try { + handle = samplerHandles.remove(glId); + } finally { + wLock.unlock(); + } + if (handle != 0) { + SDL_ReleaseGPUSampler(device.getDevice(), handle); + } + } + + + private V getOrCreateLocked(Int2ObjectOpenHashMap map, int key, Supplier factory) { + rLock.lock(); + try { + final V s = map.get(key); + if (s != null) return s; + } finally { rLock.unlock(); } + wLock.lock(); + try { + V s = map.get(key); + if (s == null) { + s = factory.get(); + map.put(key, s); + } + return s; + } finally { wLock.unlock(); } + } + + public ContextState.VAOState getVao(int glId) { + rLock.lock(); + try { return vaoStates.get(glId); } finally { rLock.unlock(); } + } + public ContextState.VAOState getOrCreateVao(int glId) { + return getOrCreateLocked(vaoStates, glId, VAO_FACTORY); + } + public void putVao(int glId, ContextState.VAOState s) { + wLock.lock(); + try { vaoStates.put(glId, s); } finally { wLock.unlock(); } + } + public void deleteVao(int glId) { + wLock.lock(); + try { vaoStates.remove(glId); } finally { wLock.unlock(); } + } + + public void putPersistentMapping(int bufferGlId, PersistentMapping m) { + wLock.lock(); + try { persistentMappings.put(bufferGlId, m); mappingsVersion++; } finally { wLock.unlock(); } + } + public PersistentMapping getPersistentMapping(int bufferGlId) { + if (fastRead()) return persistentMappings.get(bufferGlId); + rLock.lock(); + try { return persistentMappings.get(bufferGlId); } finally { rLock.unlock(); } + } + public PersistentMapping removePersistentMapping(int bufferGlId) { + final PersistentMapping dropped; + wLock.lock(); + try { dropped = persistentMappings.remove(bufferGlId); mappingsVersion++; } finally { wLock.unlock(); } + untrackPersistentDirty(dropped); + return dropped; + } + public PersistentMapping swapPersistentMapping(int bufferGlId, PersistentMapping fresh) { + final PersistentMapping prior; + wLock.lock(); + try { prior = persistentMappings.put(bufferGlId, fresh); mappingsVersion++; } finally { wLock.unlock(); } + untrackPersistentDirty(prior); + return prior; + } + + private volatile int mappingsVersion; + + private final AtomicInteger persistentDirtyCount = new AtomicInteger(); + + public boolean hasDirtyPersistentRegions() { return persistentDirtyCount.get() != 0; } + public void trackPersistentDirty() { persistentDirtyCount.incrementAndGet(); } + public void clearPersistentDirty() { persistentDirtyCount.decrementAndGet(); } + + private void untrackPersistentDirty(PersistentMapping pm) { + if (pm != null && !PersistentMapping.isClean(pm.claimDirty())) persistentDirtyCount.decrementAndGet(); + } + + public void releasePersistentStaging(PersistentMapping pm) { + if (pm == null || pm.staging == null) return; + final TransferThread tt = transferThread; + final long seq = pm.lastEnqueuedSeq; + if (tt != null && seq > tt.getSubmittedSeq()) tt.freeAfterSeq(pm.staging, seq); + else memFree(pm.staging); + } + + public boolean uploadFromPersistentMapping(int srcGlId, long readOffset, long size, long dstHandle, long writeOffset, int dstGlId, long copyPass) { + rLock.lock(); + try { + final PersistentMapping srcPm = persistentMappings.get(srcGlId); + if (srcPm == null) return false; + final ByteBuffer slice = srcPm.staging.duplicate(); + slice.position((int) readOffset).limit((int) (readOffset + size)); + uploadToBuffer(copyPass, slice, dstHandle, writeOffset, false); + final PersistentMapping dstPm = persistentMappings.get(dstGlId); + if (dstPm != null) { + PersistentBufferSync.mirrorPersistentCopy(srcPm.staging, readOffset, dstPm.staging, writeOffset, size); + } + return true; + } finally { rLock.unlock(); } + } + + public boolean enqueuePersistentCopyDeferred(int srcGlId, int dstGlId, long seq, + BiConsumer inLock) { + rLock.lock(); + try { + final PersistentMapping srcPm = persistentMappings.get(srcGlId); + if (srcPm == null) return false; + final PersistentMapping dstPm = persistentMappings.get(dstGlId); + srcPm.lastEnqueuedSeq = seq; + inLock.accept(srcPm, dstPm); + return true; + } finally { rLock.unlock(); } + } + + public int getMappingsVersion() { return mappingsVersion; } + + public void snapshotPersistentMappingsInto(IntArrayList outKeys, ArrayList outVals) { + outKeys.clear(); + outVals.clear(); + rLock.lock(); + try { + final var it = persistentMappings.int2ObjectEntrySet().fastIterator(); + while (it.hasNext()) { + final var entry = it.next(); + outKeys.add(entry.getIntKey()); + outVals.add(entry.getValue()); + } + } finally { rLock.unlock(); } + } + + public void recordBufferSizeOnly(int glId, long size) { + wLock.lock(); + try { + bufferSizes.put(glId, size); + } finally { + wLock.unlock(); + } + } + + public ByteBuffer getOrAllocUboShadow(int bufferGlId, int size) { + wLock.lock(); + try { + ByteBuffer existing = uboShadows.get(bufferGlId); + if (existing != null && existing.capacity() >= size) { + existing.clear(); + return existing; + } + if (existing != null) pendingFreeShadows.add(existing); + final ByteBuffer fresh = memAlloc(size).order(ByteOrder.nativeOrder()); + uboShadows.put(bufferGlId, fresh); + return fresh; + } finally { wLock.unlock(); } + } + + public ByteBuffer getUboShadow(int bufferGlId) { + rLock.lock(); + try { return uboShadows.get(bufferGlId); } finally { rLock.unlock(); } + } + + private void deleteUboShadow(int bufferGlId) { + final ByteBuffer existing = uboShadows.remove(bufferGlId); + if (existing != null) memFree(existing); + } + + public ByteBuffer getOrAllocEboShadow(int bufferGlId, int size) { + wLock.lock(); + try { + ByteBuffer existing = eboShadows.get(bufferGlId); + if (existing != null && existing.capacity() >= size) { + existing.clear(); + return existing; + } + if (existing != null) pendingFreeShadows.add(existing); + final ByteBuffer fresh = memAlloc(size).order(ByteOrder.nativeOrder()); + eboShadows.put(bufferGlId, fresh); + return fresh; + } finally { wLock.unlock(); } + } + + public void drainPendingFreeShadows() { + wLock.lock(); + try { + ByteBuffer b; + while ((b = pendingFreeShadows.pollFirst()) != null) memFree(b); + } finally { wLock.unlock(); } + } + + public ByteBuffer getEboShadow(int bufferGlId) { + rLock.lock(); + try { return eboShadows.get(bufferGlId); } finally { rLock.unlock(); } + } + + public boolean hasEboShadow(int bufferGlId) { + rLock.lock(); + try { return eboShadows.containsKey(bufferGlId); } finally { rLock.unlock(); } + } + + public boolean isEboShadowWanted(int glId) { + rLock.lock(); + try { return eboShadowWanted.contains(glId); } finally { rLock.unlock(); } + } + + public void markEboShadowWanted(int glId) { + wLock.lock(); + try { eboShadowWanted.add(glId); } finally { wLock.unlock(); } + } + + public void dropEboShadow(int bufferGlId) { + wLock.lock(); + try { + final ByteBuffer existing = eboShadows.remove(bufferGlId); + if (existing != null) pendingFreeShadows.add(existing); + eboShadowVersions.remove(bufferGlId); + } finally { wLock.unlock(); } + invalidateSplitCacheFor(bufferGlId); + } + + public long bumpEboShadowVersion(int bufferGlId) { + wLock.lock(); + try { + final long v = ++nextEboShadowVersion; + eboShadowVersions.put(bufferGlId, v); + return v; + } finally { wLock.unlock(); } + } + + public long getEboShadowVersion(int bufferGlId) { + rLock.lock(); + try { return eboShadowVersions.get(bufferGlId); } finally { rLock.unlock(); } + } + + private void deleteEboShadow(int bufferGlId) { + final ByteBuffer existing = eboShadows.remove(bufferGlId); + if (existing != null) memFree(existing); + eboShadowVersions.remove(bufferGlId); + eboShadowWanted.remove(bufferGlId); + } + + public boolean canShadowArrayBuffer(int size) { + return size > 0 && size <= MAX_ARRAY_SHADOW_BUFFER_BYTES; + } + + public ByteBuffer getArrayShadow(int glId) { + rLock.lock(); + try { return arrayShadows.get(glId); } finally { rLock.unlock(); } + } + + public boolean hasArrayShadow(int glId) { + rLock.lock(); + try { return arrayShadows.containsKey(glId); } finally { rLock.unlock(); } + } + + public boolean isArrayShadowWanted(int glId) { + rLock.lock(); + try { return arrayShadowWanted.contains(glId); } finally { rLock.unlock(); } + } + + public void markArrayShadowWanted(int glId) { + wLock.lock(); + try { arrayShadowWanted.add(glId); } finally { wLock.unlock(); } + } + + public ByteBuffer getOrAllocArrayShadow(int glId, int size) { + wLock.lock(); + try { + final ByteBuffer existing = arrayShadows.get(glId); + if (existing != null && existing.capacity() >= size) { + existing.clear(); + return existing; + } + if (existing != null) pendingFreeShadows.add(existing); + final ByteBuffer fresh = memAlloc(size).order(ByteOrder.nativeOrder()); + arrayShadows.put(glId, fresh); + return fresh; + } finally { wLock.unlock(); } + } + + public void mirrorArrayShadowFull(int glId, ByteBuffer data) { + final int len = data.remaining(); + final ByteBuffer shadow = getOrAllocArrayShadow(glId, len); + copyShadowRegion(data, data.position(), shadow, 0, len); + shadow.position(0).limit(len); + } + + public void mirrorArrayShadowRegion(int glId, ByteBuffer data, int dstOffset) { + wLock.lock(); + try { + final ByteBuffer shadow = arrayShadows.get(glId); + if (shadow == null) return; + final int len = data.remaining(); + if (dstOffset < 0 || dstOffset + len > shadow.capacity()) { + removeArrayShadowLocked(glId); + return; + } + copyShadowRegion(data, data.position(), shadow, dstOffset, len); + } finally { wLock.unlock(); } + } + + public void dropArrayShadow(int glId) { + wLock.lock(); + try { removeArrayShadowLocked(glId); } finally { wLock.unlock(); } + } + + private void removeArrayShadowLocked(int glId) { + final ByteBuffer existing = arrayShadows.remove(glId); + if (existing != null) pendingFreeShadows.add(existing); + } + + private void deleteArrayShadow(int glId) { + final ByteBuffer existing = arrayShadows.remove(glId); + if (existing != null) memFree(existing); + arrayShadowWanted.remove(glId); + } + + private static void copyShadowRegion(ByteBuffer src, int srcOff, ByteBuffer dst, int dstOff, int len) { + if (src.isDirect() && dst.isDirect()) { + MemoryUtil.memCopy(MemoryUtil.memAddress(src) + srcOff, MemoryUtil.memAddress(dst) + dstOff, len); + return; + } + final ByteBuffer s = src.duplicate(); + s.position(srcOff).limit(srcOff + len); + final ByteBuffer d = dst.duplicate(); + d.position(dstOff); + d.put(s); + } + + public EBOSplitScanner.EboSplit[] getOrScanSplits(int glId, int indexType, int sentinel) { + if (!hasEboShadow(glId)) return null; + final long version = getEboShadowVersion(glId); + final EboSplitKey key = new EboSplitKey(glId, version, indexType, sentinel); + return splitCache.computeIfAbsent(key, k -> { + final ByteBuffer shadow = getEboShadow(glId); + if (shadow == null) return null; + final int indexBytes = (indexType == GL11.GL_UNSIGNED_SHORT) ? 2 : 4; + return EBOSplitScanner.scanIndices(shadow, shadow.capacity() / indexBytes, indexType, sentinel); + }); + } + + public void invalidateSplitCacheFor(int glId) { + if (splitCache.isEmpty()) return; + splitCache.entrySet().removeIf(e -> e.getKey().glId == glId); + } + + public void clearSplitCache() { + splitCache.clear(); + } + + public TextureSamplerState getOrCreateTexSamplerState(int textureGlId) { + return getOrCreateLocked(texSamplerStates, textureGlId, TEX_SAMPLER_FACTORY); + } + public TextureSamplerState getTexSamplerState(int textureGlId) { + if (fastRead()) return texSamplerStates.get(textureGlId); + rLock.lock(); + try { return texSamplerStates.get(textureGlId); } finally { rLock.unlock(); } + } + + public TextureSamplerState getOrCreateSamplerObject(int samplerGlId) { + return getOrCreateLocked(samplerObjectStates, samplerGlId, TEX_SAMPLER_FACTORY); + } + public TextureSamplerState getSamplerObject(int samplerGlId) { + if (fastRead()) return samplerObjectStates.get(samplerGlId); + rLock.lock(); + try { return samplerObjectStates.get(samplerGlId); } finally { rLock.unlock(); } + } + public long getSamplerHandle(int samplerGlId) { + if (fastRead()) return samplerHandles.get(samplerGlId); + rLock.lock(); + try { return samplerHandles.get(samplerGlId); } finally { rLock.unlock(); } + } + public void deleteSamplerObject(int samplerGlId) { + wLock.lock(); + try { + samplerObjectStates.remove(samplerGlId); + } finally { wLock.unlock(); } + } + + public void shutdownTexSamplerStates() { + wLock.lock(); + try { + texSamplerStates.clear(); + samplerObjectStates.clear(); + } finally { wLock.unlock(); } + } + + public int genFboId() { return nextFboId.getAndIncrement(); } + public FboState createFbo(int fboGlId) { + wLock.lock(); + try { + final FboState s = new FboState(); + fboStates.put(fboGlId, s); + return s; + } finally { wLock.unlock(); } + } + public FboState getFbo(int fboGlId) { + if (fastRead()) return fboStates.get(fboGlId); + rLock.lock(); + try { return fboStates.get(fboGlId); } finally { rLock.unlock(); } + } + public void deleteFbo(int fboGlId) { + wLock.lock(); + try { + final FboState removed = fboStates.remove(fboGlId); + if (removed != null) removed.free(); + } finally { wLock.unlock(); } + } + public void forEachFbo(Consumer fn) { + rLock.lock(); + try { + for (FboState fbo : fboStates.values()) fn.accept(fbo); + } finally { rLock.unlock(); } + } + + public ByteBuffer putPboStaging(int bufferGlId, ByteBuffer buf) { + wLock.lock(); + try { return pboStagingData.put(bufferGlId, buf); } finally { wLock.unlock(); } + } + public ByteBuffer getPboStaging(int bufferGlId) { + rLock.lock(); + try { return pboStagingData.get(bufferGlId); } finally { rLock.unlock(); } + } + + public static final int[] XFER_BUCKET_SIZES = { 4096, 16384, 65536, 262144, 1048576, 4194304 }; + private final Object xferPoolLock = new Object(); + private final LongArrayFIFOQueue[] xferFreeBuckets = new LongArrayFIFOQueue[XFER_BUCKET_SIZES.length]; + { + for (int i = 0; i < XFER_BUCKET_SIZES.length; i++) { + xferFreeBuckets[i] = new LongArrayFIFOQueue(); + } + } + + // Guarded by xferPoolLock. + private final LongOpenHashSet liveTransferBufferHandles = new LongOpenHashSet(); + + private static int findXferBucket(long size) { + for (int i = 0; i < XFER_BUCKET_SIZES.length; i++) { + if (size <= XFER_BUCKET_SIZES[i]) return i; + } + return -1; + } + + public long getTransferBufferMapSize(long dataSize) { + final int bucket = findXferBucket(dataSize); + return (bucket >= 0) ? XFER_BUCKET_SIZES[bucket] : dataSize; + } + + public long acquireTransferBuffer(long size) { + final int bucket = findXferBucket(size); + long pooled = 0; + if (bucket >= 0) { + synchronized (xferPoolLock) { + final LongArrayFIFOQueue q = xferFreeBuckets[bucket]; + if (!q.isEmpty()) pooled = q.dequeueLong(); + } + if (pooled != 0) return pooled; + } + + final long allocSize = (bucket >= 0) ? XFER_BUCKET_SIZES[bucket] : size; + return createTransferBuffer(allocSize); + } + + public void returnTransferBuffer(long handle, long size) { + final int bucket = findXferBucket(size); + if (bucket < 0) { + releaseTransferBuffer(handle); + return; + } + synchronized (xferPoolLock) { + xferFreeBuckets[bucket].enqueue(handle); + } + } + + public long acquireTransferBufferThreadSafe(long size) { + return acquireTransferBuffer(size); + } + + public void returnTransferBufferThreadSafe(long handle, long size) { + returnTransferBuffer(handle, size); + } + + public void drainTransferBufferPool() { + synchronized (xferPoolLock) { + for (int b = 0; b < XFER_BUCKET_SIZES.length; b++) { + final LongArrayFIFOQueue q = xferFreeBuckets[b]; + while (!q.isEmpty()) { + releaseTransferBufferHandle(q.dequeueLong()); + } + } + while (!batchSegmentFree.isEmpty()) { + releaseTransferBufferHandle(batchSegmentFree.dequeueLong()); + } + for (int i = 0, n = batchSegmentPending.size(); i < n; i += 2) { + releaseTransferBufferHandle(batchSegmentPending.getLong(i)); + } + batchSegmentPending.clear(); + } + } + + private final LongArrayFIFOQueue batchSegmentFree = new LongArrayFIFOQueue(); + private final LongArrayList batchSegmentPending = new LongArrayList(); + + private long acquireBatchSegment() { + synchronized (xferPoolLock) { + if (!batchSegmentFree.isEmpty()) return batchSegmentFree.dequeueLong(); + } + return createTransferBuffer(BATCH_SEGMENT_CAPACITY); + } + + private void releaseBatchSegmentDeferred(long handle) { + if (handle == 0) return; + synchronized (xferPoolLock) { + batchSegmentPending.add(handle); + batchSegmentPending.add(gpuPoolCurrentFrame); + } + } + + private void recycleBatchSegments(long currentFrame) { + synchronized (xferPoolLock) { + final int n = batchSegmentPending.size(); + int w = 0; + for (int i = 0; i < n; i += 2) { + final long handle = batchSegmentPending.getLong(i); + final long stamp = batchSegmentPending.getLong(i + 1); + if (currentFrame - stamp >= Device.FRAMES_IN_FLIGHT) { + batchSegmentFree.enqueue(handle); + } else { + batchSegmentPending.set(w, handle); + batchSegmentPending.set(w + 1, stamp); + w += 2; + } + } + batchSegmentPending.size(w); + } + } + + public long createTransferBuffer(long size) { + try (var stack = stackPush()) { + final SDL_GPUTransferBufferCreateInfo ci = SDL_GPUTransferBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD) + .size((int) size); + + final long handle = SDL_CreateGPUTransferBuffer(device.getDevice(), ci); + if (handle == 0) { + LOG.error("Failed to create transfer buffer size={}: {}", size, SDLError.SDL_GetError()); + } else { + synchronized (xferPoolLock) { liveTransferBufferHandles.add(handle); } + } + return handle; + } + } + + public void unmapTransferBuffer(long transferBuffer) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), transferBuffer); + } + + public void releaseTransferBuffer(long transferBuffer) { + releaseTransferBufferHandle(transferBuffer); + } + + public void releaseTransferBufferHandle(long handle) { + if (handle == 0) return; + final boolean live; + synchronized (xferPoolLock) { + live = liveTransferBufferHandles.remove(handle); + } + if (live) { + SDL_ReleaseGPUTransferBuffer(device.getDevice(), handle); + } else { + LOG.error("Double release of GPU transfer buffer {} - skipped", handle, new Throwable("double-release call site")); + } + } + + static void copyMappedFromData(ByteBuffer mapped, ByteBuffer data, int size, int callsiteId) { + if (size < 0 || data.remaining() < size || mapped.remaining() < size || mapped.position() + (long) size > mapped.capacity()) { + throw new IllegalStateException( + "copyMappedFromData out of bounds: callsite=" + callsiteId + " size=" + size + + " data.remaining=" + data.remaining() + + " mapped.remaining=" + mapped.remaining() + + " mapped.position=" + mapped.position() + + " mapped.capacity=" + mapped.capacity()); + } + if (data.isDirect() && mapped.isDirect()) { + final long src = MemoryUtil.memAddress(data); + final long dst = MemoryUtil.memAddress(mapped); + MemoryUtil.memCopy(src, dst, size); + mapped.position(mapped.position() + size); + } else { + mapped.put(data.duplicate()); + } + } + + public static final int COPY_CALLSITE_UPLOAD_BUFFER = 1; + public static final int COPY_CALLSITE_UPLOAD_TEX_BATCH = 2; + public static final int COPY_CALLSITE_UPLOAD_TEX_DIRECT = 3; + public static final int COPY_CALLSITE_ARENA = 4; + + public boolean arenaUpload(ByteBuffer data, long dstHandle, long dstOffset, boolean cycle) { + final FrameManager.FrameState f = frameManager.frame(); + final int size = data.remaining(); + if (!f.arena.fits(size)) { + return false; + } + if (f.arenaCopyPass == 0 && !beginArenaBatch(f)) return false; + int at = f.arena.reserve(size); + if (at < 0) { + f.arena.requestGrow(f.arena.usedBytes() + size); + if (Tracy.ENABLED) f.arenaOverflowFlushesThisFrame++; + flushUploadArena(f); + if (!beginArenaBatch(f)) return false; + at = f.arena.reserve(size); + if (at < 0) return false; + } + f.arenaMapped.position(at); + copyMappedFromData(f.arenaMapped, data, size, COPY_CALLSITE_ARENA); + try (var stack = stackPush()) { + final SDL_GPUTransferBufferLocation src = SDL_GPUTransferBufferLocation.calloc(stack) + .transfer_buffer(f.arenaXfer) + .offset(at); + final SDL_GPUBufferRegion dst = SDL_GPUBufferRegion.calloc(stack) + .buffer(dstHandle) + .offset((int) dstOffset) + .size(size); + SDL_UploadToGPUBuffer(f.arenaCopyPass, src, dst, cycle); + } + return true; + } + + private boolean beginArenaBatch(FrameManager.FrameState f) { + if (f.arenaXfer != 0 && f.arena.applyGrow()) { + releaseTransferBufferHandle(f.arenaXfer); + f.arenaXfer = 0; + } + if (f.arenaXfer == 0) { + f.arena.applyGrow(); + f.arenaXfer = createTransferBuffer(f.arena.capacity()); + if (f.arenaXfer == 0) return false; + } + f.arenaMapped = SDL_MapGPUTransferBuffer(device.getDevice(), f.arenaXfer, true, f.arena.capacity()); + if (f.arenaMapped == null) { + LOG.error("Failed to map arena transfer buffer: {}", SDLError.SDL_GetError()); + return false; + } + f.arenaCommandBuffer = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (f.arenaCommandBuffer == 0) { + LOG.error("Failed to acquire arena upload command buffer: {}", SDLError.SDL_GetError()); + f.arenaMapped = null; + return false; + } + f.arenaCopyPass = SDL_BeginGPUCopyPass(f.arenaCommandBuffer); + if (f.arenaCopyPass == 0) { + LOG.error("Failed to begin arena copy pass: {}", SDLError.SDL_GetError()); + SDL_SubmitGPUCommandBuffer(f.arenaCommandBuffer); + f.arenaCommandBuffer = 0; + f.arenaMapped = null; + return false; + } + return true; + } + + public void flushUploadArena() { + flushUploadArena(frameManager.frame()); + } + + public void flushUploadArena(FrameManager.FrameState f) { + if (f.arenaMapped != null) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), f.arenaXfer); + f.arenaMapped = null; + } + if (f.arenaCopyPass != 0) { + SDL_EndGPUCopyPass(f.arenaCopyPass); + f.arenaCopyPass = 0; + } + if (f.arenaCommandBuffer != 0) { + if (!SDL_SubmitGPUCommandBuffer(f.arenaCommandBuffer)) { + LOG.error("Failed to submit arena upload command buffer: {}", SDLError.SDL_GetError()); + } + f.arenaCommandBuffer = 0; + if (Tracy.ENABLED) f.arenaSubmitsThisFrame++; + } + f.arena.reset(); + } + + public void uploadToBuffer(long copyPass, ByteBuffer data, long gpuBuffer, long offset, boolean cycle) { + final long size = data.remaining(); + final long xfer = acquireTransferBuffer(size); + if (xfer == 0) return; + + final long mapSize = getTransferBufferMapSize(size); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped == null || mapped.capacity() < size) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + returnTransferBuffer(xfer, size); + throw new IllegalStateException("uploadToBuffer: bad mapping size=" + size + " mapSize=" + mapSize + " mapped=" + (mapped == null ? "null" : "cap=" + mapped.capacity())); + } + copyMappedFromData(mapped, data, (int) size, COPY_CALLSITE_UPLOAD_BUFFER); + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + try (var stack = stackPush()) { + final SDL_GPUTransferBufferLocation src = SDL_GPUTransferBufferLocation.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + + final SDL_GPUBufferRegion dst = SDL_GPUBufferRegion.calloc(stack) + .buffer(gpuBuffer) + .offset((int) offset) + .size((int) size); + + SDL_UploadToGPUBuffer(copyPass, src, dst, cycle); + } + + frameManager.recordUploadCommands(size, 1); + returnTransferBuffer(xfer, size); + } + + public static final int BATCH_SEGMENT_CAPACITY = 4 * 1024 * 1024; + + public void uploadToTexture(long copyPass, ByteBuffer data, long gpuTexture, int x, int y, int w, int h, int level) { + final FrameManager.FrameState f = frameManager.frame(); + final int size = data.remaining(); + + if (size > BATCH_SEGMENT_CAPACITY) { + directUploadToTexture(copyPass, data, gpuTexture, x, y, w, h, level); + return; + } + + f.batchOffset = (f.batchOffset + 15) & -16; + + if (f.batchMapped != null && f.batchOffset + size > BATCH_SEGMENT_CAPACITY) { + flushBatchedUploads(copyPass); + if (f.commandBuffer == 0 && f.pendingUploadCommandBuffer != 0) { + frameManager.flushPendingUploadCommandBuffer(); + } + } + + if (f.batchMapped == null) { + f.batchXfer = acquireBatchSegment(); + if (f.batchXfer == 0) return; + f.batchMapped = SDL_MapGPUTransferBuffer(device.getDevice(), f.batchXfer, false, BATCH_SEGMENT_CAPACITY); + if (f.batchMapped == null) { + synchronized (xferPoolLock) { batchSegmentFree.enqueue(f.batchXfer); } + f.batchXfer = 0; + return; + } + f.batchOffset = 0; + } + + if ((long) f.batchOffset + size > BATCH_SEGMENT_CAPACITY) { + throw new IllegalStateException("uploadToTexture batch overflow: batchOffset=" + f.batchOffset + " size=" + size + " cap=" + BATCH_SEGMENT_CAPACITY); + } + f.batchMapped.position(f.batchOffset); + copyMappedFromData(f.batchMapped, data, size, COPY_CALLSITE_UPLOAD_TEX_BATCH); + + f.pendingTexHandles.add(gpuTexture); + f.pendingTexX.add(x); + f.pendingTexY.add(y); + f.pendingTexW.add(w); + f.pendingTexH.add(h); + f.pendingTexLevels.add(level); + f.pendingTexOffsets.add(f.batchOffset); + f.batchOffset += size; + } + + public void flushBatchedUploads(long copyPass) { + final FrameManager.FrameState f = frameManager.frame(); + final int n = f.pendingTexHandles.size(); + if (n == 0) return; + + if (f.batchMapped != null) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), f.batchXfer); + f.batchMapped = null; + } + + try (var stack = stackPush()) { + final SDL_GPUTextureTransferInfo src = SDL_GPUTextureTransferInfo.calloc(stack); + final SDL_GPUTextureRegion dst = SDL_GPUTextureRegion.calloc(stack); + for (int i = 0; i < n; i++) { + src.transfer_buffer(f.batchXfer).offset(f.pendingTexOffsets.getInt(i)); + dst.texture(f.pendingTexHandles.getLong(i)).mip_level(f.pendingTexLevels.getInt(i)) + .x(f.pendingTexX.getInt(i)).y(f.pendingTexY.getInt(i)).z(0) + .w(f.pendingTexW.getInt(i)).h(f.pendingTexH.getInt(i)).d(1); + SDL_UploadToGPUTexture(copyPass, src, dst, false); + } + } + releaseBatchSegmentDeferred(f.batchXfer); + f.batchXfer = 0; + + final long totalBytes = f.batchOffset; + f.pendingTexHandles.clear(); + f.pendingTexX.clear(); + f.pendingTexY.clear(); + f.pendingTexW.clear(); + f.pendingTexH.clear(); + f.pendingTexLevels.clear(); + f.pendingTexOffsets.clear(); + f.batchOffset = 0; + frameManager.recordUploadCommands(totalBytes, n); + } + + public boolean hasBatchedUploads() { + return !frameManager.frame().pendingTexHandles.isEmpty(); + } + + public void uploadToTexture3D(long copyPass, ByteBuffer data, long gpuTexture, int x, int y, int z, int w, int h, int d, int level) { + final long size = data.remaining(); + final long xfer = acquireTransferBuffer(size); + if (xfer == 0) return; + + final long mapSize = getTransferBufferMapSize(size); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped == null || mapped.capacity() < size) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + returnTransferBuffer(xfer, size); + throw new IllegalStateException("uploadToTexture3D: bad mapping size=" + size + " mapSize=" + mapSize + " mapped=" + (mapped == null ? "null" : "cap=" + mapped.capacity())); + } + copyMappedFromData(mapped, data, (int) size, COPY_CALLSITE_UPLOAD_TEX_DIRECT); + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + try (var stack = stackPush()) { + final SDL_GPUTextureTransferInfo src = SDL_GPUTextureTransferInfo.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + final SDL_GPUTextureRegion dst = SDL_GPUTextureRegion.calloc(stack) + .texture(gpuTexture) + .mip_level(level) + .x(x).y(y).z(z) + .w(w).h(h).d(d); + SDL_UploadToGPUTexture(copyPass, src, dst, false); + } + + frameManager.recordUploadCommands(size, 1); + returnTransferBuffer(xfer, size); + } + + private void directUploadToTexture(long copyPass, ByteBuffer data, long gpuTexture, int x, int y, int w, int h, int level) { + final long size = data.remaining(); + final long xfer = acquireTransferBuffer(size); + if (xfer == 0) return; + + final long mapSize = getTransferBufferMapSize(size); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped == null || mapped.capacity() < size) { + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + returnTransferBuffer(xfer, size); + throw new IllegalStateException("directUploadToTexture: bad mapping size=" + size + " mapSize=" + mapSize + " mapped=" + (mapped == null ? "null" : "cap=" + mapped.capacity())); + } + copyMappedFromData(mapped, data, (int) size, COPY_CALLSITE_UPLOAD_TEX_DIRECT); + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + try (var stack = stackPush()) { + final SDL_GPUTextureTransferInfo src = SDL_GPUTextureTransferInfo.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + + final SDL_GPUTextureRegion dst = SDL_GPUTextureRegion.calloc(stack) + .texture(gpuTexture) + .mip_level(level) + .x(x).y(y).z(0) + .w(w).h(h).d(1); + + SDL_UploadToGPUTexture(copyPass, src, dst, false); + } + + frameManager.recordUploadCommands(size, 1); + returnTransferBuffer(xfer, size); + } + + public boolean enqueueDeferredTextureUpload(ContextState st, ByteBuffer prepped, long texHandle, int x, int y, int w, int h, int level) { + final TransferThread tt = transferThread; + if (tt == null) return false; + final long size = prepped.remaining(); + final long xfer = acquireTransferBufferThreadSafe(size); + if (xfer == 0) return false; + final long mapSize = getTransferBufferMapSize(size); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped != null) { + final int prevPos = prepped.position(); + mapped.put(prepped); + prepped.position(prevPos); + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + final long seq = TransferThread.nextSeq(); + st.frameHighestEnqueuedSeq = seq; + tt.enqueue(TransferThread.TextureRegionUpload.acquire(xfer, texHandle, x, y, w, h, level, size, seq)); + tt.wake(); + return true; + } + + public void downloadFromTexture(long commandBuffer, long gpuTexture, int x, int y, int w, int h, int level, ByteBuffer output) { + downloadFromTexture(commandBuffer, gpuTexture, x, y, 0, w, h, 1, level, output); + } + + public void downloadFromTexture(long commandBuffer, long gpuTexture, int x, int y, int z, int w, int h, int d, int level, ByteBuffer output) { + final int size = output.remaining(); + + try (var stack = stackPush()) { + final SDL_GPUTransferBufferCreateInfo xferCi = SDL_GPUTransferBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD) + .size(size); + final long xfer = SDL_CreateGPUTransferBuffer(device.getDevice(), xferCi); + if (xfer == 0) { + LOG.error("Failed to create download transfer buffer: {}", SDLError.SDL_GetError()); + return; + } + + final long copyPass = SDL_BeginGPUCopyPass(commandBuffer); + if (copyPass == 0) { + LOG.error("Failed to begin copy pass for texture download: {}", SDLError.SDL_GetError()); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + return; + } + + final SDL_GPUTextureRegion src = SDL_GPUTextureRegion.calloc(stack) + .texture(gpuTexture) + .mip_level(level) + .x(x).y(y).z(z) + .w(w).h(h).d(d); + + final SDL_GPUTextureTransferInfo dst = SDL_GPUTextureTransferInfo.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + + SDL_DownloadFromGPUTexture(copyPass, src, dst); + SDL_EndGPUCopyPass(copyPass); + + final long fence = SDL_SubmitGPUCommandBufferAndAcquireFence(commandBuffer); + if (fence == 0) { + LOG.error("Failed to submit download command buffer: {}", SDLError.SDL_GetError()); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + return; + } + try { + final PointerBuffer fences = stack.pointers(fence); + SDL_WaitForGPUFences(device.getDevice(), true, fences); + } finally { + SDL_ReleaseGPUFence(device.getDevice(), fence); + } + + final long mappedPtr = nSDL_MapGPUTransferBuffer(device.getDevice(), xfer, false); + if (mappedPtr != 0) { + final ByteBuffer mapped = MemoryUtil.memByteBuffer(mappedPtr, size); + output.put(mapped); + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + } + } + + public void downloadFromBuffer(long commandBuffer, long gpuBuffer, int offset, int size, ByteBuffer output) { + try (var stack = stackPush()) { + final SDL_GPUTransferBufferCreateInfo xferCi = SDL_GPUTransferBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD) + .size(size); + final long xfer = SDL_CreateGPUTransferBuffer(device.getDevice(), xferCi); + if (xfer == 0) { + LOG.error("Failed to create download transfer buffer for buffer readback: {}", SDLError.SDL_GetError()); + return; + } + + final long copyPass = SDL_BeginGPUCopyPass(commandBuffer); + if (copyPass == 0) { + LOG.error("Failed to begin copy pass for buffer download: {}", SDLError.SDL_GetError()); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + return; + } + + final SDL_GPUBufferRegion src = SDL_GPUBufferRegion.calloc(stack) + .buffer(gpuBuffer) + .offset(offset) + .size(size); + + final SDL_GPUTransferBufferLocation dst = SDL_GPUTransferBufferLocation.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + + SDL_DownloadFromGPUBuffer(copyPass, src, dst); + SDL_EndGPUCopyPass(copyPass); + + final long fence = SDL_SubmitGPUCommandBufferAndAcquireFence(commandBuffer); + if (fence == 0) { + LOG.error("Failed to submit buffer download command buffer: {}", SDLError.SDL_GetError()); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + return; + } + try { + final PointerBuffer fences = stack.pointers(fence); + SDL_WaitForGPUFences(device.getDevice(), true, fences); + } finally { + SDL_ReleaseGPUFence(device.getDevice(), fence); + } + + final long mappedPtr = nSDL_MapGPUTransferBuffer(device.getDevice(), xfer, false); + if (mappedPtr != 0) { + final ByteBuffer mapped = MemoryUtil.memByteBuffer(mappedPtr, size); + output.put(mapped); + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + SDL_ReleaseGPUTransferBuffer(device.getDevice(), xfer); + } + } + private long defaultSampler; + private long fallbackTexture; + private long dummyVertexBuffer; + + public long getOrCreateDefaultSampler() { + if (defaultSampler != 0) return defaultSampler; + + try (var stack = stackPush()) { + final SDL_GPUSamplerCreateInfo ci = SDL_GPUSamplerCreateInfo.calloc(stack) + .min_filter(SDL_GPU_FILTER_LINEAR) + .mag_filter(SDL_GPU_FILTER_LINEAR) + .mipmap_mode(SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) + .address_mode_u(SDL_GPU_SAMPLERADDRESSMODE_REPEAT) + .address_mode_v(SDL_GPU_SAMPLERADDRESSMODE_REPEAT) + .address_mode_w(SDL_GPU_SAMPLERADDRESSMODE_REPEAT) + .min_lod(0.0f) + .max_lod(1000.0f); + + defaultSampler = SDL_CreateGPUSampler(device.getDevice(), ci); + if (defaultSampler == 0) { + LOG.error("Failed to create default sampler: {}", SDLError.SDL_GetError()); + } + } + return defaultSampler; + } + + public long getOrCreateFallbackTexture() { + if (fallbackTexture != 0) return fallbackTexture; + + try (var stack = stackPush()) { + final SDL_GPUTextureCreateInfo ci = SDL_GPUTextureCreateInfo.calloc(stack) + .type(SDL_GPU_TEXTURETYPE_2D) + .format(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM) + .usage(SDL_GPU_TEXTUREUSAGE_SAMPLER) + .width(1) + .height(1) + .layer_count_or_depth(1) + .num_levels(1); + + fallbackTexture = SDL_CreateGPUTexture(device.getDevice(), ci); + if (fallbackTexture == 0) { + LOG.error("Failed to create fallback texture: {}", SDLError.SDL_GetError()); + return 0; + } + trackTextureHandle(fallbackTexture); + } + // GL 4.4 sec 11.1.3.5: sampling an incomplete texture yields (0,0,0,1). + final byte[] texel = { 0, 0, 0, (byte) 0xFF }; + seedOneTexel(fallbackTexture, texel); + return fallbackTexture; + } + + private long fallbackStorageTexture3D; + public long getOrCreateFallbackStorageTexture3D() { + if (fallbackStorageTexture3D != 0) return fallbackStorageTexture3D; + try (var stack = stackPush()) { + final SDL_GPUTextureCreateInfo ci = SDL_GPUTextureCreateInfo.calloc(stack) + .type(SDL_GPU_TEXTURETYPE_3D) + .format(SDL_GPU_TEXTUREFORMAT_R8_UINT) + .usage(SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ + | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ + | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) + .width(1).height(1).layer_count_or_depth(1).num_levels(1); + fallbackStorageTexture3D = SDL_CreateGPUTexture(device.getDevice(), ci); + if (fallbackStorageTexture3D == 0) { + LOG.error("Failed to create fallback storage 3D texture: {}", SDLError.SDL_GetError()); + return 0; + } + trackTextureHandle(fallbackStorageTexture3D); + } + seedOneTexel(fallbackStorageTexture3D, new byte[1]); + return fallbackStorageTexture3D; + } + + private long fallbackStorageBuffer; + public long getOrCreateFallbackStorageBuffer() { + if (fallbackStorageBuffer != 0) return fallbackStorageBuffer; + try (var stack = stackPush()) { + final SDL_GPUBufferCreateInfo ci = SDL_GPUBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ + | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ) + .size(FALLBACK_STORAGE_BUFFER_BYTES); + fallbackStorageBuffer = SDL_CreateGPUBuffer(device.getDevice(), ci); + if (fallbackStorageBuffer == 0) { + LOG.error("Failed to create fallback storage buffer: {}", SDLError.SDL_GetError()); + return 0; + } + trackBufferHandle(fallbackStorageBuffer); + } + seedZeroBuffer(fallbackStorageBuffer, FALLBACK_STORAGE_BUFFER_BYTES); + return fallbackStorageBuffer; + } + + private static final int FALLBACK_STORAGE_BUFFER_BYTES = 16; + + /** + * Mesa binds a null image view for an unbound image unit and dispatches anyway + * (st_atom_image.c st_convert_image_from_unit). SDL has no null descriptor and dereferences the + * handle, so the equivalent is a real 1x1x1 zeroed texture whose format and target match the + * shader's declaration. + */ + private final Long2LongOpenHashMap computeStandInTextures = new Long2LongOpenHashMap(); + + static long computeStandInKey(int glFormat, int glTarget, boolean readWrite) { + return ((long) glFormat << 33) | ((long) glTarget << 1) | (readWrite ? 1L : 0L); + } + + public long getOrCreateComputeStandInTexture(int glFormat, int glTarget, boolean readWrite) { + final long key = computeStandInKey(glFormat, glTarget, readWrite); + synchronized (computeStandInTextures) { + final long cached = computeStandInTextures.get(key); + if (cached != 0) return cached; + } + final int sdlFormat = mapTextureFormat(glFormat); + final int usage = readWrite ? SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE : SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ; + final long handle; + try (var stack = stackPush()) { + final SDL_GPUTextureCreateInfo ci = SDL_GPUTextureCreateInfo.calloc(stack) + .type(mapTextureType(glTarget)) + .format(sdlFormat) + .usage(usage) + .width(1).height(1).layer_count_or_depth(1).num_levels(1); + handle = SDL_CreateGPUTexture(device.getDevice(), ci); + } + if (handle == 0) { + LOG.error("Failed to create compute stand-in texture for GL format 0x{} target 0x{}: {}", + Integer.toHexString(glFormat), Integer.toHexString(glTarget), SDLError.SDL_GetError()); + return 0; + } + trackTextureHandle(handle); + seedOneTexel(handle, new byte[Math.max(1, PixelOps.sdlFormatTexelBytes(sdlFormat))]); + synchronized (computeStandInTextures) { + final long raced = computeStandInTextures.get(key); + if (raced != 0) { + releaseTextureHandle(handle); + return raced; + } + computeStandInTextures.put(key, handle); + } + return handle; + } + + private void seedOneTexel(long texture, byte[] texel) { + if (texture == 0) return; + final long xfer = createTransferBuffer(texel.length); + if (xfer == 0) return; + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, false, texel.length); + if (mapped != null) mapped.put(texel); + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (cb != 0) { + try (var stack = stackPush()) { + final long copyPass = SDL_BeginGPUCopyPass(cb); + final SDL_GPUTextureTransferInfo src = SDL_GPUTextureTransferInfo.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + final SDL_GPUTextureRegion dst = SDL_GPUTextureRegion.calloc(stack) + .texture(texture) + .mip_level(0) + .x(0).y(0).z(0) + .w(1).h(1).d(1); + SDL_UploadToGPUTexture(copyPass, src, dst, false); + SDL_EndGPUCopyPass(copyPass); + } + SDL_SubmitGPUCommandBuffer(cb); + } + releaseTransferBuffer(xfer); + } + + private void seedZeroBuffer(long buffer, int bytes) { + if (buffer == 0) return; + final long xfer = createTransferBuffer(bytes); + if (xfer == 0) return; + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, false, bytes); + if (mapped != null) MemoryUtil.memSet(mapped, 0); + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (cb != 0) { + try (var stack = stackPush()) { + final long copyPass = SDL_BeginGPUCopyPass(cb); + final SDL_GPUTransferBufferLocation src = SDL_GPUTransferBufferLocation.calloc(stack) + .transfer_buffer(xfer) + .offset(0); + final SDL_GPUBufferRegion dst = SDL_GPUBufferRegion.calloc(stack) + .buffer(buffer) + .offset(0) + .size(bytes); + SDL_UploadToGPUBuffer(copyPass, src, dst, false); + SDL_EndGPUCopyPass(copyPass); + } + SDL_SubmitGPUCommandBuffer(cb); + } + releaseTransferBuffer(xfer); + } + + private long dummyColorTarget; + public long getOrCreateDummyColorTarget() { + if (dummyColorTarget != 0) return dummyColorTarget; + try (var stack = stackPush()) { + final SDL_GPUTextureCreateInfo ci = SDL_GPUTextureCreateInfo.calloc(stack) + .type(SDL_GPU_TEXTURETYPE_2D) + .format(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM) + .usage(SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) + .width(1).height(1).layer_count_or_depth(1).num_levels(1); + dummyColorTarget = SDL_CreateGPUTexture(device.getDevice(), ci); + } + trackTextureHandle(dummyColorTarget); + return dummyColorTarget; + } + + private static final int DUMMY_VBO_SIZE = 16 * 16; + public static final int ATTRIB_RING_BLOCKS = 2048 * Device.FRAMES_IN_FLIGHT; + public static final int ATTRIB_RING_CHUNK_BLOCKS = 64; + private static final int ATTRIB_RING_CHUNKS = ATTRIB_RING_BLOCKS / ATTRIB_RING_CHUNK_BLOCKS; + private final AtomicLong attribRingCounter = new AtomicLong(); + + public int nextAttribRingChunkOffset() { + final int chunk = 1 + (int) (attribRingCounter.getAndIncrement() % (ATTRIB_RING_CHUNKS - 1)); + return chunk * ATTRIB_RING_CHUNK_BLOCKS * DUMMY_VBO_SIZE; + } + + public long getOrCreateDummyVertexBuffer() { + if (dummyVertexBuffer != 0) return dummyVertexBuffer; + + try (var stack = stackPush()) { + dummyVertexBuffer = SDL_CreateGPUBuffer(device.getDevice(), SDL_GPUBufferCreateInfo.calloc(stack).usage(SDL_GPU_BUFFERUSAGE_VERTEX).size(ATTRIB_RING_BLOCKS * DUMMY_VBO_SIZE)); + if (dummyVertexBuffer == 0) { + LOG.error("Failed to create dummy vertex buffer: {}", SDLError.SDL_GetError()); + return 0; + } + trackBufferHandle(dummyVertexBuffer); + + final long xfer = createTransferBuffer(DUMMY_VBO_SIZE); + if (xfer != 0) { + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, false, DUMMY_VBO_SIZE); + if (mapped != null) { + final FloatBuffer fb = mapped.asFloatBuffer(); + for (int i = 0; i < 16; i++) { + if (i == 1) { + fb.put(1.0f).put(1.0f).put(1.0f).put(1.0f); // color: white + } else { + fb.put(0.0f).put(0.0f).put(0.0f).put(1.0f); // default: (0,0,0,1) + } + } + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + + final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (cb != 0) { + final long copyPass = SDL_BeginGPUCopyPass(cb); + final var src = SDL_GPUTransferBufferLocation.calloc(stack).transfer_buffer(xfer).offset(0); + final var dst = SDL_GPUBufferRegion.calloc(stack).buffer(dummyVertexBuffer).offset(0).size(DUMMY_VBO_SIZE); + SDL_UploadToGPUBuffer(copyPass, src, dst, false); + SDL_EndGPUCopyPass(copyPass); + SDL_SubmitGPUCommandBuffer(cb); + } + releaseTransferBufferHandle(xfer); + } + } + return dummyVertexBuffer; + } + + private static final int ATTRIB_SLOT_SIZE = 16; + + private long attribDefaultXfer; + + public void uploadAttribDefaults(long copyPass, float[] defaults, int dirtyMask) { + if (dummyVertexBuffer == 0 || dirtyMask == 0) return; + + if (attribDefaultXfer == 0) { + attribDefaultXfer = createTransferBuffer(DUMMY_VBO_SIZE); + if (attribDefaultXfer == 0) return; + } + + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), attribDefaultXfer, true, DUMMY_VBO_SIZE); + if (mapped == null) return; + final FloatBuffer fb = mapped.asFloatBuffer(); + int wmask = dirtyMask; + while (wmask != 0) { + final int slot = Integer.numberOfTrailingZeros(wmask); + final int base = slot * 4; + fb.position(base); + fb.put(defaults[base]).put(defaults[base + 1]).put(defaults[base + 2]).put(defaults[base + 3]); + wmask &= wmask - 1; + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), attribDefaultXfer); + + try (var stack = stackPush()) { + int mask = dirtyMask; + while (mask != 0) { + final int slot = Integer.numberOfTrailingZeros(mask); + final int offset = slot * ATTRIB_SLOT_SIZE; + final var src = SDL_GPUTransferBufferLocation.calloc(stack).transfer_buffer(attribDefaultXfer).offset(offset); + final var dst = SDL_GPUBufferRegion.calloc(stack).buffer(dummyVertexBuffer).offset(offset).size(ATTRIB_SLOT_SIZE); + SDL_UploadToGPUBuffer(copyPass, src, dst, false); + mask &= mask - 1; + } + } + } + + public int mapTextureFormat(int glFormat) { + return mapTextureFormat(glFormat, preferredD24, preferredD24S8); + } + + public static int mapTextureFormat(int glFormat, int preferredD24, int preferredD24S8) { + return switch (glFormat) { + case GL11.GL_RGBA, GL11.GL_RGBA8 -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + case GL11.GL_RGB, GL11.GL_RGB8 -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; // RGB -> RGBA promotion + case GL11.GL_ALPHA, GL11.GL_LUMINANCE, GL11.GL_LUMINANCE_ALPHA -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; // expanded to RGBA at upload + case GL21.GL_SRGB8_ALPHA8 -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB; + case GL30.GL_RGBA32F -> SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT; + case GL11.GL_RGBA16 -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UNORM; + case GL30.GL_RGBA16F -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT; + case GL30.GL_R8 -> SDL_GPU_TEXTUREFORMAT_R8_UNORM; + case GL30.GL_RG8 -> SDL_GPU_TEXTUREFORMAT_R8G8_UNORM; + case GL30.GL_R16F -> SDL_GPU_TEXTUREFORMAT_R16_FLOAT; + case GL30.GL_RG16F -> SDL_GPU_TEXTUREFORMAT_R16G16_FLOAT; + case GL30.GL_R32F -> SDL_GPU_TEXTUREFORMAT_R32_FLOAT; + case GL30.GL_RG32F -> SDL_GPU_TEXTUREFORMAT_R32G32_FLOAT; + case GL11.GL_DEPTH_COMPONENT -> SDL_GPU_TEXTUREFORMAT_D32_FLOAT; // unsized -> D32F default + case GL14.GL_DEPTH_COMPONENT16 -> SDL_GPU_TEXTUREFORMAT_D16_UNORM; + case GL14.GL_DEPTH_COMPONENT24 -> preferredD24; + case GL14.GL_DEPTH_COMPONENT32, GL30.GL_DEPTH_COMPONENT32F -> SDL_GPU_TEXTUREFORMAT_D32_FLOAT; + case GL30.GL_DEPTH24_STENCIL8 -> preferredD24S8; + case GL30.GL_DEPTH32F_STENCIL8 -> SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT; + case GL30.GL_R8UI -> SDL_GPU_TEXTUREFORMAT_R8_UINT; + case GL30.GL_R16UI -> SDL_GPU_TEXTUREFORMAT_R16_UINT; + case GL30.GL_R32UI -> SDL_GPU_TEXTUREFORMAT_R32_UINT; + case GL30.GL_RG8UI -> SDL_GPU_TEXTUREFORMAT_R8G8_UINT; + case GL30.GL_RG16UI -> SDL_GPU_TEXTUREFORMAT_R16G16_UINT; + case GL30.GL_RG32UI -> SDL_GPU_TEXTUREFORMAT_R32G32_UINT; + case GL30.GL_RGBA8UI -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT; + case GL30.GL_RGBA16UI -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UINT; + case GL30.GL_RGBA32UI -> SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT; + case GL30.GL_R8I -> SDL_GPU_TEXTUREFORMAT_R8_INT; + case GL30.GL_R16I -> SDL_GPU_TEXTUREFORMAT_R16_INT; + case GL30.GL_R32I -> SDL_GPU_TEXTUREFORMAT_R32_INT; + case GL30.GL_RG8I -> SDL_GPU_TEXTUREFORMAT_R8G8_INT; + case GL30.GL_RG16I -> SDL_GPU_TEXTUREFORMAT_R16G16_INT; + case GL30.GL_RG32I -> SDL_GPU_TEXTUREFORMAT_R32G32_INT; + case GL30.GL_RGBA8I -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_INT; + case GL30.GL_RGBA16I -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_INT; + case GL30.GL_RGBA32I -> SDL_GPU_TEXTUREFORMAT_R32G32B32A32_INT; + case GL30.GL_RGB8UI -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT; + case GL30.GL_RGB16UI -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UINT; + case GL30.GL_RGB32UI -> SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT; + case GL30.GL_RGB8I -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_INT; + case GL30.GL_RGB16I -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_INT; + case GL30.GL_RGB32I -> SDL_GPU_TEXTUREFORMAT_R32G32B32A32_INT; + case GL30.GL_R11F_G11F_B10F -> SDL_GPU_TEXTUREFORMAT_R11G11B10_UFLOAT; + case GL31.GL_R8_SNORM -> SDL_GPU_TEXTUREFORMAT_R8_SNORM; + case GL31.GL_RG8_SNORM -> SDL_GPU_TEXTUREFORMAT_R8G8_SNORM; + case GL31.GL_RGB8_SNORM -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_SNORM; // RGB SNORM -> RGBA SNORM promotion + case GL31.GL_RGBA8_SNORM -> SDL_GPU_TEXTUREFORMAT_R8G8B8A8_SNORM; + case GL31.GL_RGBA16_SNORM -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_SNORM; + case GL31.GL_RGB16_SNORM -> SDL_GPU_TEXTUREFORMAT_R16G16B16A16_SNORM; // RGB SNORM -> RGBA SNORM promotion + default -> { + LOG.warn("Unmapped GL texture format: 0x{}", Integer.toHexString(glFormat)); + yield SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + } + }; + } + + private static boolean isDepthFormat(int sdlFormat) { + return sdlFormat == SDL_GPU_TEXTUREFORMAT_D16_UNORM + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D24_UNORM + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D32_FLOAT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT; + } + + static boolean isIntegerFormat(int sdlFormat) { + return sdlFormat == SDL_GPU_TEXTUREFORMAT_R8_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R8G8_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16G16_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32G32_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R8_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R8G8_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R8G8B8A8_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16G16_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R16G16B16A16_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32G32_INT + || sdlFormat == SDL_GPU_TEXTUREFORMAT_R32G32B32A32_INT; + } + + private static int mapTextureType(int glTarget) { + return switch (glTarget) { + case GL11.GL_TEXTURE_2D -> SDL_GPU_TEXTURETYPE_2D; + case GL13.GL_TEXTURE_CUBE_MAP -> SDL_GPU_TEXTURETYPE_CUBE; + case GL12.GL_TEXTURE_3D -> SDL_GPU_TEXTURETYPE_3D; + case GL30.GL_TEXTURE_2D_ARRAY -> SDL_GPU_TEXTURETYPE_2D_ARRAY; + default -> SDL_GPU_TEXTURETYPE_2D; + }; + } + + private void releaseAllAndClear(Int2LongOpenHashMap map, LongConsumer release) { + for (long handle : map.values()) { + if (handle != 0) release.accept(handle); + } + map.clear(); + } + + public void shutdown() { + flushDeferredReleases(); + + final long dev = device.getDevice(); + if (attribDefaultXfer != 0) { + releaseTransferBufferHandle(attribDefaultXfer); + attribDefaultXfer = 0; + } + + drainTransferBufferPool(); + drainGpuBufferPool(); + + samplerCache.releaseAll(device); + + if (defaultSampler != 0) { + SDL_ReleaseGPUSampler(dev, defaultSampler); + defaultSampler = 0; + } + if (fallbackTexture != 0) { + releaseTextureHandle(fallbackTexture); + fallbackTexture = 0; + } + if (dummyVertexBuffer != 0) { + releaseBufferHandle(dummyVertexBuffer); + dummyVertexBuffer = 0; + } + + if (fallbackStorageBuffer != 0) { + releaseBufferHandle(fallbackStorageBuffer); + fallbackStorageBuffer = 0; + } + if (dummyColorTarget != 0) { + releaseTextureHandle(dummyColorTarget); + dummyColorTarget = 0; + } + if (fallbackStorageTexture3D != 0) { + releaseTextureHandle(fallbackStorageTexture3D); + fallbackStorageTexture3D = 0; + } + synchronized (computeStandInTextures) { + for (long handle : computeStandInTextures.values()) releaseTextureHandle(handle); + computeStandInTextures.clear(); + } + + releaseAllAndClear(textureHandles, this::releaseTextureHandle); + releaseAllAndClear(bufferHandles, this::releaseBufferHandle); + releaseAllAndClear(samplerHandles, h -> SDL_ReleaseGPUSampler(dev, h)); + bufferSizes.clear(); + bufferUsages.clear(); + bufferGlUsages.clear(); + bufferStorageFlags.clear(); + undefinedContentBuffers.clear(); + + for (FboState fbo : fboStates.values()) fbo.free(); + fboStates.clear(); + for (ByteBuffer bb : uboShadows.values()) memFree(bb); + uboShadows.clear(); + for (ByteBuffer bb : eboShadows.values()) memFree(bb); + eboShadows.clear(); + eboShadowWanted.clear(); + for (ByteBuffer bb : arrayShadows.values()) memFree(bb); + arrayShadows.clear(); + arrayShadowWanted.clear(); + for (ByteBuffer bb : pboStagingData.values()) memFree(bb); + pboStagingData.clear(); + for (PersistentMapping pm : persistentMappings.values()) { + untrackPersistentDirty(pm); + releasePersistentStaging(pm); + } + persistentMappings.clear(); + mappingsVersion++; + } + + public record TextureMeta(int glTarget, int glFormat, int sdlFormat, int width, int height, int depth, int levels, int usage) {} +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureOps.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureOps.java new file mode 100644 index 000000000..5e2929212 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureOps.java @@ -0,0 +1,224 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL14; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDL_GPUBlitInfo; +import org.lwjgl.sdl.SDL_GPUTextureLocation; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class TextureOps { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private final Device device; + private final FrameManager frameManager; + private final ResourceManager resourceManager; + private final FBOClearTracker fboClearTracker; + + public TextureOps(Device device, FrameManager frameManager, ResourceManager resourceManager, FBOClearTracker fboClearTracker) { + this.device = device; + this.frameManager = frameManager; + this.resourceManager = resourceManager; + this.fboClearTracker = fboClearTracker; + } + + public void releaseTextureForRealloc(ContextState st, int glId) { + fboClearTracker.scrubPendingClearsForTexture(st, glId); + resourceManager.releaseTextureHandleForRealloc(glId); + } + + public boolean uploadTextureRegion(ContextState st, int glId, ResourceManager.TextureMeta meta, long texHandle, ByteBuffer src, int x, int y, int w, int h, int level, int srcFormat, int srcType) { + if (meta == null || level >= meta.levels()) return false; + if (src == null || texHandle == 0 || frameManager.getCommandBuffer() == 0) return false; + final boolean defer = st.deferUploads && !resourceManager.isFboAttachment(glId); + final long cp = defer ? 0L : frameManager.ensureCopyPass(); + if (!defer && cp == 0) return false; + final ByteBuffer unpacked = PixelOps.applyUnpackPixelStore(src, w, h, srcFormat, srcType, st.pixelStore); + final ByteBuffer prepped = PixelOps.prepareUploadBuffer(srcFormat, meta.sdlFormat(), unpacked, w, h); + try { + final boolean handled = defer && resourceManager.enqueueDeferredTextureUpload(st, prepped, texHandle, x, y, w, h, level); + if (!handled) { + final long inlineCp = (cp != 0) ? cp : frameManager.ensureCopyPass(); + if (inlineCp == 0) return false; + resourceManager.uploadToTexture(inlineCp, prepped, texHandle, x, y, w, h, level); + } + } finally { + if (prepped != unpacked) MemoryUtil.memFree(prepped); + if (unpacked != src) MemoryUtil.memFree(unpacked); + } + trackMipUploadForTexture(glId, level, meta.levels()); + return true; + } + + public void texParameteri(ContextState st, int pname, int param, int glId) { + if (glId == 0) return; + final TextureSamplerState ss = resourceManager.getOrCreateTexSamplerState(glId); + switch (pname) { + case GL11.GL_TEXTURE_MIN_FILTER -> ss.minFilter = param; + case GL11.GL_TEXTURE_MAG_FILTER -> ss.magFilter = param; + case GL11.GL_TEXTURE_WRAP_S -> ss.wrapS = param; + case GL11.GL_TEXTURE_WRAP_T -> ss.wrapT = param; + case GL12.GL_TEXTURE_WRAP_R -> ss.wrapR = param; + case GL12.GL_TEXTURE_MAX_LEVEL -> { + ss.maxLevel = param; return; + } + case GL12.GL_TEXTURE_MIN_LOD -> ss.minLod = (float) param; + case GL12.GL_TEXTURE_MAX_LOD -> ss.maxLod = (float) param; + case GL14.GL_TEXTURE_COMPARE_MODE -> ss.compareMode = param; + case GL14.GL_TEXTURE_COMPARE_FUNC -> ss.compareFunc = param; + default -> { return; } + } + ss.sdlSampler = 0; + st.samplerBindGen++; + } + + public void texParameterf(ContextState st, int pname, float param, int glId) { + if (glId == 0) return; + final TextureSamplerState ss = resourceManager.getOrCreateTexSamplerState(glId); + switch (pname) { + case GL12.GL_TEXTURE_MIN_LOD -> ss.minLod = param; + case GL12.GL_TEXTURE_MAX_LOD -> ss.maxLod = param; + case GL14.GL_TEXTURE_LOD_BIAS -> ss.lodBias = param; + case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> ss.maxAnisotropy = param; + default -> { texParameteri(st, pname, (int) param, glId); return; } + } + ss.sdlSampler = 0; + st.samplerBindGen++; + } + + public void readbackTexture(long texHandle, int x, int y, int w, int h, int level, ByteBuffer output) { + if (texHandle == 0 || output == null) return; + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + + if (texHandle == frameManager.getSwapchainTexture()) { + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + resourceManager.downloadFromTexture(cb, texHandle, x, y, w, h, level, output); + frameManager.reacquireCommandBuffer(); + } else { + final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (cb == 0) return; + resourceManager.downloadFromTexture(cb, texHandle, x, y, w, h, level, output); + } + } + + public void copyTexSubImageImpl(ContextState st, int destGlId, int level, int xoffset, int yoffset, int x, int y, int width, int height) { + if (destGlId == 0) return; + final long destTex = resourceManager.getTextureHandle(destGlId); + if (destTex == 0) return; + + final FboState fbo = resourceManager.getFbo(st.boundReadFboId); + if (fbo == null) return; + + final ResourceManager.TextureMeta destMeta = resourceManager.getTextureMeta(destGlId); + final boolean isDepthDest = destMeta != null && PixelOps.isDepthFormat(destMeta.sdlFormat()); + final long srcTex = isDepthDest ? fbo.depthTexture : fbo.colorTextures[fbo.readBufferIndex]; + if (srcTex == 0) return; + + if (isDepthDest) { + copyTexture(srcTex, x, y, destTex, xoffset, yoffset, width, height); + return; + } + + final int srcGlId = fbo.colorGlIds[fbo.readBufferIndex]; + final ResourceManager.TextureMeta srcMeta = srcGlId != 0 ? resourceManager.getTextureMeta(srcGlId) : null; + if (srcMeta != null && destMeta != null && srcMeta.sdlFormat() == destMeta.sdlFormat()) { + copyTexture(srcTex, x, y, destTex, xoffset, yoffset, width, height); + } else { + blitTexture(srcTex, x, y, width, height, destTex, xoffset, yoffset, width, height, GL11.GL_NEAREST); + } + } + + public static boolean canCopyInsteadOfBlit(ResourceManager.TextureMeta src, ResourceManager.TextureMeta dst, int srcW, int srcH, int dstW, int dstH) { + return src != null && dst != null && src.sdlFormat() == dst.sdlFormat() && srcW > 0 && srcH > 0 && srcW == dstW && srcH == dstH; + } + + public void copyTexture(long srcTex, int srcX, int srcY, long dstTex, int dstX, int dstY, int w, int h) { + final long cp = frameManager.ensureCopyPass(); + if (cp == 0) return; + try (var stack = MemoryStack.stackPush()) { + final var src = SDL_GPUTextureLocation.calloc(stack).texture(srcTex).x(srcX).y(srcY); + final var dst = SDL_GPUTextureLocation.calloc(stack).texture(dstTex).x(dstX).y(dstY); + SDL_CopyGPUTextureToTexture(cp, src, dst, w, h, 1, false); + } + } + + public void blitTexture(long srcTex, int srcX, int srcY, int srcW, int srcH, long dstTex, int dstX, int dstY, int dstW, int dstH, int glFilter) { + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + + try (var stack = MemoryStack.stackPush()) { + final var info = SDL_GPUBlitInfo.calloc(stack); + info.source(s -> s.texture(srcTex).x(srcX).y(srcY).w(srcW).h(srcH)); + info.destination(d -> d.texture(dstTex).x(dstX).y(dstY).w(dstW).h(dstH)); + info.filter(glFilter == GL11.GL_LINEAR ? SDL_GPU_FILTER_LINEAR : SDL_GPU_FILTER_NEAREST); + info.flip_mode(0); + frameManager.noteBlit(); + SDL_BlitGPUTexture(cb, info); + } + } + + public void trackMipUploadForTexture(int glId, int level, int levels) { + final FrameManager.FrameState f = frameManager.frame(); + if (level > 0) { + f.pendingMipGen.remove(glId); + } else if (levels > 1) { + f.pendingMipGen.add(glId); + } + } + + public void clearPendingMipGen(int glId) { + frameManager.frame().pendingMipGen.remove(glId); + } + + public void drainPendingMipGen() { + final FrameManager.FrameState f = frameManager.frame(); + if (f.pendingMipGen.isEmpty()) return; + final long uploadCb = f.commandBuffer != 0 ? f.commandBuffer : f.pendingUploadCommandBuffer; + if (uploadCb == 0) { f.pendingMipGen.clear(); return; } + + final int[] glIds = f.pendingMipGen.toIntArray(); + f.pendingMipGen.clear(); + + frameManager.endCopyPassIfActive(); + frameManager.endRenderPassIfActive(); + + for (int glId : glIds) { + final long handle = resourceManager.getTextureHandle(glId); + if (handle == 0) continue; + final ResourceManager.TextureMeta meta = resourceManager.getTextureMeta(glId); + if (meta == null || meta.levels() <= 1) continue; + SDL_GenerateMipmapsForGPUTexture(uploadCb, handle); + } + + if (f.commandBuffer == uploadCb) { + if (!SDL_SubmitGPUCommandBuffer(uploadCb)) { + LOG.error("drainPendingMipGen: failed to submit frame CB: {}", SDLError.SDL_GetError()); + } + f.commandBuffer = 0; + } else { + if (!SDL_SubmitGPUCommandBuffer(uploadCb)) { + LOG.error("drainPendingMipGen: failed to submit pending-upload CB: {}", SDLError.SDL_GetError()); + } + f.pendingUploadCommandBuffer = 0; + f.pendingUploadBytes = 0; + f.pendingUploadCommands = 0; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureSamplerState.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureSamplerState.java new file mode 100644 index 000000000..eb4b801e8 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TextureSamplerState.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.lwjgl.opengl.GL11; + +public final class TextureSamplerState { + public int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR; + public int magFilter = GL11.GL_LINEAR; + public int wrapS = GL11.GL_REPEAT; + public int wrapT = GL11.GL_REPEAT; + public int wrapR = GL11.GL_REPEAT; + public int maxLevel = -1; + public float minLod = -1000.0f; + public float maxLod = 1000.0f; + public float lodBias = 0.0f; + public float maxAnisotropy = 1.0f; + public int compareMode = 0; + public int compareFunc = GL11.GL_LEQUAL; + public long sdlSampler; +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThread.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThread.java new file mode 100644 index 000000000..b69ecc34a --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThread.java @@ -0,0 +1,548 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.sdl.SDL_GPUBufferLocation; +import org.lwjgl.sdl.SDL_GPUBufferRegion; +import org.lwjgl.sdl.SDL_GPUTextureRegion; +import org.lwjgl.sdl.SDL_GPUTextureTransferInfo; +import org.lwjgl.sdl.SDL_GPUTransferBufferLocation; +import org.lwjgl.sdl.SDLError; + +import java.nio.ByteBuffer; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.LockSupport; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.lwjgl.system.MemoryUtil; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class TransferThread { + private static final long P_TRANSFER_BUSY_PCT = Tracy.plotHandle("sdl.transferBusyPct", TracyBackend.PLOT_FORMAT_PERCENTAGE); + private static final long P_TRANSFER_BYTES = Tracy.plotHandle("sdl.transferBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_TRANSFER_SUBMITS = Tracy.plotHandle("sdl.transferSubmits"); + private static final long P_TRANSFER_WAIT_US = Tracy.plotHandle("sdl.transferWaitUs"); + private static final long P_TRANSFER_UNPARKS_SENT = Tracy.plotHandle("sdl.transferUnparksSent"); + private static final long P_TRANSFER_UNPARKS_ELIDED = Tracy.plotHandle("sdl.transferUnparksElided"); + private static final Tracy.ZoneId Z_SDL_UPLOAD = Tracy.zoneId("sdlUpload", Tracy.COLOR_WORKER); + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU-Transfer"); + + private static final AtomicLong SEQ = new AtomicLong(); + + public static long nextSeq() { return SEQ.incrementAndGet(); } + public static long currentSeq() { return SEQ.get(); } + + private final Device device; + private final ResourceManager resourceManager; + private final Thread thread; + private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); + private volatile long submittedSeq; + private volatile long flushRequestedSeq; + private volatile boolean shutdown; + private volatile boolean parked; + private volatile long unparksSent; + private volatile long unparksElided; + private long lastUnparksSent; + private long lastUnparksElided; + + // Debug stats + private int frameUploads; + private long frameBytes; + private int frameCBSubmits; + private long maxWaitNs; + private long totalCBSubmits; + private long totalBytes; + private int pendingFrameUploads; + private long pendingFrameBytes; + private int pendingFrameCBSubmits; + private long pendingActiveNanos; + private long lastStatsResetNanos; + private volatile long pendingFrameWaitNanos; + + private static final long FLUSH_COALESCE_BYTES = 8L * 1024 * 1024; + private static final int FLUSH_COALESCE_COMMANDS = 128; + private static final long WAKE_COALESCE_ENQUEUES = 16; + + private long openCB; + private long openCopyPass; + private long openHighestSeq; + private long openBytes; + private int openCount; + private final LongArrayList pendingReturnHandles = new LongArrayList(); + private final LongArrayList pendingReturnSizes = new LongArrayList(); + + private final SDL_GPUTransferBufferLocation srcLoc = SDL_GPUTransferBufferLocation.calloc(); + private final SDL_GPUBufferRegion dstRegion = SDL_GPUBufferRegion.calloc(); + private final SDL_GPUBufferLocation srcBufLoc = SDL_GPUBufferLocation.calloc(); + private final SDL_GPUBufferLocation dstBufLoc = SDL_GPUBufferLocation.calloc(); + private final SDL_GPUTextureTransferInfo texXferInfo = SDL_GPUTextureTransferInfo.calloc(); + private final SDL_GPUTextureRegion texRegion = SDL_GPUTextureRegion.calloc(); + + private static final ConcurrentLinkedQueue FREE_POOL = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue pendingFrees = new ConcurrentLinkedQueue<>(); + + public TransferThread(Device device, ResourceManager resourceManager) { + this.device = device; + this.resourceManager = resourceManager; + this.thread = new Thread(this::run, "SDL-GPU-Transfer"); + this.thread.setDaemon(true); + this.thread.start(); + } + + public Thread getThread() { return thread; } + + public long getSubmittedSeq() { return submittedSeq; } + + public void enqueue(DeferredUpload upload) { + queue.offer(upload); + if (shouldWakeOnEnqueue(upload.seq())) wake(); + } + + static boolean shouldWakeOnEnqueue(long seq) { + return (seq & (WAKE_COALESCE_ENQUEUES - 1)) == 0; + } + + public void wake() { + if (parked) { + unparksSent++; + LockSupport.unpark(thread); + } else { + unparksElided++; + } + } + + public void freeAfterSeq(ByteBuffer buf, long seq) { + if (buf == null) return; + if (seq <= submittedSeq) { MemoryUtil.memFree(buf); return; } + PendingFree pf = FREE_POOL.poll(); + if (pf == null) pf = new PendingFree(); + pf.seq = seq; + pf.buf = buf; + pendingFrees.offer(pf); + wake(); + } + + private void drainDuePendingFrees() { + final long sub = submittedSeq; + PendingFree head = pendingFrees.peek(); + while (head != null && head.seq <= sub) { + pendingFrees.poll(); + MemoryUtil.memFree(head.buf); + head.buf = null; + FREE_POOL.offer(head); + head = pendingFrees.peek(); + } + } + + private void drainAllPendingFreesOnShutdown() { + PendingFree pf; + while ((pf = pendingFrees.poll()) != null) { + MemoryUtil.memFree(pf.buf); + pf.buf = null; + FREE_POOL.offer(pf); + } + } + + private final Object submittedLock = new Object(); + + public void requestFlushUpTo(long seq) { + if (seq <= submittedSeq || seq <= flushRequestedSeq) return; + flushRequestedSeq = seq; + LockSupport.unpark(thread); + } + + public void awaitSubmittedUpTo(long seq) { + if (submittedSeq >= seq) return; + if (seq > flushRequestedSeq) flushRequestedSeq = seq; + LockSupport.unpark(thread); + final long startNs = System.nanoTime(); + synchronized (submittedLock) { + while (submittedSeq < seq) { + try { + submittedLock.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + } + final long waitNs = System.nanoTime() - startNs; + if (waitNs > maxWaitNs) maxWaitNs = waitNs; + pendingFrameWaitNanos += waitNs; + } + + public void shutdown() { + shutdown = true; + LockSupport.unpark(thread); + } + + public void resetFrameStats() { + frameUploads = pendingFrameUploads; + frameBytes = pendingFrameBytes; + frameCBSubmits = pendingFrameCBSubmits; + if (Tracy.ENABLED) { + final long now = System.nanoTime(); + final long wall = now - lastStatsResetNanos; + lastStatsResetNanos = now; + Tracy.plotInt(P_TRANSFER_BUSY_PCT, wall > 0 ? Math.min(100, pendingActiveNanos * 100 / wall) : 0); + Tracy.plotInt(P_TRANSFER_BYTES, pendingFrameBytes); + Tracy.plotInt(P_TRANSFER_SUBMITS, pendingFrameCBSubmits); + Tracy.plotInt(P_TRANSFER_WAIT_US, pendingFrameWaitNanos / 1000); + Tracy.plotInt(P_TRANSFER_UNPARKS_SENT, unparksSent - lastUnparksSent); + Tracy.plotInt(P_TRANSFER_UNPARKS_ELIDED, unparksElided - lastUnparksElided); + lastUnparksSent = unparksSent; + lastUnparksElided = unparksElided; + } + pendingFrameWaitNanos = 0; + pendingFrameUploads = 0; + pendingFrameBytes = 0; + pendingFrameCBSubmits = 0; + pendingActiveNanos = 0; + maxWaitNs = 0; + } + + static boolean shouldFlush(boolean hasOpenCB, long flushRequestedSeq, long submittedSeq, long openBytes, int openCount) { + if (!hasOpenCB) return false; + return flushRequestedSeq > submittedSeq || openBytes >= FLUSH_COALESCE_BYTES || openCount >= FLUSH_COALESCE_COMMANDS; + } + + private void run() { + LOG.info("Transfer thread started"); + while (!shutdown) { + final long workStart = Tracy.ENABLED ? System.nanoTime() : 0L; + // Drain all pending uploads + DeferredUpload upload = queue.poll(); + if (upload != null) { + do { + processOne(upload); + upload = queue.poll(); + } while (upload != null); + } + + if (shouldFlush(openCB != 0, flushRequestedSeq, submittedSeq, openBytes, openCount)) { + flushOpenCB(); + } + + if (Tracy.ENABLED) pendingActiveNanos += System.nanoTime() - workStart; + + if (queue.isEmpty() && !shutdown) { + parked = true; + if (queue.isEmpty() && !shutdown && flushRequestedSeq <= submittedSeq) { + LockSupport.parkNanos(1_000_000L); // 1ms + } + parked = false; + } + } + if (openCB != 0) flushOpenCB(); + drainAllPendingFreesOnShutdown(); + srcLoc.free(); + dstRegion.free(); + srcBufLoc.free(); + dstBufLoc.free(); + texXferInfo.free(); + texRegion.free(); + LOG.info("Transfer thread stopped"); + } + + private void processOne(DeferredUpload upload) { + Tracy.beginZone(Z_SDL_UPLOAD); + try { + processOneInner(upload); + } finally { + Tracy.endZone(); + } + } + + private void processOneInner(DeferredUpload upload) { + if (upload instanceof StagingReadUpload sr) { + final long size = sr.size; + final long xfer = resourceManager.acquireTransferBufferThreadSafe(size); + if (xfer == 0) { + LOG.error("Failed to acquire transfer buffer for StagingRead (size {})", size); + StagingReadUpload.release(sr); + return; + } + final long mapSize = resourceManager.getTransferBufferMapSize(size); + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(device.getDevice(), xfer, true, mapSize); + if (mapped != null) { + final ByteBuffer src = sr.stagingBuffer; + final int prevPos = src.position(); + final int prevLim = src.limit(); + src.limit((int) (sr.srcOffset + size)).position((int) sr.srcOffset); + mapped.put(src); + src.limit(prevLim).position(prevPos); + } + SDL_UnmapGPUTransferBuffer(device.getDevice(), xfer); + recordBufferUpload(xfer, size, sr.dstGpuBuffer, sr.dstOffset, sr.seq, sr.cycle); + StagingReadUpload.release(sr); + } else if (upload instanceof PreCopiedUpload pc) { + recordBufferUpload(pc.transferBuffer, pc.size, pc.dstGpuBuffer, pc.dstOffset, pc.seq, pc.cycle); + PreCopiedUpload.release(pc); + } else if (upload instanceof GpuCopyUpload gc) { + recordGpuCopy(gc.srcHandle, gc.dstHandle, gc.readOffset, gc.writeOffset, gc.size, gc.seq); + GpuCopyUpload.release(gc); + } else if (upload instanceof TextureRegionUpload tr) { + recordTextureUpload(tr.transferBuffer, tr.texHandle, tr.x, tr.y, tr.w, tr.h, tr.level, tr.size, tr.seq); + TextureRegionUpload.release(tr); + } + } + + private boolean ensureOpenCB() { + if (openCB != 0) return true; + openCB = SDL_AcquireGPUCommandBuffer(device.getDevice()); + if (openCB == 0) { + LOG.error("Failed to acquire GPU command buffer: {}", SDLError.SDL_GetError()); + return false; + } + openCopyPass = SDL_BeginGPUCopyPass(openCB); + return true; + } + + private void recordBufferUpload(long transferBuffer, long size, long dstGpuBuffer, long dstOffset, long seq, boolean cycle) { + if (transferBuffer == 0) return; + if (!ensureOpenCB()) { + resourceManager.returnTransferBufferThreadSafe(transferBuffer, size); + return; + } + srcLoc.transfer_buffer(transferBuffer).offset(0); + dstRegion.buffer(dstGpuBuffer).offset((int) dstOffset).size((int) size); + SDL_UploadToGPUBuffer(openCopyPass, srcLoc, dstRegion, cycle); + + openHighestSeq = Math.max(openHighestSeq, seq); + openBytes += size; + openCount++; + pendingReturnHandles.add(transferBuffer); + pendingReturnSizes.add(size); + } + + private void recordGpuCopy(long srcHandle, long dstHandle, long readOffset, long writeOffset, long size, long seq) { + if (!ensureOpenCB()) return; + srcBufLoc.buffer(srcHandle).offset((int) readOffset); + dstBufLoc.buffer(dstHandle).offset((int) writeOffset); + SDL_CopyGPUBufferToBuffer(openCopyPass, srcBufLoc, dstBufLoc, (int) size, false); + + openHighestSeq = Math.max(openHighestSeq, seq); + openBytes += size; + openCount++; + } + + private void recordTextureUpload(long transferBuffer, long texHandle, int x, int y, int w, int h, int level, long size, long seq) { + if (transferBuffer == 0) return; + if (!ensureOpenCB()) { + resourceManager.returnTransferBufferThreadSafe(transferBuffer, size); + return; + } + texXferInfo.transfer_buffer(transferBuffer).offset(0); + texRegion.texture(texHandle).mip_level(level).x(x).y(y).z(0).w(w).h(h).d(1); + SDL_UploadToGPUTexture(openCopyPass, texXferInfo, texRegion, false); + + openHighestSeq = Math.max(openHighestSeq, seq); + openBytes += size; + openCount++; + pendingReturnHandles.add(transferBuffer); + pendingReturnSizes.add(size); + } + + private void flushOpenCB() { + if (openCB == 0) return; + + SDL_EndGPUCopyPass(openCopyPass); + if (!SDL_SubmitGPUCommandBuffer(openCB)) { + LOG.error("Failed to submit transfer command buffer: {}", SDLError.SDL_GetError()); + } + + synchronized (submittedLock) { + submittedSeq = openHighestSeq; + submittedLock.notifyAll(); + } + + drainDuePendingFrees(); + + for (int i = 0, n = pendingReturnHandles.size(); i < n; i++) { + resourceManager.returnTransferBufferThreadSafe(pendingReturnHandles.getLong(i), pendingReturnSizes.getLong(i)); + } + pendingReturnHandles.clear(); + pendingReturnSizes.clear(); + + pendingFrameUploads += openCount; + pendingFrameBytes += openBytes; + pendingFrameCBSubmits++; + totalCBSubmits++; + totalBytes += openBytes; + + openCB = 0; + openCopyPass = 0; + openHighestSeq = 0; + openBytes = 0; + openCount = 0; + } + + public String getDebugInfo() { + if (totalCBSubmits == 0) return "Transfer: idle"; + return String.format("Transfer: %d uploads, %s, %d CBs, wait %.2fms (total: %d CBs, %s), unparks %d sent/%d elided", + frameUploads, + formatBytes(frameBytes), + frameCBSubmits, + maxWaitNs / 1_000_000.0, + totalCBSubmits, + formatBytes(totalBytes), + unparksSent, + unparksElided); + } + + private static String formatBytes(long bytes) { + if (bytes < 1024) return bytes + "B"; + if (bytes < 1024 * 1024) return String.format("%.1fKB", bytes / 1024.0); + return String.format("%.1fMB", bytes / (1024.0 * 1024.0)); + } + + private static final class PendingFree { + long seq; + ByteBuffer buf; + } + + public sealed interface DeferredUpload permits StagingReadUpload, PreCopiedUpload, GpuCopyUpload, TextureRegionUpload { + public long seq(); + } + + public static final class StagingReadUpload implements DeferredUpload { + private static final ConcurrentLinkedQueue POOL = new ConcurrentLinkedQueue<>(); + + public ByteBuffer stagingBuffer; + public long srcOffset; + public long size; + public long dstGpuBuffer; + public long dstOffset; + public long seq; + public boolean cycle; + + private StagingReadUpload() {} + + public static StagingReadUpload acquire(ByteBuffer stagingBuffer, long srcOffset, long size, long dstGpuBuffer, long dstOffset, long seq, boolean cycle) { + StagingReadUpload obj = POOL.poll(); + if (obj == null) obj = new StagingReadUpload(); + obj.stagingBuffer = stagingBuffer; + obj.srcOffset = srcOffset; + obj.size = size; + obj.dstGpuBuffer = dstGpuBuffer; + obj.dstOffset = dstOffset; + obj.seq = seq; + obj.cycle = cycle; + return obj; + } + + public static void release(StagingReadUpload obj) { + obj.stagingBuffer = null; + POOL.offer(obj); + } + + @Override public long seq() { return seq; } + } + + public static final class PreCopiedUpload implements DeferredUpload { + private static final ConcurrentLinkedQueue POOL = new ConcurrentLinkedQueue<>(); + + public long transferBuffer; + public long size; + public long dstGpuBuffer; + public long dstOffset; + public long seq; + public boolean cycle; + + private PreCopiedUpload() {} + + public static PreCopiedUpload acquire(long transferBuffer, long size, long dstGpuBuffer, long dstOffset, long seq, boolean cycle) { + PreCopiedUpload obj = POOL.poll(); + if (obj == null) obj = new PreCopiedUpload(); + obj.transferBuffer = transferBuffer; + obj.size = size; + obj.dstGpuBuffer = dstGpuBuffer; + obj.dstOffset = dstOffset; + obj.seq = seq; + obj.cycle = cycle; + return obj; + } + + public static void release(PreCopiedUpload obj) { + POOL.offer(obj); + } + + @Override public long seq() { return seq; } + } + + public static final class GpuCopyUpload implements DeferredUpload { + private static final ConcurrentLinkedQueue POOL = new ConcurrentLinkedQueue<>(); + + public long srcHandle; + public long dstHandle; + public long readOffset; + public long writeOffset; + public long size; + public long seq; + + private GpuCopyUpload() {} + + public static GpuCopyUpload acquire(long srcHandle, long dstHandle, long readOffset, + long writeOffset, long size, long seq) { + GpuCopyUpload obj = POOL.poll(); + if (obj == null) obj = new GpuCopyUpload(); + obj.srcHandle = srcHandle; + obj.dstHandle = dstHandle; + obj.readOffset = readOffset; + obj.writeOffset = writeOffset; + obj.size = size; + obj.seq = seq; + return obj; + } + + public static void release(GpuCopyUpload obj) { + POOL.offer(obj); + } + + @Override public long seq() { return seq; } + } + + public static final class TextureRegionUpload implements DeferredUpload { + private static final ConcurrentLinkedQueue POOL = new ConcurrentLinkedQueue<>(); + + public long transferBuffer; + public long texHandle; + public int x; + public int y; + public int w; + public int h; + public int level; + public long size; + public long seq; + + private TextureRegionUpload() {} + + public static TextureRegionUpload acquire(long transferBuffer, long texHandle, int x, int y, int w, int h, int level, long size, long seq) { + TextureRegionUpload obj = POOL.poll(); + if (obj == null) obj = new TextureRegionUpload(); + obj.transferBuffer = transferBuffer; + obj.texHandle = texHandle; + obj.x = x; + obj.y = y; + obj.w = w; + obj.h = h; + obj.level = level; + obj.size = size; + obj.seq = seq; + return obj; + } + + public static void release(TextureRegionUpload obj) { + POOL.offer(obj); + } + + @Override public long seq() { return seq; } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArena.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArena.java new file mode 100644 index 000000000..4581065f5 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArena.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +public final class UploadArena { + public static final int INITIAL_CAPACITY = 16 * 1024 * 1024; + + private static final int ALIGNMENT = 16; + + private int capacity = INITIAL_CAPACITY; + private int growTo = INITIAL_CAPACITY; + private int offset; + private int copyCount; + + public int reserve(int size) { + if (size < 0) return -1; + final int at = (offset + ALIGNMENT - 1) & -ALIGNMENT; + if ((long) at + size > capacity) return -1; + offset = at + size; + copyCount++; + return at; + } + + public boolean fits(int size) { + return size >= 0 && size <= capacity; + } + + public void requestGrow(int minSize) { + while (growTo < minSize) growTo <<= 1; + } + + public boolean applyGrow() { + if (growTo > capacity) { + capacity = growTo; + return true; + } + return false; + } + + public void reset() { + offset = 0; + copyCount = 0; + } + + public int copyCount() { return copyCount; } + public int usedBytes() { return offset; } + public int capacity() { return capacity; } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBinder.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBinder.java new file mode 100644 index 000000000..79f5415d2 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBinder.java @@ -0,0 +1,181 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.FormatMap; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.TextureSamplerState; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL30; + +import org.lwjgl.sdl.SDL_GPUSamplerCreateInfo; +import org.lwjgl.sdl.SDL_GPUTextureSamplerBinding; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class SamplerBinder { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final LongOpenHashSet loggedFallbackSubs = new LongOpenHashSet(); + + private final Device device; + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + + public SamplerBinder(Device device, ResourceManager resourceManager, ShaderManager shaderManager) { + this.device = device; + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + } + + public long getSamplerForTexture(int glTexId) { + final TextureSamplerState ss = resourceManager.getTexSamplerState(glTexId); + if (ss == null) return resourceManager.getOrCreateDefaultSampler(); + return getOrCreateSdlSampler(ss); + } + + public long getSamplerForUnit(ContextState st, int glUnit, int glTexId) { + if (glUnit >= 0 && glUnit < st.boundSamplerObjects.length && st.boundSamplerObjects[glUnit] != 0) { + final TextureSamplerState ss = resourceManager.getSamplerObject(st.boundSamplerObjects[glUnit]); + if (ss != null) return getOrCreateSdlSampler(ss); + } + if (glTexId != 0) return getSamplerForTexture(glTexId); + return resourceManager.getOrCreateDefaultSampler(); + } + + public long getOrCreateSdlSampler(TextureSamplerState ss) { + if (ss.sdlSampler != 0) return ss.sdlSampler; + + final SamplerCache.Key key = new SamplerCache.Key( + ss.minFilter, ss.magFilter, ss.wrapS, ss.wrapT, ss.wrapR, + ss.minLod, ss.maxLod, ss.lodBias, + ss.maxAnisotropy, ss.compareMode, ss.compareFunc); + + final long handle = resourceManager.samplerCache().getOrCreate(key, this::createSamplerForKey); + ss.sdlSampler = handle; + return handle != 0 ? handle : resourceManager.getOrCreateDefaultSampler(); + } + + private long createSamplerForKey(SamplerCache.Key key) { + try (var stack = MemoryStack.stackPush()) { + final boolean enableCompare = key.compareMode() == GL30.GL_COMPARE_REF_TO_TEXTURE; + final boolean wantsMipmap = FormatMap.isMipmapMinFilter(key.minFilter()); + final float effectiveMaxLod = wantsMipmap ? key.maxLod() : 0.0f; + final SDL_GPUSamplerCreateInfo ci = SDL_GPUSamplerCreateInfo.calloc(stack) + .min_filter(FormatMap.mapFilter(key.minFilter())) + .mag_filter(FormatMap.mapFilter(key.magFilter())) + .mipmap_mode(FormatMap.mapMipmapMode(key.minFilter())) + .address_mode_u(FormatMap.mapAddressMode(key.wrapS())) + .address_mode_v(FormatMap.mapAddressMode(key.wrapT())) + .address_mode_w(FormatMap.mapAddressMode(key.wrapR())) + .min_lod(key.minLod()) + .max_lod(effectiveMaxLod) + .mip_lod_bias(key.lodBias()) + .enable_anisotropy(key.maxAnisotropy() > 1.0f) + .max_anisotropy(key.maxAnisotropy()) + .enable_compare(enableCompare) + .compare_op(enableCompare ? FormatMap.mapCompareOp(key.compareFunc()) : SDL_GPU_COMPAREOP_INVALID); + + return SDL_CreateGPUSampler(device.getDevice(), ci); + } + } + + public void bindSamplers(long renderPass, ContextState st, long bindCb) { + if (st.boundProgram == 0) return; + if (st.boundProgram == st.lastAppliedSamplerProgram && st.samplerBindGen == st.lastAppliedSamplerBindGen && bindCb == st.lastAppliedSamplerCb) { + return; + } + final long fallbackTexture = resourceManager.getOrCreateFallbackTexture(); + if (fallbackTexture == 0) return; + + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (prog == null || !prog.linked) { + bindFallbackForStage(renderPass, st, fallbackTexture, true); + bindFallbackForStage(renderPass, st, fallbackTexture, false); + st.lastAppliedSamplerProgram = st.boundProgram; + st.lastAppliedSamplerBindGen = st.samplerBindGen; + st.lastAppliedSamplerCb = bindCb; + return; + } + + bindStageSamplers(renderPass, st, prog, fallbackTexture, true); + bindStageSamplers(renderPass, st, prog, fallbackTexture, false); + st.lastAppliedSamplerProgram = st.boundProgram; + st.lastAppliedSamplerBindGen = st.samplerBindGen; + st.lastAppliedSamplerCb = bindCb; + } + + private void bindStageSamplers(long renderPass, ContextState st, ShaderManager.ProgramObject prog, long fallbackTexture, boolean fragment) { + final int raw = fragment ? prog.fragmentResources.numSamplers() : prog.vertexResources.numSamplers(); + if (raw > ContextState.MAX_SAMPLERS) { + throw new IllegalStateException("program " + st.boundProgram + " has " + raw + " " + (fragment ? "fragment" : "vertex") + " samplers; MAX=" + ContextState.MAX_SAMPLERS); + } + if (raw <= 0) return; + final SDL_GPUTextureSamplerBinding.Buffer bindings = (fragment ? st.fragSamplerBindings : st.vertSamplerBindings).position(0).limit(raw); + final long bindingsBase = MemoryUtil.memAddress(bindings); + final int[] samplerUnits = SamplerLookup.resolvedUnits(prog, fragment); + final long[] lastTex = fragment ? st.lastFragSamplerTex : st.lastVertSamplerTex; + final long[] lastSmp = fragment ? st.lastFragSamplerSmp : st.lastVertSamplerSmp; + final int lastProg = fragment ? st.lastFragSamplerProgram : st.lastVertSamplerProgram; + final boolean programChanged = st.boundProgram != lastProg; + boolean anyChanged = programChanged; + for (int i = 0; i < raw; i++) { + final int glUnit = samplerUnits[i]; + final int glTexId = (glUnit >= 0 && glUnit < st.boundTextures.length) ? st.boundTextures[glUnit] : 0; + long texHandle = (glTexId != 0) ? resourceManager.getTextureHandle(glTexId) : 0; + if (texHandle == 0) { + texHandle = fallbackTexture; + if (loggedFallbackSubs.add(((long) st.boundProgram << 32) | (glUnit & 0xFFFFFFFFL))) { + LOG.warn("[SamplerBinder] program {} {} sampler slot {} (glUnit={} glTexId={}) has no SDL texture; substituting 2D fallback", st.boundProgram, fragment ? "fragment" : "vertex", i, glUnit, glTexId); + } + } + final long sampler = getSamplerForUnit(st, glUnit, glTexId); + if (programChanged || texHandle != lastTex[i] || sampler != lastSmp[i]) { + anyChanged = true; + final long elemAddr = bindingsBase + (long) i * SDL_GPUTextureSamplerBinding.SIZEOF; + MemoryAccess.putAddress(elemAddr + SDL_GPUTextureSamplerBinding.TEXTURE, texHandle); + MemoryAccess.putAddress(elemAddr + SDL_GPUTextureSamplerBinding.SAMPLER, sampler); + lastTex[i] = texHandle; + lastSmp[i] = sampler; + } + } + if (anyChanged) { + if (fragment) { + SDL_BindGPUFragmentSamplers(renderPass, 0, bindings); + st.lastFragSamplerProgram = st.boundProgram; + } else { + SDL_BindGPUVertexSamplers(renderPass, 0, bindings); + st.lastVertSamplerProgram = st.boundProgram; + } + } + } + + private void bindFallbackForStage(long renderPass, ContextState st, long fallbackTexture, boolean fragment) { + final int count = ContextState.MAX_SAMPLERS; + final SDL_GPUTextureSamplerBinding.Buffer bindings = (fragment ? st.fragSamplerBindings : st.vertSamplerBindings).position(0).limit(count); + final long bindingsBase = MemoryUtil.memAddress(bindings); + final long sampler = resourceManager.getOrCreateDefaultSampler(); + final long[] lastTex = fragment ? st.lastFragSamplerTex : st.lastVertSamplerTex; + final long[] lastSmp = fragment ? st.lastFragSamplerSmp : st.lastVertSamplerSmp; + for (int i = 0; i < count; i++) { + final long elemAddr = bindingsBase + (long) i * SDL_GPUTextureSamplerBinding.SIZEOF; + MemoryAccess.putAddress(elemAddr + SDL_GPUTextureSamplerBinding.TEXTURE, fallbackTexture); + MemoryAccess.putAddress(elemAddr + SDL_GPUTextureSamplerBinding.SAMPLER, sampler); + lastTex[i] = 0L; + lastSmp[i] = 0L; + } + if (fragment) { + SDL_BindGPUFragmentSamplers(renderPass, 0, bindings); + st.lastFragSamplerProgram = 0; + } else { + SDL_BindGPUVertexSamplers(renderPass, 0, bindings); + st.lastVertSamplerProgram = 0; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCache.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCache.java new file mode 100644 index 000000000..3e2efeff4 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCache.java @@ -0,0 +1,78 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.concurrent.locks.ReentrantLock; + +import static org.lwjgl.sdl.SDLGPU.SDL_ReleaseGPUSampler; + +public final class SamplerCache { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + public record Key(int minFilter, int magFilter, int wrapS, int wrapT, int wrapR, float minLod, float maxLod, float lodBias, float maxAnisotropy, int compareMode, int compareFunc) {} + + @FunctionalInterface + public interface Factory { + long create(Key key); + } + + private final Object2LongOpenHashMap handles = new Object2LongOpenHashMap<>(); + private final LongArrayList allHandles = new LongArrayList(); + private final ReentrantLock lock = new ReentrantLock(); + + public SamplerCache() { + handles.defaultReturnValue(0L); + } + + public long getOrCreate(Key key, Factory factory) { + lock.lock(); + try { + final long existing = handles.getLong(key); + if (existing != 0L) return existing; + final long fresh = factory.create(key); + if (fresh != 0L) { + handles.put(key, fresh); + allHandles.add(fresh); + } + return fresh; + } finally { + lock.unlock(); + } + } + + public void releaseAll(Device device) { + lock.lock(); + try { + final long dev = device.getDevice(); + if (dev == 0L) { + handles.clear(); + allHandles.clear(); + return; + } + final int n = allHandles.size(); + for (int i = 0; i < n; i++) { + final long h = allHandles.getLong(i); + if (h != 0L) SDL_ReleaseGPUSampler(dev, h); + } + LOG.info("SamplerCache: released {} cached SDL samplers", n); + handles.clear(); + allHandles.clear(); + } finally { + lock.unlock(); + } + } + + public int size() { + lock.lock(); + try { + return handles.size(); + } finally { + lock.unlock(); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerLookup.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerLookup.java new file mode 100644 index 000000000..47f643052 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerLookup.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import it.unimi.dsi.fastutil.objects.Object2IntMap; + +import java.util.List; + +public final class SamplerLookup { + private SamplerLookup() {} + + public static int[] resolvedUnits(ShaderManager.ProgramObject prog, boolean fragment) { + if (prog.samplerUnitsDirty) { + prog.vertexSamplerUnits = resolveStage(prog.vertexSamplerNames, prog.samplerTextureUnits, prog.vertexResources.numSamplers()); + prog.fragmentSamplerUnits = resolveStage(prog.fragmentSamplerNames, prog.samplerTextureUnits, prog.fragmentResources.numSamplers()); + prog.samplerUnitsDirty = false; + } + return fragment ? prog.fragmentSamplerUnits : prog.vertexSamplerUnits; + } + + private static int[] resolveStage(List samplerNames, Object2IntMap textureUnits, int samplerCount) { + if (samplerCount <= 0) return new int[0]; + final int[] units = new int[samplerCount]; + for (int i = 0; i < samplerCount; i++) { + units[i] = getSamplerTextureUnit(samplerNames, textureUnits, i); + } + return units; + } + + public static int getSamplerTextureUnit(List samplerNames, Object2IntMap textureUnits, int bindingIndex) { + if (bindingIndex >= samplerNames.size()) return bindingIndex; + final String name = samplerNames.get(bindingIndex); + final int unit = textureUnits.getInt(name); + if (unit != -1) return unit; + return switch (name) { + case "tex", "texture", "gtexture" -> 0; + case "lightmap" -> 1; + case "normals" -> 2; + case "specular" -> 3; + default -> bindingIndex; + }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinder.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinder.java new file mode 100644 index 000000000..d5974af92 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinder.java @@ -0,0 +1,117 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryUtil; + +import static org.lwjgl.sdl.SDLGPU.nSDL_BindGPUFragmentStorageBuffers; +import static org.lwjgl.sdl.SDLGPU.nSDL_BindGPUVertexStorageBuffers; + +public final class StorageBufferBinder { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + private final IntOpenHashSet nullHandleWarned = new IntOpenHashSet(); + + public StorageBufferBinder(ResourceManager resourceManager, ShaderManager shaderManager) { + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + } + + public void bindStorageBuffers(long renderPass, ContextState st, long bindCb) { + if (st.boundProgram == 0) return; + if (st.boundProgram == st.lastAppliedStorageBufProgram + && st.ssboBindGen == st.lastAppliedStorageBufBindGen + && bindCb == st.lastAppliedStorageBufCb) { + return; + } + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (prog == null || !prog.linked) { + bindFallbackForStage(renderPass, st, true); + bindFallbackForStage(renderPass, st, false); + st.lastAppliedStorageBufProgram = st.boundProgram; + st.lastAppliedStorageBufBindGen = st.ssboBindGen; + st.lastAppliedStorageBufCb = bindCb; + return; + } + + bindStage(renderPass, st, prog, true); + bindStage(renderPass, st, prog, false); + + st.lastAppliedStorageBufProgram = st.boundProgram; + st.lastAppliedStorageBufBindGen = st.ssboBindGen; + st.lastAppliedStorageBufCb = bindCb; + } + + private void bindStage(long renderPass, ContextState st, ShaderManager.ProgramObject prog, boolean fragment) { + final ShaderManager.GraphicsBindingMap map = fragment ? prog.fragmentGraphicsBindingMap : prog.vertexGraphicsBindingMap; + final int[] slots = map.roSsboGlSlots(); + final int count = slots.length; + if (count == 0) return; + if (count > ContextState.MAX_STORAGE_BUFFERS_PER_STAGE) { + throw new IllegalStateException("program " + st.boundProgram + " has " + count + " " + (fragment ? "fragment" : "vertex") + " SSBOs; MAX=" + ContextState.MAX_STORAGE_BUFFERS_PER_STAGE); + } + + final PointerBuffer ptrs = (fragment ? st.fragStorageBufBindings : st.vertStorageBufBindings).position(0).limit(count); + final long[] lastBuf = fragment ? st.lastFragStorageBuf : st.lastVertStorageBuf; + final int lastProg = fragment ? st.lastFragStorageBufProgram : st.lastVertStorageBufProgram; + boolean anyChanged = st.boundProgram != lastProg; + + final long fallback = resourceManager.getOrCreateFallbackStorageBuffer(); + for (int i = 0; i < count; i++) { + final int glIndex = slots[i]; + final int glBufId = (glIndex >= 0 && glIndex < ContextState.MAX_INDEXED_BUFFERS) ? st.boundSsboByIndex[glIndex] : 0; + long bufHandle = (glBufId != 0) ? resourceManager.getBufferHandle(glBufId) : 0; + if (bufHandle == 0) { + if (nullHandleWarned.add(st.boundProgram)) { + LOG.warn("StorageBufferBinder: program {} {} stage SSBO at glIndex={} has no bound buffer (glBufId={}); substituting fallback", st.boundProgram, fragment ? "fragment" : "vertex", glIndex, glBufId); + } + if (fallback == 0) return; + bufHandle = fallback; + } + ptrs.put(i, bufHandle); + if (bufHandle != lastBuf[i]) { + anyChanged = true; + lastBuf[i] = bufHandle; + } + } + + if (anyChanged) { + if (Tracy.ENABLED) st.ssboBinds++; + if (fragment) { + nSDL_BindGPUFragmentStorageBuffers(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastFragStorageBufProgram = st.boundProgram; + } else { + nSDL_BindGPUVertexStorageBuffers(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastVertStorageBufProgram = st.boundProgram; + } + } + } + + private void bindFallbackForStage(long renderPass, ContextState st, boolean fragment) { + final int count = ContextState.MAX_STORAGE_BUFFERS_PER_STAGE; + final long fallback = resourceManager.getOrCreateFallbackStorageBuffer(); + if (fallback == 0) return; + final PointerBuffer ptrs = (fragment ? st.fragStorageBufBindings : st.vertStorageBufBindings).position(0).limit(count); + final long[] lastBuf = fragment ? st.lastFragStorageBuf : st.lastVertStorageBuf; + for (int i = 0; i < count; i++) { + ptrs.put(i, fallback); + lastBuf[i] = 0L; + } + if (Tracy.ENABLED) st.ssboBinds++; + if (fragment) { + nSDL_BindGPUFragmentStorageBuffers(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastFragStorageBufProgram = 0; + } else { + nSDL_BindGPUVertexStorageBuffers(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastVertStorageBufProgram = 0; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageTextureBinder.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageTextureBinder.java new file mode 100644 index 000000000..594176747 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageTextureBinder.java @@ -0,0 +1,115 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryUtil; + +import java.util.List; + +import static org.lwjgl.sdl.SDLGPU.nSDL_BindGPUFragmentStorageTextures; +import static org.lwjgl.sdl.SDLGPU.nSDL_BindGPUVertexStorageTextures; + +public final class StorageTextureBinder { + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private final ResourceManager resourceManager; + private final ShaderManager shaderManager; + private final IntOpenHashSet nullHandleWarned = new IntOpenHashSet(); + + public StorageTextureBinder(ResourceManager resourceManager, ShaderManager shaderManager) { + this.resourceManager = resourceManager; + this.shaderManager = shaderManager; + } + + public void bindStorageTextures(long renderPass, ContextState st, long bindCb) { + if (st.boundProgram == 0) return; + if (st.boundProgram == st.lastAppliedStorageTexProgram && st.samplerBindGen == st.lastAppliedStorageTexBindGen && bindCb == st.lastAppliedStorageTexCb) { + return; + } + final ShaderManager.ProgramObject prog = shaderManager.getProgram(st.boundProgram); + if (prog == null || !prog.linked) { + bindFallbackForStage(renderPass, st, true); + bindFallbackForStage(renderPass, st, false); + st.lastAppliedStorageTexProgram = st.boundProgram; + st.lastAppliedStorageTexBindGen = st.samplerBindGen; + st.lastAppliedStorageTexCb = bindCb; + return; + } + + bindStage(renderPass, st, prog, true); + bindStage(renderPass, st, prog, false); + + st.lastAppliedStorageTexProgram = st.boundProgram; + st.lastAppliedStorageTexBindGen = st.samplerBindGen; + st.lastAppliedStorageTexCb = bindCb; + } + + private void bindStage(long renderPass, ContextState st, ShaderManager.ProgramObject prog, boolean fragment) { + final List imgNames = fragment ? prog.fragmentImageNames : prog.vertexImageNames; + final int count = imgNames.size(); + if (count == 0) return; + if (count > ContextState.MAX_IMAGE_UNITS) { + throw new IllegalStateException("program " + st.boundProgram + " has " + count + " " + (fragment ? "fragment" : "vertex") + " storage images; MAX=" + ContextState.MAX_IMAGE_UNITS); + } + + final PointerBuffer ptrs = (fragment ? st.fragStorageTexBindings : st.vertStorageTexBindings).position(0).limit(count); + final long[] lastTex = fragment ? st.lastFragStorageTex : st.lastVertStorageTex; + final int lastProg = fragment ? st.lastFragStorageTexProgram : st.lastVertStorageTexProgram; + final boolean programChanged = st.boundProgram != lastProg; + boolean anyChanged = programChanged; + + final long fallback = resourceManager.getOrCreateFallbackStorageTexture3D(); + for (int i = 0; i < count; i++) { + final String name = imgNames.get(i); + final int glUnit = prog.imageTextureUnits.getInt(name); + final int glTexId = (glUnit >= 0 && glUnit < ContextState.MAX_IMAGE_UNITS) ? st.boundStorageTextureByUnit[glUnit] : 0; + long texHandle = (glTexId != 0) ? resourceManager.getTextureHandle(glTexId) : 0; + if (texHandle == 0) { + if (nullHandleWarned.add(st.boundProgram)) { + LOG.warn("StorageTextureBinder: program {} {} stage image '{}' has no bound texture (glUnit={} glTexId={}); substituting fallback", st.boundProgram, fragment ? "fragment" : "vertex", name, glUnit, glTexId); + } + if (fallback == 0) return; + texHandle = fallback; + } + ptrs.put(i, texHandle); + if (texHandle != lastTex[i]) { + anyChanged = true; + lastTex[i] = texHandle; + } + } + + if (anyChanged) { + if (fragment) { + nSDL_BindGPUFragmentStorageTextures(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastFragStorageTexProgram = st.boundProgram; + } else { + nSDL_BindGPUVertexStorageTextures(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastVertStorageTexProgram = st.boundProgram; + } + } + } + + private void bindFallbackForStage(long renderPass, ContextState st, boolean fragment) { + final int count = ContextState.MAX_IMAGE_UNITS; + final long fallback = resourceManager.getOrCreateFallbackStorageTexture3D(); + if (fallback == 0) return; + final PointerBuffer ptrs = (fragment ? st.fragStorageTexBindings : st.vertStorageTexBindings).position(0).limit(count); + final long[] lastTex = fragment ? st.lastFragStorageTex : st.lastVertStorageTex; + for (int i = 0; i < count; i++) { + ptrs.put(i, fallback); + lastTex[i] = 0L; + } + if (fragment) { + nSDL_BindGPUFragmentStorageTextures(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastFragStorageTexProgram = 0; + } else { + nSDL_BindGPUVertexStorageTextures(renderPass, 0, MemoryUtil.memAddress(ptrs), count); + st.lastVertStorageTexProgram = 0; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClipZRemap.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClipZRemap.java new file mode 100644 index 000000000..66cec9191 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClipZRemap.java @@ -0,0 +1,51 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import java.util.ArrayList; +import java.util.List; + +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.applyEdits; + +public final class ClipZRemap { + + private static final String INJECTION_STD = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;\n"; + + private ClipZRemap() {} + + public static String injectGLToVulkanClipZ(String source) { + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(source); + } catch (Exception e) { + return source; + } + final ArrayList edits = new ArrayList<>(1); + collectEdits(root, edits); + return edits.isEmpty() ? source : applyEdits(source, edits); + } + + public static void collectEdits(GLSLParser.Translation_unitContext root, List edits) { + final int[] mainCloseBraceIdx = { -1 }; + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void enterFunction_definition(GLSLParser.Function_definitionContext ctx) { + if (mainCloseBraceIdx[0] >= 0) return; + final GLSLParser.Function_prototypeContext proto = ctx.function_prototype(); + if (proto == null || proto.IDENTIFIER() == null) return; + if (!"main".equals(proto.IDENTIFIER().getText())) return; + final GLSLParser.Compound_statement_no_new_scopeContext body = ctx.compound_statement_no_new_scope(); + if (body == null || body.RIGHT_BRACE() == null) return; + mainCloseBraceIdx[0] = body.RIGHT_BRACE().getSymbol().getStartIndex(); + } + }, root); + + if (mainCloseBraceIdx[0] < 0) return; + final int idx = mainCloseBraceIdx[0]; + edits.add(new Edit(idx, idx - 1, INJECTION_STD)); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/MatrixMarshal.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/MatrixMarshal.java new file mode 100644 index 000000000..e2d25aaac --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/MatrixMarshal.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import java.nio.FloatBuffer; + +public final class MatrixMarshal { + private MatrixMarshal() {} + + public static void marshalMatrixToColumnMajor(FloatBuffer src, int srcPos, int count, int size, boolean transpose, float[] dst, int dstPos) { + final int floatsPerMatrix = size * size; + if (transpose) { + for (int e = 0; e < count; e++) { + final int sBase = srcPos + e * floatsPerMatrix; + final int dBase = dstPos + e * floatsPerMatrix; + for (int col = 0; col < size; col++) { + for (int row = 0; row < size; row++) { + dst[dBase + col * size + row] = src.get(sBase + row * size + col); + } + } + } + } else { + for (int e = 0; e < count; e++) { + src.get(srcPos + e * floatsPerMatrix, dst, dstPos + e * floatsPerMatrix, floatsPerMatrix); + } + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java new file mode 100644 index 000000000..4309a59f9 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java @@ -0,0 +1,203 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.List; +import java.util.Set; + +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.applyEdits; + +public final class PerFrameBlockInjector { + + private static final String SHADOWED_PREFIX = "angelica_pfb_unused_"; + + private PerFrameBlockInjector() {} + + public static String inject(String source, PerFrameUniformBlock perFrame, PerFrameUniformBlock perPass) { + final PerFrameUniformBlock[] blocks = new PerFrameUniformBlock[ShaderManager.BLOCK_COUNT]; + blocks[ShaderManager.BLOCK_PER_FRAME] = normalize(perFrame); + blocks[ShaderManager.BLOCK_PER_PASS] = normalize(perPass); + if (blocks[0] == null && blocks[1] == null) return source; + + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(source); + } catch (Exception e) { + return source; + } + + final int insertAt = firstDeclarationStart(root); + if (insertAt < 0) return source; + + final Map memberTypes = new LinkedHashMap<>(); + final Object2IntOpenHashMap memberBlock = new Object2IntOpenHashMap<>(); + memberBlock.defaultReturnValue(-1); + for (int b = 0; b < blocks.length; b++) { + if (blocks[b] == null) continue; + for (Member m : blocks[b].members()) { + memberTypes.put(m.name(), std140Type(m.type())); + memberBlock.put(m.name(), b); + } + } + + final List stripEdits = new ArrayList<>(); + final IntArrayList stripBlocks = new IntArrayList(); + final Set shadowed = new HashSet<>(); + classifyDeclarations(root, memberTypes, memberBlock, stripEdits, stripBlocks, shadowed); + + final Set referenced = referencedMembers(root, memberTypes.keySet(), shadowed); + final boolean[] injected = new boolean[blocks.length]; + boolean anyInjected = false; + for (int b = 0; b < blocks.length; b++) { + if (blocks[b] == null) continue; + for (Member m : blocks[b].members()) { + if (referenced.contains(m.name())) { injected[b] = true; anyInjected = true; break; } + } + } + if (!anyInjected) return source; + + final List edits = new ArrayList<>(stripEdits.size() + 2); + final StringBuilder blockDecls = new StringBuilder(128); + for (int b = 0; b < blocks.length; b++) { + if (injected[b]) appendBlockText(blockDecls, b, blocks[b].members(), shadowed); + } + edits.add(new Edit(insertAt, insertAt - 1, blockDecls.toString())); + for (int i = 0; i < stripEdits.size(); i++) { + if (injected[stripBlocks.getInt(i)]) edits.add(stripEdits.get(i)); + } + return applyEdits(source, edits); + } + + private static PerFrameUniformBlock normalize(PerFrameUniformBlock block) { + return (block == null || block.isEmpty()) ? null : block; + } + + static String std140Type(UniformType type) { + return switch (type) { + case FLOAT -> "float"; + case INT, BOOL -> "int"; + case VEC2 -> "vec2"; + case VEC3 -> "vec3"; + case VEC4 -> "vec4"; + case VEC2I -> "ivec2"; + case VEC3I -> "ivec3"; + case VEC4I -> "ivec4"; + case MAT3 -> "mat3"; + case MAT4 -> "mat4"; + }; + } + + private static void appendBlockText(StringBuilder sb, int blockIndex, List members, Set shadowed) { + sb.append("layout(std140, binding = ").append(ShaderManager.BLOCK_BINDINGS[blockIndex]) + .append(") readonly buffer ").append(ShaderManager.BLOCK_NAMES[blockIndex]).append(" {\n"); + for (Member m : members) { + final String name = shadowed.contains(m.name()) ? SHADOWED_PREFIX + m.name() : m.name(); + sb.append(" ").append(std140Type(m.type())).append(' ').append(name).append(";\n"); + } + sb.append("};\n"); + } + + private static int firstDeclarationStart(GLSLParser.Translation_unitContext root) { + final List decls = root.external_declaration(); + return (decls == null || decls.isEmpty()) ? -1 : decls.get(0).getStart().getStartIndex(); + } + + private static void classifyDeclarations(GLSLParser.Translation_unitContext root, Map memberTypes, Object2IntOpenHashMap memberBlock, List stripEdits, IntArrayList stripBlocks, Set shadowed) { + for (GLSLParser.External_declarationContext ed : root.external_declaration()) { + final GLSLParser.DeclarationContext ctx = ed.declaration(); + if (ctx == null) continue; + + final List declared = declaredNames(ctx); + if (declared.isEmpty()) continue; + + int block = -1; + for (String name : declared) { + final int b = memberBlock.getInt(name); + if (b >= 0) { block = b; break; } + } + if (block < 0) continue; + + if (isReplaceableUniform(ctx, declared, memberTypes)) { + stripEdits.add(new Edit(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), "")); + stripBlocks.add(block); + continue; + } + + for (String name : declared) { + if (memberTypes.containsKey(name)) shadowed.add(name); + } + } + } + + private static boolean isReplaceableUniform(GLSLParser.DeclarationContext ctx, List declared, Map memberTypes) { + final GLSLParser.Init_declarator_listContext idl = ctx.init_declarator_list(); + if (idl == null) return false; + final GLSLParser.Single_declarationContext single = idl.single_declaration(); + if (single == null || single.fully_specified_type() == null) return false; + final GLSLParser.Fully_specified_typeContext fst = single.fully_specified_type(); + if (fst.type_qualifier() == null) return false; + + boolean hasUniform = false; + for (GLSLParser.Single_type_qualifierContext stq : fst.type_qualifier().single_type_qualifier()) { + if (stq.storage_qualifier() != null && "uniform".equals(stq.storage_qualifier().getText())) { + hasUniform = true; + break; + } + } + if (!hasUniform) return false; + if (fst.type_specifier() == null || fst.type_specifier().type_specifier_nonarray() == null) return false; + final String declaredType = fst.type_specifier().type_specifier_nonarray().getText(); + + for (String name : declared) { + if (!declaredType.equals(memberTypes.get(name))) return false; + } + return true; + } + + private static Set referencedMembers(GLSLParser.Translation_unitContext root, Set memberNames, Set shadowed) { + final Set referenced = new HashSet<>(); + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void visitTerminal(TerminalNode node) { + final Token tok = node.getSymbol(); + if (tok.getType() != GLSLLexer.IDENTIFIER) return; + final String name = tok.getText(); + if (memberNames.contains(name) && !shadowed.contains(name)) referenced.add(name); + } + }, root); + return referenced; + } + + private static List declaredNames(GLSLParser.DeclarationContext ctx) { + final GLSLParser.Init_declarator_listContext idl = ctx.init_declarator_list(); + if (idl == null) return List.of(); + final GLSLParser.Single_declarationContext single = idl.single_declaration(); + if (single == null) return List.of(); + final List out = new ArrayList<>(2); + if (single.typeless_declaration() != null && single.typeless_declaration().IDENTIFIER() != null) { + out.add(single.typeless_declaration().IDENTIFIER().getText()); + } + for (GLSLParser.Typeless_declarationContext td : idl.typeless_declaration()) { + if (td.IDENTIFIER() != null) out.add(td.IDENTIFIER().getText()); + } + return out; + } + +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java new file mode 100644 index 000000000..5718596ee --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java @@ -0,0 +1,116 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.applyEdits; + +public final class SamplerStripper { + + private static final Logger LOGGER = LogManager.getLogger("Angelica-SDLGPU"); + + private SamplerStripper() {} + + public static String stripUnused(String source) { + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(source); + } catch (Exception e) { + return source; + } + final List edits = new ArrayList<>(); + collectEdits(root, source, edits); + return edits.isEmpty() ? source : applyEdits(source, edits); + } + + public static void collectEdits(GLSLParser.Translation_unitContext root, String source, List edits) { + record SamplerDecl(String name, int start, int stop) {} + final List samplers = new ArrayList<>(); + + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void enterDeclaration(GLSLParser.DeclarationContext ctx) { + final GLSLParser.Init_declarator_listContext idl = ctx.init_declarator_list(); + if (idl == null) return; + final GLSLParser.Single_declarationContext single = idl.single_declaration(); + if (single == null || single.fully_specified_type() == null) return; + final GLSLParser.Fully_specified_typeContext fst = single.fully_specified_type(); + if (fst.type_qualifier() == null) return; + + boolean hasUniform = false; + for (GLSLParser.Single_type_qualifierContext stq : fst.type_qualifier().single_type_qualifier()) { + if (stq.storage_qualifier() != null && "uniform".equals(stq.storage_qualifier().getText())) { + hasUniform = true; + break; + } + } + if (!hasUniform) return; + if (fst.type_specifier() == null || fst.type_specifier().type_specifier_nonarray() == null) return; + + final String typeText = fst.type_specifier().type_specifier_nonarray().getText(); + if (!isSamplerType(typeText)) return; + + final int start = ctx.getStart().getStartIndex(); + final int stop = ctx.getStop().getStopIndex(); + if (single.typeless_declaration() != null && single.typeless_declaration().IDENTIFIER() != null) { + samplers.add(new SamplerDecl(single.typeless_declaration().IDENTIFIER().getText(), start, stop)); + } + for (GLSLParser.Typeless_declarationContext td : idl.typeless_declaration()) { + if (td.IDENTIFIER() != null) { + samplers.add(new SamplerDecl(td.IDENTIFIER().getText(), start, stop)); + } + } + } + }, root); + + if (samplers.isEmpty()) return; + + final Map refCounts = new HashMap<>(); + for (SamplerDecl s : samplers) refCounts.put(s.name(), 0); + + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void visitTerminal(TerminalNode node) { + final Token tok = node.getSymbol(); + if (tok.getType() != GLSLLexer.IDENTIFIER) return; + final String name = tok.getText(); + final Integer prior = refCounts.get(name); + if (prior == null) return; + final int pos = tok.getStartIndex(); + for (SamplerDecl s : samplers) { + if (pos >= s.start() && pos <= s.stop()) return; + } + refCounts.put(name, prior + 1); + } + }, root); + + final Set directiveRefs = GlslTransformUtils.identifiersInDirectiveText(source); + + for (SamplerDecl s : samplers) { + if (refCounts.getOrDefault(s.name(), 0) != 0) continue; + if (directiveRefs.contains(s.name())) { + LOGGER.debug("Keeping sampler {}: referenced only inside a preprocessor block", s.name()); + continue; + } + edits.add(new Edit(s.start(), s.stop(), "")); + } + } + + private static boolean isSamplerType(String t) { + return t.startsWith("sampler") || t.startsWith("isampler") || t.startsWith("usampler"); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java new file mode 100644 index 000000000..729d4756c --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java @@ -0,0 +1,1721 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.taumc.glsl.grammar.GLSLParser; +import com.gtnewhorizons.angelica.sdlgpu.shader.cross.CrossCompileUtil; +import com.gtnewhorizons.angelica.sdlgpu.shader.dxbc.DxbcCrossCompile; +import com.gtnewhorizons.angelica.sdlgpu.shader.msl.MslCrossCompile; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.sdl.SDL_GPUComputePipelineCreateInfo; +import org.lwjgl.sdl.SDL_GPUShaderCreateInfo; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL43; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.IntConsumer; + +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.*; +import static org.lwjgl.system.MemoryUtil.*; + +import it.unimi.dsi.fastutil.booleans.BooleanArrayList; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrays; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; + +/** + * Manages shader compilation: GLSL -> SPIR-V (via shaderc) -> per-backend (via SPIRV-Cross). + * Tracks shader/program objects with synthetic GL IDs. + */ +public final class ShaderManager { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + private final Device device; + private Consumer uniformReleaseListener; + + public void setUniformReleaseListener(Consumer listener) { this.uniformReleaseListener = listener; } + + private int nextShaderId = 1; + private int nextProgramId = 1; + private final Int2ObjectOpenHashMap shaderObjects = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectOpenHashMap programObjects = new Int2ObjectOpenHashMap<>(); + + private record PrewarmKey(String source, int glShaderType) {} + private record PrewarmEntry(byte[] remappedSpirv, StageReflection reflection, GraphicsBindingMap graphicsBindingMap, Set boolUniforms, String transformedSource) {} + private record PrewarmHit(ByteBuffer spirv, StageReflection reflection, GraphicsBindingMap graphicsBindingMap, Set boolUniforms, String transformedSource) {} + private static final int PREWARM_CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap PREWARM_CACHE = new Object2ObjectLinkedOpenHashMap<>(); + + public static void clearPrewarmCache() { + synchronized (PREWARM_CACHE) { PREWARM_CACHE.clear(); } + } + + private static PrewarmHit lookupPrewarm(String src, int glShaderType) { + final PrewarmEntry e; + synchronized (PREWARM_CACHE) { + e = PREWARM_CACHE.getAndMoveToFirst(new PrewarmKey(src, glShaderType)); + } + if (e == null) return null; + // per-hit copy: linkProgram patches the returned SPIR-V in place (applyVaryingMatch / applyAttribLocationsAndInputMask) + final ByteBuffer copy = memAlloc(e.remappedSpirv().length); + copy.put(e.remappedSpirv()).flip(); + return new PrewarmHit(copy, e.reflection(), e.graphicsBindingMap(), e.boolUniforms(), e.transformedSource()); + } + + public ShaderManager(Device device) { + this.device = device; + } + + public int createShader(int type) { + final int id = nextShaderId++; + shaderObjects.put(id, new ShaderObject(type)); + return id; + } + + public void shaderSource(int shader, CharSequence source) { + final ShaderObject obj = shaderObjects.get(shader); + if (obj == null) return; + + String raw = source.toString(); + if (!raw.isEmpty() && raw.charAt(raw.length() - 1) == '\0') { + raw = raw.substring(0, raw.length() - 1); + } + + final PrewarmHit hit = lookupPrewarm(raw, obj.type); + if (hit != null) { + obj.source = hit.transformedSource(); + obj.reflection = hit.reflection(); + obj.graphicsBindingMap = hit.graphicsBindingMap(); + obj.boolUniforms = hit.boolUniforms(); + obj.spirvFuture = CompletableFuture.completedFuture(new SpirvCompiler.Result(hit.spirv(), null, null)); + return; + } + + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, obj.type, "shader" + shader, true); + obj.boolUniforms = pre != null ? pre.boolUniforms() : Set.of(); + String src = pre != null ? pre.rewrittenSource() : raw; + if (obj.isVertex()) { + src = ClipZRemap.injectGLToVulkanClipZ(src); + } + src = SamplerStripper.stripUnused(src); + if (obj.type == GL20.GL_VERTEX_SHADER || obj.type == GL20.GL_FRAGMENT_SHADER) { + src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + } + + obj.source = src; + + final ShaderWorkSubmitter submitter = GLSMHooks.shaderWorkSubmitter; + if (submitter != null) { + final int shaderKind = shaderKindFor(obj); + final int glType = obj.type; + final String finalSrc = src; + obj.spirvFuture = submitter.submit(() -> { + final SpirvCompiler.Result r = SpirvCompiler.compile(finalSrc, shaderKind, "shader" + shader, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() != null && (glType == GL20.GL_VERTEX_SHADER || glType == GL20.GL_FRAGMENT_SHADER)) { + obj.graphicsBindingMap = remapSpirvForSDLGPU(r.spirv(), glType); + obj.reflection = reflectStage(r.spirv(), glType == GL20.GL_VERTEX_SHADER); + } + return r; + }); + } else { + obj.spirvFuture = null; + } + } + + private static int shaderKindFor(ShaderObject obj) { + return shaderKindFor(obj.type); + } + + private static int shaderKindFor(int glShaderType) { + if (glShaderType == GL20.GL_VERTEX_SHADER) return Shaderc.shaderc_vertex_shader; + if (glShaderType == GL32.GL_GEOMETRY_SHADER) return Shaderc.shaderc_geometry_shader; + if (glShaderType == GL43.GL_COMPUTE_SHADER) return Shaderc.shaderc_compute_shader; + return Shaderc.shaderc_fragment_shader; + } + + public record PrewarmTransformResult(String source, Set boolUniforms) {} + + public static String applyPrewarmTransforms(String transformedSource, int glShaderType) { + return applyPrewarmTransformsFull(transformedSource, glShaderType).source(); + } + + public static PrewarmTransformResult applyPrewarmTransformsFull(String transformedSource, int glShaderType) { + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(transformedSource); + } catch (Exception e) { + return new PrewarmTransformResult(transformedSource, Set.of()); + } + final List edits = new ArrayList<>(); + final GlslVulkanPreprocess.Metadata meta = GlslVulkanPreprocess.collectEdits(transformedSource, root, glShaderType, "prewarm", true, edits); + if (glShaderType == GL20.GL_VERTEX_SHADER) { + ClipZRemap.collectEdits(root, edits); + } + SamplerStripper.collectEdits(root, transformedSource, edits); + String s = edits.isEmpty() ? transformedSource : GlslVulkanPreprocess.applyEdits(transformedSource, edits); + if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) { + s = PerFrameBlockInjector.inject(s, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + } + return new PrewarmTransformResult(s, meta.boolUniforms()); + } + + public static void prewarmSpirv(String transformedSource, int glShaderType) { + if (glShaderType != GL20.GL_VERTEX_SHADER && glShaderType != GL20.GL_FRAGMENT_SHADER + && glShaderType != GL43.GL_COMPUTE_SHADER && glShaderType != GL32.GL_GEOMETRY_SHADER) { + return; + } + + final PrewarmKey key = new PrewarmKey(transformedSource, glShaderType); + synchronized (PREWARM_CACHE) { + if (PREWARM_CACHE.containsKey(key)) return; + } + + final PrewarmTransformResult pre = applyPrewarmTransformsFull(transformedSource, glShaderType); + + final SpirvCompiler.Result r = SpirvCompiler.compile(pre.source(), shaderKindFor(glShaderType), "prewarm", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) return; + + try { + GraphicsBindingMap graphicsBindingMap = GraphicsBindingMap.EMPTY; + if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) { + graphicsBindingMap = remapSpirvForSDLGPU(r.spirv(), glShaderType); + } + final StageReflection reflection = (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) + ? reflectStage(r.spirv(), glShaderType == GL20.GL_VERTEX_SHADER) : StageReflection.EMPTY; + + final byte[] heap = new byte[r.spirv().remaining()]; + r.spirv().duplicate().get(heap); + synchronized (PREWARM_CACHE) { + PREWARM_CACHE.putAndMoveToFirst(key, new PrewarmEntry(heap, reflection, graphicsBindingMap, pre.boolUniforms(), pre.source())); + while (PREWARM_CACHE.size() > PREWARM_CACHE_MAX) PREWARM_CACHE.removeLast(); + } + } finally { + memFree(r.spirv()); + } + } + + public void compileShader(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + if (obj == null) return; + + final SpirvCompiler.Result r; + final boolean alreadyRemapped; + if (obj.spirvFuture != null) { + r = obj.spirvFuture.join(); + obj.spirvFuture = null; + alreadyRemapped = true; + } else { + r = SpirvCompiler.compile(obj.source, shaderKindFor(obj), "shader" + shader, SpirvCompiler.Options.vulkanForced460Core()); + alreadyRemapped = false; + } + if (r.spirv() == null) { + obj.infoLog = r.error() == null ? "(no error)" : r.error(); + obj.compiled = false; + LOG.error("Shader {} compilation failed: {} (dump={})", shader, obj.infoLog, r.dumpPath()); + return; + } + obj.spirv = r.spirv(); + if (!alreadyRemapped && (obj.type == GL20.GL_VERTEX_SHADER || obj.type == GL20.GL_FRAGMENT_SHADER)) { + obj.graphicsBindingMap = remapSpirvForSDLGPU(obj.spirv, obj.type); + obj.reflection = reflectStage(obj.spirv, obj.isVertex()); + } + obj.compiled = true; + obj.infoLog = ""; + } + + public void deleteShader(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + if (obj == null) return; + if (obj.attachCount > 0) { + obj.deletePending = true; + return; + } + shaderObjects.remove(shader); + if (obj.spirv != null) memFree(obj.spirv); + } + + private void releaseShaderAttachment(int shader) { + if (shader == 0) return; + final ShaderObject obj = shaderObjects.get(shader); + if (obj == null) return; + if (obj.attachCount > 0) obj.attachCount--; + if (obj.deletePending && obj.attachCount == 0) { + shaderObjects.remove(shader); + if (obj.spirv != null) memFree(obj.spirv); + } + } + + public boolean isCompiled(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + return obj != null && obj.compiled; + } + + public String getShaderInfoLog(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + return obj != null ? obj.infoLog : ""; + } + + public int getShaderType(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + return obj != null ? obj.type : 0; + } + + public String getShaderSource(int shader) { + final ShaderObject obj = shaderObjects.get(shader); + return obj != null ? obj.source : ""; + } + + public int createProgram() { + final int id = nextProgramId++; + programObjects.put(id, new ProgramObject()); + return id; + } + + public void attachShader(int program, int shader) { + final ProgramObject prog = programObjects.get(program); + final ShaderObject shObj = shaderObjects.get(shader); + if (prog == null || shObj == null) return; + + final int oldSlot; + if (shObj.isVertex()) { oldSlot = prog.vertexShader; prog.vertexShader = shader; } + else if (shObj.isGeometry()) { oldSlot = prog.geometryShader; prog.geometryShader = shader; } + else if (shObj.isCompute()) { oldSlot = prog.computeShader; prog.computeShader = shader; } + else { oldSlot = prog.fragmentShader; prog.fragmentShader = shader; } + + if (oldSlot == shader) return; + if (oldSlot != 0) { + final ShaderObject oldObj = shaderObjects.get(oldSlot); + if (oldObj != null && oldObj.attachCount > 0) oldObj.attachCount--; + } + shObj.attachCount++; + } + + public void linkProgram(int program) { + final ProgramObject prog = programObjects.get(program); + if (prog == null) return; + + if (prog.computeShader != 0 && prog.vertexShader == 0 && prog.fragmentShader == 0) { + linkComputeProgram(program, prog); + return; + } + + final ShaderObject vs = shaderObjects.get(prog.vertexShader); + final ShaderObject fs = shaderObjects.get(prog.fragmentShader); + final ShaderObject gs = prog.geometryShader != 0 ? shaderObjects.get(prog.geometryShader) : null; + + if (vs == null || !vs.compiled || fs == null || !fs.compiled) { + prog.linked = false; + prog.infoLog = "Shader not compiled"; + return; + } + + if (gs != null && !gs.compiled) { + prog.linked = false; + prog.infoLog = "Geometry shader not compiled"; + return; + } + + releaseProgramGpuResources(prog); + + prog.vertexSpirv = copyBuffer(vs.spirv); + prog.fragmentSpirv = copyBuffer(fs.spirv); + prog.vertexSource = vs.source; + prog.vertexReflection = vs.reflection; + prog.maxFragOutputLocation = fs.reflection.maxOutputLocation(); + dumpLinkedSource(program, vs.source, fs.source); + + applyVaryingMatch(prog, vs.reflection, fs.reflection); + applyAttribLocationsAndInputMask(prog, vs.reflection); + + prog.vertexResources = vs.reflection.counts(); + prog.fragmentResources = fs.reflection.counts(); + prog.vertexGraphicsBindingMap = vs.graphicsBindingMap; + prog.fragmentGraphicsBindingMap = fs.graphicsBindingMap; + prog.vertexSamplerNames = vs.reflection.samplerNames(); + prog.fragmentSamplerNames = fs.reflection.samplerNames(); + prog.samplerUnitsDirty = true; + prog.allSamplerNames.clear(); + prog.allSamplerNames.addAll(prog.vertexSamplerNames); + prog.allSamplerNames.addAll(prog.fragmentSamplerNames); + prog.vertexImageNames = vs.reflection.storageImageNames(); + prog.fragmentImageNames = fs.reflection.storageImageNames(); + prog.allImageNames.clear(); + prog.allImageNames.addAll(prog.vertexImageNames); + prog.allImageNames.addAll(prog.fragmentImageNames); + prog.imageTextureUnits.clear(); + prog.boolUniforms.clear(); + prog.boolUniforms.addAll(vs.boolUniforms); + prog.boolUniforms.addAll(fs.boolUniforms); + if (gs != null) prog.boolUniforms.addAll(gs.boolUniforms); + LOG.debug("Program {} resources: VS={} FS={} vsSamplers={} fsSamplers={}", program, + prog.vertexResources, prog.fragmentResources, prog.vertexSamplerNames, prog.fragmentSamplerNames); + if (gs != null) { + LOG.warn("Program {} has geometry shader attached -- GS emulation not yet implemented, GS will be ignored", program); + } + if (prog.vertexGraphicsBindingMap.rwStorageTextureGlSlots().length > 0 + || prog.fragmentGraphicsBindingMap.rwStorageTextureGlSlots().length > 0) { + LOG.error("Program {} has a graphics-stage RW storage image (SDL_GPU unsupported); ensure RwImageStoreExtractor stripped it. Rejecting link.", program); + prog.linked = false; + prog.infoLog = "graphics-stage RW storage image present"; + return; + } + + prog.linked = true; + prog.infoLog = ""; + + applyUboMembers(prog, vs.reflection, true); + applyUboMembers(prog, fs.reflection, false); + applyBlockMembers(prog, vs.reflection); + applyBlockMembers(prog, fs.reflection); + registerExtraNames(prog, vs.reflection); + registerExtraNames(prog, fs.reflection); + + for (final String name : prog.allSamplerNames) ensureLocation(prog, name); + for (final String name : prog.allImageNames) ensureLocation(prog, name); + + prog.buildUniformSlotArrays(); + + } + + private void linkComputeProgram(int program, ProgramObject prog) { + final ShaderObject cs = shaderObjects.get(prog.computeShader); + if (cs == null || !cs.compiled || cs.spirv == null) { + prog.linked = false; + prog.infoLog = "Compute shader not compiled"; + return; + } + + releaseProgramGpuResources(prog); + + prog.computeSpirv = copyBuffer(cs.spirv); + prog.computeBindingMap = remapSpirvForComputeSDLGPU(prog.computeSpirv); + if (!validateComputeBindingMap(prog.computeBindingMap, program)) { + prog.linked = false; + prog.infoLog = "Compute shader has out-of-range layout(binding=N); see prior log for details"; + return; + } + + final StageReflection refl = cs.reflection != StageReflection.EMPTY ? cs.reflection : reflectStage(prog.computeSpirv, false); + final ResourceCounts counts = refl.counts(); + prog.computeResources = counts; + + prog.vertexSamplerNames = List.of(); + prog.fragmentSamplerNames = refl.samplerNames(); + prog.samplerUnitsDirty = true; + prog.allSamplerNames.clear(); + prog.allSamplerNames.addAll(refl.samplerNames()); + prog.vertexImageNames = List.of(); + prog.fragmentImageNames = refl.storageImageNames(); + prog.allImageNames.clear(); + prog.allImageNames.addAll(refl.storageImageNames()); + prog.imageTextureUnits.clear(); + prog.boolUniforms.clear(); + prog.boolUniforms.addAll(cs.boolUniforms); + + applyUboMembers(prog, refl, false); + registerExtraNames(prog, refl); + for (final String name : prog.allSamplerNames) ensureLocation(prog, name); + for (final String name : prog.allImageNames) ensureLocation(prog, name); + prog.buildUniformSlotArrays(); + + final int[] localSize = CrossCompileUtil.parseLocalSize(prog.computeSpirv); + final CrossCompiled cc = crossCompile(prog.computeSpirv, GL43.GL_COMPUTE_SHADER); + + try (var stack = stackPush()) { + final SDL_GPUComputePipelineCreateInfo ci = SDL_GPUComputePipelineCreateInfo.calloc(stack) + .code(cc.code()) + .entrypoint(stack.ASCII(cc.entrypoint())) + .format(cc.targetFormat()) + .num_samplers(counts.numSamplers()) + .num_readonly_storage_textures(refl.numReadonlyStorageTextures()) + .num_readonly_storage_buffers(refl.numReadonlyStorageBuffers()) + .num_readwrite_storage_textures(refl.numReadwriteStorageTextures()) + .num_readwrite_storage_buffers(refl.numReadwriteStorageBuffers()) + .num_uniform_buffers(counts.numUBOs()) + .threadcount_x(localSize[0]).threadcount_y(localSize[1]).threadcount_z(localSize[2]); + + LOG.debug("Creating SDL compute pipeline: program={} fmt=0x{} entry={} samplers={} ubos={} ssbo(ro/rw)={}/{} storTex(ro/rw)={}/{} localSize={}x{}x{}", + program, Integer.toHexString(cc.targetFormat()), cc.entrypoint(), + counts.numSamplers(), counts.numUBOs(), + refl.numReadonlyStorageBuffers(), refl.numReadwriteStorageBuffers(), + refl.numReadonlyStorageTextures(), refl.numReadwriteStorageTextures(), + localSize[0], localSize[1], localSize[2]); + + final long handle = SDL_CreateGPUComputePipeline(device.getDevice(), ci); + if (handle == 0) { + LOG.error("Failed to create SDL GPU compute pipeline for program {}: {}", program, SDLError.SDL_GetError()); + prog.linked = false; + prog.infoLog = "Compute pipeline creation failed: " + SDLError.SDL_GetError(); + return; + } + prog.sdlComputePipeline = handle; + } finally { + if (cc.ownsCode()) memFree(cc.code()); + } + + prog.linked = true; + prog.infoLog = ""; + } + + static void applyUboMembers(ProgramObject prog, StageReflection refl, boolean isVertex) { + if (refl.uboSize() > 0) { + if (isVertex) prog.vertexUboSize = refl.uboSize(); + else prog.fragmentUboSize = refl.uboSize(); + } + for (UboMember m : refl.uboMembers()) { + final int loc = ensureLocation(prog, m.name()); + final UniformMemberInfo info = new UniformMemberInfo( + m.offset(), m.size(), m.arrayStride(), isVertex, + m.vectorSize(), m.columns(), m.baseType(), m.arrayLen() + ); + prog.locationToMemberInfo.put(loc, info); + if (isVertex) prog.vertexMemberInfo.put(loc, info); + else prog.fragmentMemberInfo.put(loc, info); + } + } + + static void applyBlockMembers(ProgramObject prog, StageReflection refl) { + for (int b = 0; b < BLOCK_COUNT; b++) { + final BlockReflection block = refl.blocks()[b]; + if (block.members().isEmpty()) continue; + prog.blockSize[b] = Math.max(prog.blockSize[b], block.size()); + prog.blockBinding[b] = block.binding(); + for (UboMember m : block.members()) { + final int loc = ensureLocation(prog, m.name()); + if (prog.blockMemberInfo[b].containsKey(loc)) continue; + prog.blockMemberInfo[b].put(loc, new UniformMemberInfo( + m.offset(), m.size(), m.arrayStride(), false, + m.vectorSize(), m.columns(), m.baseType(), m.arrayLen())); + } + } + } + + private static void registerExtraNames(ProgramObject prog, StageReflection refl) { + for (String name : refl.extraUniformNames()) ensureLocation(prog, name); + } + + private static int ensureLocation(ProgramObject prog, String name) { + final int existing = prog.nameToLocation.getInt(name); + if (existing != -1) return existing; + final int loc = prog.nextUniformLocation++; + prog.nameToLocation.put(name, loc); + prog.locationToName.put(loc, name); + return loc; + } + + private static void applyVaryingMatch(ProgramObject prog, StageReflection vs, StageReflection fs) { + if (vs.vsOutputs().isEmpty() || fs.fsInputs().isEmpty() || prog.fragmentSpirv == null) return; + final HashMap vsOutLocs = new HashMap<>(vs.vsOutputs().size() * 2); + for (VsOutput o : vs.vsOutputs()) vsOutLocs.put(o.name(), o.originalLocation()); + final IntBuffer fsBuf = prog.fragmentSpirv.asIntBuffer(); + for (FsInput fi : fs.fsInputs()) { + final Integer vsLoc = vsOutLocs.get(fi.name()); + if (vsLoc == null || vsLoc == fi.originalLocation()) continue; + if (fsBuf.get(fi.binaryOffset()) != fi.originalLocation()) { + LOG.error("applyVaryingMatch: SPIR-V binary offset sanity check failed for '{}' (expected {}, got {})", fi.name(), fi.originalLocation(), fsBuf.get(fi.binaryOffset())); + continue; + } + fsBuf.put(fi.binaryOffset(), vsLoc); + } + } + + static void applyAttribLocationsAndInputMask(ProgramObject prog, StageReflection vs) { + prog.resolvedAttribLocations.clear(); + prog.activeAttribNames = null; + if (vs.vsInputs().isEmpty() || prog.vertexSpirv == null) return; + prog.vertexInputMask = patchAttribLocations(prog.vertexSpirv, vs, prog.attribLocationBindings, + prog.vertexInputVecSize, prog.vertexInputBaseType, prog.vertexInputName, prog.resolvedAttribLocations); + } + + private static int patchAttribLocations(ByteBuffer spirv, StageReflection vs, Object2IntOpenHashMap bindings, int[] outVecSize, int[] outBaseType, String[] outName, Object2IntOpenHashMap resolvedOut) { + final IntBuffer vsBuf = spirv.asIntBuffer(); + int mask = 0; + if (outName != null) Arrays.fill(outName, null); + for (VsInput vi : vs.vsInputs()) { + int finalLoc = vi.originalLocation(); + final int desired = bindings.getInt(vi.name()); + if (desired != -1 && desired != vi.originalLocation()) { + if (vsBuf.get(vi.binaryOffset()) != vi.originalLocation()) { + LOG.error("applyAttribLocations: sanity check failed for '{}' (expected {}, got {})", vi.name(), vi.originalLocation(), vsBuf.get(vi.binaryOffset())); + } else { + vsBuf.put(vi.binaryOffset(), desired); + finalLoc = desired; + } + } + if (resolvedOut != null) resolvedOut.put(vi.name(), finalLoc); + if (finalLoc < 0 || finalLoc >= 16) continue; + mask |= (1 << finalLoc); + outVecSize[finalLoc] = vi.vecSize(); + outBaseType[finalLoc] = vi.baseType(); + if (outName != null) outName[finalLoc] = vi.name(); + } + return mask; + } + + public VertexVariant getOrBuildVertexVariant(int program, long key, List attribs) { + final ProgramObject prog = programObjects.get(program); + if (prog == null || !prog.linked || prog.vertexSource.isEmpty()) return null; + final VertexVariant hit = prog.vertexVariants.get(key); + if (hit != null) return hit; + if (prog.vertexVariantFailed.contains(key)) return null; + + final VertexVariant built = buildVertexVariant(program, prog, attribs); + if (built == null) { + prog.vertexVariantFailed.add(key); + return null; + } + prog.vertexVariants.put(key, built); + return built; + } + + private VertexVariant buildVertexVariant(int program, ProgramObject prog, List attribs) { + final String preprocessed = SpirvCompiler.preprocess(prog.vertexSource, Shaderc.shaderc_vertex_shader, "variant" + program, SpirvCompiler.Options.vulkanForced460Core()); + if (preprocessed == null) { + LOG.warn("Vertex attribute conversion: program {} preprocessing failed; falling back to normalized coercion, values will be scaled", program); + return null; + } + final String src = UscaledRetype.retype(preprocessed, attribs); + if (src == null) { + LOG.warn("Vertex attribute conversion: program {} source rewrite failed for {}; falling back to normalized coercion, values will be scaled", program, attribs); + return null; + } + final SpirvCompiler.Result r = SpirvCompiler.compile(src, Shaderc.shaderc_vertex_shader, "variant" + program, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + LOG.warn("Vertex attribute conversion: program {} variant failed to compile ({}); falling back to normalized coercion, values will be scaled", program, r.error()); + return null; + } + try { + remapSpirvForSDLGPU(r.spirv(), GL20.GL_VERTEX_SHADER); + final StageReflection refl = reflectStage(r.spirv(), true); + if (!sameVaryingLayout(prog.vertexReflection.vsOutputs(), refl.vsOutputs())) { + LOG.error("Vertex attribute conversion: program {} variant changed VS output locations; the fragment stage is patched against the base layout. Falling back to normalized coercion.", program); + return null; + } + final VertexVariant v = new VertexVariant(); + v.spirv = copyBuffer(r.spirv()); + + final Object2IntOpenHashMap bindings = new Object2IntOpenHashMap<>(prog.attribLocationBindings); + bindings.defaultReturnValue(-1); + for (UscaledRetype.Attrib a : attribs) bindings.put(a.name() + UscaledRetype.SUFFIX, a.location()); + v.inputMask = patchAttribLocations(v.spirv, refl, bindings, v.inputVecSize, v.inputBaseType, null, null); + if (v.inputMask != prog.vertexInputMask) { + memFree(v.spirv); + LOG.error("Vertex attribute conversion: program {} variant resolved inputs to 0x{} but the program binds 0x{}; a renamed input landed on the wrong location. Falling back to normalized coercion.", + program, Integer.toHexString(v.inputMask), Integer.toHexString(prog.vertexInputMask)); + return null; + } + v.sdlShader = createSDLShader(v.spirv, SDL_GPU_SHADERSTAGE_VERTEX, prog.vertexResources.numSamplers(), prog.vertexResources.numUBOs(), prog.vertexResources.numStorageBuffers(), prog.vertexResources.numStorageTextures()); + if (v.sdlShader == 0) { + memFree(v.spirv); + LOG.error("Vertex attribute conversion: program {} variant shader creation failed: {}", program, SDLError.SDL_GetError()); + return null; + } + LOG.info("Vertex attribute conversion: program {} converted {}", program, attribs); + if (SystemProperties.DUMP_SHADERS) dumpVariantSource(program, src); + return v; + } finally { + memFree(r.spirv()); + } + } + + private static boolean linkDumpDirCleared; + + private static void dumpLinkedSource(int program, String vertexSrc, String fragmentSrc) { + final Path dir = SystemProperties.shaderDumpDir("link"); + if (dir == null) return; + try { + Files.createDirectories(dir); + if (!linkDumpDirCleared) { + linkDumpDirCleared = true; + try (var entries = Files.list(dir)) { + for (Path p : entries.toList()) Files.deleteIfExists(p); + } + } + Files.writeString(dir.resolve("prog" + program + "_vs.glsl"), vertexSrc); + Files.writeString(dir.resolve("prog" + program + "_fs.glsl"), fragmentSrc); + } catch (IOException e) { + LOG.warn("Failed to dump linked source for program {}: {}", program, e.toString()); + } + } + + private static void dumpVariantSource(int program, String src) { + try { + final Path dir = Path.of("patched_shaders"); + Files.createDirectories(dir); + Files.writeString(dir.resolve("variant_" + program + ".vsh"), src); + } catch (IOException e) { + LOG.warn("Failed to dump vertex attribute conversion variant for program {}: {}", program, e.toString()); + } + } + + private static boolean sameVaryingLayout(List base, List variant) { + if (base.size() != variant.size()) return false; + for (VsOutput b : base) { + boolean matched = false; + for (VsOutput v : variant) { + if (b.name().equals(v.name())) { + if (b.originalLocation() != v.originalLocation()) return false; + matched = true; + break; + } + } + if (!matched) return false; + } + return true; + } + + private void releaseProgramGpuResources(ProgramObject prog) { + final long dev = device.getDevice(); + for (VertexVariant v : prog.vertexVariants.values()) { + if (v.sdlShader != 0) SDL_ReleaseGPUShader(dev, v.sdlShader); + if (v.spirv != null) memFree(v.spirv); + } + prog.vertexVariants.clear(); + prog.vertexVariantFailed.clear(); + if (prog.sdlVertexShader != 0) { SDL_ReleaseGPUShader(dev, prog.sdlVertexShader); prog.sdlVertexShader = 0; } + if (prog.sdlFragmentShader != 0) { SDL_ReleaseGPUShader(dev, prog.sdlFragmentShader); prog.sdlFragmentShader = 0; } + if (prog.sdlComputePipeline != 0) { SDL_ReleaseGPUComputePipeline(dev, prog.sdlComputePipeline); prog.sdlComputePipeline = 0; } + if (prog.vertexSpirv != null) { memFree(prog.vertexSpirv); prog.vertexSpirv = null; } + if (prog.fragmentSpirv != null) { memFree(prog.fragmentSpirv); prog.fragmentSpirv = null; } + if (prog.geometrySpirv != null) { memFree(prog.geometrySpirv); prog.geometrySpirv = null; } + if (prog.computeSpirv != null) { memFree(prog.computeSpirv); prog.computeSpirv = null; } + if (uniformReleaseListener != null) uniformReleaseListener.accept(prog); + } + + public void releaseProgramFinal(int program) { + final ProgramObject prog = programObjects.remove(program); + if (prog == null) return; + releaseProgramGpuResources(prog); + forEachAttachedShader(prog, this::releaseShaderAttachment); + } + + private static void forEachAttachedShader(ProgramObject prog, IntConsumer body) { + if (prog.vertexShader != 0) body.accept(prog.vertexShader); + if (prog.fragmentShader != 0) body.accept(prog.fragmentShader); + if (prog.geometryShader != 0) body.accept(prog.geometryShader); + if (prog.computeShader != 0) body.accept(prog.computeShader); + } + + public void markProgramForDeletion(int program) { + final ProgramObject prog = programObjects.get(program); + if (prog != null) prog.deletePending = true; + } + + public boolean isLinked(int program) { + final ProgramObject prog = programObjects.get(program); + return prog != null && prog.linked; + } + + public String getProgramInfoLog(int program) { + final ProgramObject prog = programObjects.get(program); + return prog != null ? prog.infoLog : ""; + } + + public boolean isShader(int id) { return shaderObjects.containsKey(id); } + public boolean isProgram(int id) { return programObjects.containsKey(id); } + + public int getAttachedShaderCount(int program) { + final ProgramObject prog = programObjects.get(program); + if (prog == null) return 0; + final int[] n = { 0 }; + forEachAttachedShader(prog, s -> n[0]++); + return n[0]; + } + + public void getAttachedShaders(int program, IntBuffer count, IntBuffer shaders) { + final ProgramObject prog = programObjects.get(program); + final int[] n = { 0 }; + if (prog != null && shaders != null) { + forEachAttachedShader(prog, s -> { + if (shaders.remaining() > n[0]) shaders.put(shaders.position() + n[0]++, s); + }); + } + if (count != null && count.remaining() > 0) count.put(count.position(), n[0]); + } + + public ProgramObject getProgram(int program) { + return programObjects.get(program); + } + + public long createSDLShader(ByteBuffer spirv, int stage, int numSamplers, int numUniformBuffers, int numStorageBuffers, int numStorageTextures) { + final CrossCompiled cc = crossCompile(spirv, glShaderTypeForSdlStage(stage)); + try (var stack = stackPush()) { + final SDL_GPUShaderCreateInfo ci = SDL_GPUShaderCreateInfo.calloc(stack) + .code(cc.code()) + .entrypoint(stack.ASCII(cc.entrypoint())) + .format(cc.targetFormat()) + .stage(stage) + .num_samplers(numSamplers) + .num_uniform_buffers(numUniformBuffers) + .num_storage_buffers(numStorageBuffers) + .num_storage_textures(numStorageTextures); + + LOG.debug("Creating SDL shader: stage={} samplers={} ubos={} ssbos={} storTex={} fmt=0x{} entry={} code=[pos={} lim={} rem={}]", + stage, numSamplers, numUniformBuffers, numStorageBuffers, numStorageTextures, + Integer.toHexString(cc.targetFormat()), cc.entrypoint(), + cc.code().position(), cc.code().limit(), cc.code().remaining()); + + final long handle = SDL_CreateGPUShader(device.getDevice(), ci); + if (handle == 0) { + LOG.error("Failed to create SDL GPU shader: {}", SDLError.SDL_GetError()); + } + return handle; + } finally { + if (cc.ownsCode()) memFree(cc.code()); + } + } + + private record CrossCompiled(int targetFormat, ByteBuffer code, String entrypoint, boolean ownsCode) {} + + private CrossCompiled crossCompile(ByteBuffer spirv, int glShaderType) { + if (device.supportsSpirv()) { + return new CrossCompiled(SDL_GPU_SHADERFORMAT_SPIRV, spirv, "main", false); + } + if (device.supportsMsl()) { + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, glShaderType); + return new CrossCompiled(SDL_GPU_SHADERFORMAT_MSL, out.code(), out.entrypoint(), true); + } + if (device.supportsDxbc()) { + final DxbcCrossCompile.Output out = DxbcCrossCompile.compile(spirv, glShaderType); + return new CrossCompiled(SDL_GPU_SHADERFORMAT_DXBC, out.code(), out.entrypoint(), true); + } + if (device.supportsDxil()) { + throw new UnsupportedOperationException("SPIR-V -> DXIL cross-compilation not yet implemented"); + } + throw new RuntimeException("No supported shader format available"); + } + + private static int glShaderTypeForSdlStage(int sdlStage) { + if (sdlStage == SDL_GPU_SHADERSTAGE_VERTEX) return GL20.GL_VERTEX_SHADER; + if (sdlStage == SDL_GPU_SHADERSTAGE_FRAGMENT) return GL20.GL_FRAGMENT_SHADER; + throw new IllegalArgumentException("Unsupported SDL_GPU shader stage: " + sdlStage); + } + + public record ResourceCounts(int numSamplers, int numUBOs, int numStorageBuffers, int numStorageTextures) { + public static final ResourceCounts EMPTY = new ResourceCounts(0, 0, 0, 0); + } + + + public int getUniformLocation(int program, String name) { + final ProgramObject prog = programObjects.get(program); + if (prog == null || !prog.linked) return -1; + return prog.nameToLocation.getInt(name); + } + + /** + * Remap SPIR-V descriptor set/binding numbers to match SDL GPU's expected layout. + */ + public static GraphicsBindingMap remapSpirvForSDLGPU(ByteBuffer spirv, int shaderType) { + final boolean isVertex = (shaderType == GL20.GL_VERTEX_SHADER); + final boolean isFragment = (shaderType == GL20.GL_FRAGMENT_SHADER); + if (!isVertex && !isFragment) return GraphicsBindingMap.EMPTY; + + final int resourceSet = isVertex ? 0 : 2; + final int uboSet = isVertex ? 1 : 3; + + final Int2IntOpenHashMap idToNewSet = new Int2IntOpenHashMap(); + final Int2IntOpenHashMap idToNewBinding = new Int2IntOpenHashMap(); + final IntArrayList roStorageTextureGlSlots = new IntArrayList(); + final IntArrayList rwStorageTextureGlSlots = new IntArrayList(); + final IntArrayList roSsboGlSlots = new IntArrayList(); + + withSpvc(spirv, null, (compiler, resources, stack) -> { + int n = 0; + n = collectResourceIds(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, idToNewSet, idToNewBinding, resourceSet, n, stack); + n = collectGraphicsStorageImages(resources, compiler, idToNewSet, idToNewBinding, resourceSet, n, roStorageTextureGlSlots, rwStorageTextureGlSlots, stack); + n = collectComputeBindings(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, idToNewSet, idToNewBinding, roSsboGlSlots, resourceSet, n, stack); + collectResourceIds(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, idToNewSet, idToNewBinding, uboSet, 0, stack); + warnOnSeparateSamplers(resources, stack, isVertex ? "vertex" : "fragment"); + return null; + }); + + if (idToNewSet.isEmpty()) return GraphicsBindingMap.EMPTY; + patchSpirvDecorations(spirv.asIntBuffer(), idToNewSet, idToNewBinding); + LOG.debug("Remapped {} SPIR-V resources for {} shader (resourceSet={}, uboSet={})", idToNewSet.size(), isVertex ? "vertex" : "fragment", resourceSet, uboSet); + return new GraphicsBindingMap(roStorageTextureGlSlots.toIntArray(), rwStorageTextureGlSlots.toIntArray(), roSsboGlSlots.toIntArray()); + } + + private static void warnOnSeparateSamplers(long resources, MemoryStack stack, String stage) { + if (CrossCompileUtil.countResources(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, stack) > 0 && separateSamplerWarned.compareAndSet(false, true)) { + LOG.error("{} shader declares a separate sampler; SDL_GPU cannot bind one and its descriptor will be left unremapped", stage); + } + } + + private static final AtomicBoolean separateSamplerWarned = new AtomicBoolean(); + + private static int collectGraphicsStorageImages(long resources, long compiler, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, int targetSet, int nextBinding, IntArrayList roOut, IntArrayList rwOut, MemoryStack stack) { + final int[] next = { nextBinding }; + forEachResource(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, stack, (j, res) -> { + final int spvId = res.id(); + roOut.add(Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding)); + idToNewSet.put(spvId, targetSet); + idToNewBinding.put(spvId, next[0]++); + }); + forEachResource(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, stack, (j, res) -> { + final int spvId = res.id(); + final int oldBinding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + idToNewSet.put(spvId, targetSet); + idToNewBinding.put(spvId, next[0]++); + if (Spvc.spvc_compiler_has_decoration(compiler, spvId, Spv.SpvDecorationNonWritable)) { + roOut.add(oldBinding); + } else { + rwOut.add(oldBinding); + } + }); + return next[0]; + } + + public static ComputeBindingMap remapSpirvForComputeSDLGPU(ByteBuffer spirv) { + final Int2IntOpenHashMap idToNewSet = new Int2IntOpenHashMap(); + final Int2IntOpenHashMap idToNewBinding = new Int2IntOpenHashMap(); + final IntArrayList samplerSlots = new IntArrayList(); + final IntArrayList roTexSlots = new IntArrayList(); + final IntArrayList rwTexSlots = new IntArrayList(); + final IntArrayList roBufSlots = new IntArrayList(); + final IntArrayList rwBufSlots = new IntArrayList(); + final IntArrayList uboSlots = new IntArrayList(); + + final List samplerNames = new ArrayList<>(); + final List roTexNames = new ArrayList<>(); + final List rwTexNames = new ArrayList<>(); + final BooleanArrayList uboDefault = new BooleanArrayList(); + final IntArrayList uboSizes = new IntArrayList(); + final IntArrayList roTexFormats = new IntArrayList(); + final IntArrayList rwTexFormats = new IntArrayList(); + final IntArrayList roTexTargets = new IntArrayList(); + final IntArrayList rwTexTargets = new IntArrayList(); + + final StorageSplitOut roTex = new StorageSplitOut(roTexSlots, roTexNames, roTexFormats, roTexTargets); + final StorageSplitOut rwTex = new StorageSplitOut(rwTexSlots, rwTexNames, rwTexFormats, rwTexTargets); + + final ComputeBindingMap err = withSpvc(spirv, ComputeBindingMap.EMPTY, (compiler, resources, stack) -> { + int s0 = 0, s1 = 0; + s0 = collectComputeBindings(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, idToNewSet, idToNewBinding, samplerSlots, 0, s0, stack, samplerNames); + final int[] sepSplit = collectComputeStorageSplit(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, idToNewSet, idToNewBinding, roTex, rwTex, s0, s1, stack, (c, id, st) -> true); + s0 = sepSplit[0]; s1 = sepSplit[1]; + final int[] imgSplit = collectComputeStorageSplit(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, idToNewSet, idToNewBinding, roTex, rwTex, s0, s1, stack, (c, id, st) -> Spvc.spvc_compiler_has_decoration(c, id, Spv.SpvDecorationNonWritable)); + s0 = imgSplit[0]; s1 = imgSplit[1]; + final int[] bufSplit = collectComputeStorageSplit(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, idToNewSet, idToNewBinding, StorageSplitOut.slotsOnly(roBufSlots), StorageSplitOut.slotsOnly(rwBufSlots), s0, s1, stack, CrossCompileUtil::isStorageBufferReadOnly); + s0 = bufSplit[0]; s1 = bufSplit[1]; + collectComputeUbos(resources, compiler, idToNewSet, idToNewBinding, uboSlots, uboDefault, uboSizes, stack); + warnOnSeparateSamplers(resources, stack, "compute"); + return null; + }); + if (err != null) return err; + + if (!idToNewSet.isEmpty()) { + patchSpirvDecorations(spirv.asIntBuffer(), idToNewSet, idToNewBinding); + } + + return new ComputeBindingMap( + samplerSlots.toIntArray(), + roTexSlots.toIntArray(), + rwTexSlots.toIntArray(), + roBufSlots.toIntArray(), + rwBufSlots.toIntArray(), + uboSlots.toIntArray(), + samplerNames.toArray(new String[0]), + roTexNames.toArray(new String[0]), + rwTexNames.toArray(new String[0]), + uboDefault.toBooleanArray(), + uboSizes.toIntArray(), + roTexFormats.toIntArray(), + rwTexFormats.toIntArray(), + roTexTargets.toIntArray(), + rwTexTargets.toIntArray()); + } + + private static void collectComputeUbos(long resources, long compiler, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, IntArrayList glSlotsOut, BooleanArrayList isDefaultOut, IntArrayList sizesOut, MemoryStack stack) { + final int[] next = { 0 }; + final PointerBuffer pSize = stack.pointers(0); + forEachResource(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack, (j, res) -> { + final int spvId = res.id(); + final int oldBinding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + idToNewSet.put(spvId, 2); + idToNewBinding.put(spvId, next[0]++); + glSlotsOut.add(oldBinding); + final String resName = res.nameString(); + final String typeName = Spvc.spvc_compiler_get_name(compiler, res.base_type_id()); + isDefaultOut.add((resName != null && resName.endsWith("DefaultUniformBlock")) || (typeName != null && typeName.endsWith("DefaultUniformBlock"))); + int size = 0; + final long typeHandle = Spvc.spvc_compiler_get_type_handle(compiler, res.base_type_id()); + if (Spvc.spvc_compiler_get_declared_struct_size(compiler, typeHandle, pSize) == Spvc.SPVC_SUCCESS) { + size = (int) pSize.get(0); + } + sizesOut.add(size); + }); + } + + @FunctionalInterface + private interface SpvcBody { T run(long compiler, long resources, MemoryStack stack); } + + private static T withSpvc(ByteBuffer spirv, T onError, SpvcBody body) { + try (var stack = stackPush()) { + final PointerBuffer pContext = stack.pointers(0); + if (Spvc.spvc_context_create(pContext) != Spvc.SPVC_SUCCESS) { + LOG.error("SPIRV-Cross: spvc_context_create failed"); + return onError; + } + final long ctx = pContext.get(0); + try { + final IntBuffer spirvWords = spirv.asIntBuffer(); + final PointerBuffer pParsedIR = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, spirvWords, spirvWords.remaining(), pParsedIR) != Spvc.SPVC_SUCCESS) { + LOG.error("SPIRV-Cross: parse_spirv failed"); + return onError; + } + final PointerBuffer pCompiler = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pParsedIR.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler) != Spvc.SPVC_SUCCESS) { + LOG.error("SPIRV-Cross: create_compiler failed"); + return onError; + } + final long compiler = pCompiler.get(0); + final PointerBuffer pResources = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(compiler, pResources) != Spvc.SPVC_SUCCESS) { + LOG.error("SPIRV-Cross: create_shader_resources failed"); + return onError; + } + return body.run(compiler, pResources.get(0), stack); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + } + + private static void patchSpirvDecorations(IntBuffer words, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding) { + final int wordCount = words.limit(); + int i = 5; // skip header + while (i < wordCount) { + final int word0 = words.get(i); + final int opcode = word0 & 0xFFFF; + final int instrLen = (word0 >>> 16) & 0xFFFF; + if (instrLen == 0) break; // malformed + if (opcode == 71 && instrLen >= 4) { // OpDecorate + final int targetId = words.get(i + 1); + if (idToNewSet.containsKey(targetId)) { + final int decoration = words.get(i + 2); + if (decoration == Spv.SpvDecorationBinding) { + words.put(i + 3, idToNewBinding.get(targetId)); + } else if (decoration == Spv.SpvDecorationDescriptorSet) { + words.put(i + 3, idToNewSet.get(targetId)); + } + } + } + i += instrLen; + } + } + + @FunctionalInterface + private interface ResourceConsumer { void accept(int index, SpvcReflectedResource res); } + + @FunctionalInterface + private interface ReadOnlyClassifier { boolean isReadOnly(long compiler, int spvId, MemoryStack stack); } + + private static void forEachResource(long resources, int type, MemoryStack stack, ResourceConsumer body) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, type, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int count = (int) pCount.get(0); + if (count == 0) return; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int j = 0; j < count; j++) body.accept(j, list.get(j)); + } + + private static int collectComputeBindings(long resources, long compiler, int resourceType, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, IntArrayList glSlotsOut, int targetSet, int nextBinding, MemoryStack stack) { + return collectComputeBindings(resources, compiler, resourceType, idToNewSet, idToNewBinding, glSlotsOut, targetSet, nextBinding, stack, null); + } + + private static int collectComputeBindings(long resources, long compiler, int resourceType, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, IntArrayList glSlotsOut, int targetSet, int nextBinding, MemoryStack stack, List namesOut) { + final int[] next = { nextBinding }; + forEachResource(resources, resourceType, stack, (j, res) -> { + final int spvId = res.id(); + final int oldBinding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + idToNewSet.put(spvId, targetSet); + idToNewBinding.put(spvId, next[0]++); + glSlotsOut.add(oldBinding); + if (namesOut != null) namesOut.add(res.nameString()); + }); + return next[0]; + } + + private static boolean validateComputeBindingMap(ComputeBindingMap map, int program) { + final int maxSampler = 32; + final int maxImage = ContextState.MAX_IMAGE_UNITS; + final int maxIndexed = ContextState.MAX_INDEXED_BUFFERS; + return checkSlots(map.samplerGlSlots(), maxSampler, "sampler", program) + && checkSlots(map.roStorageTextureGlSlots(), maxImage, "readonly storage image", program) + && checkSlots(map.rwStorageTextureGlSlots(), maxImage, "readwrite storage image", program) + && checkSlots(map.roSsboGlSlots(), maxIndexed, "readonly SSBO", program) + && checkSlots(map.rwSsboGlSlots(), maxIndexed, "readwrite SSBO", program) + && checkSlots(map.uboGlSlots(), maxIndexed, "UBO", program); + } + + private static boolean checkSlots(int[] slots, int max, String kind, int program) { + for (int s : slots) { + if (s < 0 || s >= max) { + LOG.error("Compute program {}: {} layout(binding={}) is out of range [0,{}); rejecting link", program, kind, s, max); + return false; + } + } + return true; + } + + private record StorageSplitOut(IntArrayList glSlots, List names, IntArrayList glFormats, IntArrayList glTargets) { + static StorageSplitOut slotsOnly(IntArrayList glSlots) { + return new StorageSplitOut(glSlots, null, null, null); + } + + void add(long compiler, SpvcReflectedResource res, int oldBinding) { + glSlots.add(oldBinding); + if (names == null) return; + names.add(res.nameString()); + final long imageType = Spvc.spvc_compiler_get_type_handle(compiler, res.base_type_id()); + int glFormat = SpvImageFormatMap.glInternalFormat(Spvc.spvc_type_get_image_storage_format(imageType)); + if (glFormat == 0) { + final long sampled = Spvc.spvc_compiler_get_type_handle(compiler, Spvc.spvc_type_get_image_sampled_type(imageType)); + glFormat = SpvImageFormatMap.glFormatForSampledType(Spvc.spvc_type_get_basetype(sampled)); + } + glFormats.add(glFormat); + glTargets.add(SpvImageFormatMap.glTextureTarget( + Spvc.spvc_type_get_image_dimension(imageType), Spvc.spvc_type_get_image_arrayed(imageType))); + } + } + + private static int[] collectComputeStorageSplit(long resources, long compiler, int resourceType, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, StorageSplitOut ro, StorageSplitOut rw, int set0Binding, int set1Binding, MemoryStack stack, ReadOnlyClassifier classifier) { + final int[] split = { set0Binding, set1Binding }; + forEachResource(resources, resourceType, stack, (j, res) -> { + final int spvId = res.id(); + final int oldBinding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + if (classifier.isReadOnly(compiler, spvId, stack)) { + idToNewSet.put(spvId, 0); + idToNewBinding.put(spvId, split[0]++); + ro.add(compiler, res, oldBinding); + } else { + idToNewSet.put(spvId, 1); + idToNewBinding.put(spvId, split[1]++); + rw.add(compiler, res, oldBinding); + } + }); + return split; + } + + private static int collectResourceIds(long resources, long compiler, int resourceType, Int2IntOpenHashMap idToNewSet, Int2IntOpenHashMap idToNewBinding, int targetSet, int nextBinding, MemoryStack stack) { + final int[] next = { nextBinding }; + forEachResource(resources, resourceType, stack, (j, res) -> { + final int spvId = res.id(); + idToNewSet.put(spvId, targetSet); + idToNewBinding.put(spvId, next[0]++); + }); + return next[0]; + } + + private static ByteBuffer copyBuffer(ByteBuffer src) { + final ByteBuffer copy = memAlloc(src.remaining()); + copy.put(src.duplicate()); + copy.flip(); + return copy; + } + + public void shutdown() { + for (ProgramObject prog : programObjects.values()) { + releaseProgramGpuResources(prog); + } + programObjects.clear(); + for (ShaderObject obj : shaderObjects.values()) { + if (obj.spirv != null) memFree(obj.spirv); + } + shaderObjects.clear(); + } + + public static final class ShaderObject { + public final int type; // GL_VERTEX_SHADER or GL_FRAGMENT_SHADER + public String source = ""; + public ByteBuffer spirv; + public boolean compiled; + public String infoLog = ""; + public boolean deletePending; + public int attachCount; + public CompletableFuture spirvFuture; + public StageReflection reflection = StageReflection.EMPTY; + public GraphicsBindingMap graphicsBindingMap = GraphicsBindingMap.EMPTY; + public Set boolUniforms = Set.of(); + + public ShaderObject(int type) { + this.type = type; + } + + public boolean isVertex() { + return type == GL20.GL_VERTEX_SHADER; + } + + public boolean isFragment() { + return type == GL20.GL_FRAGMENT_SHADER; + } + + public boolean isGeometry() { + return type == GL32.GL_GEOMETRY_SHADER; + } + + public boolean isCompute() { + return type == GL43.GL_COMPUTE_SHADER; + } + } + + public record UniformMemberInfo( + int offset, int size, int arrayStride, boolean isVertex, + int vectorSize, int columns, int baseType, int arrayLen + ) {} + + public record UboMember( + String name, int offset, int size, int arrayStride, + int vectorSize, int columns, int baseType, int arrayLen + ) {} + + public record VsInput(String name, int binaryOffset, int originalLocation, int vecSize, int baseType) {} + + public record VsOutput(String name, int originalLocation) {} + + public record FsInput(String name, int binaryOffset, int originalLocation) {} + + public record StageReflection( + ResourceCounts counts, + List samplerNames, // SAMPLED_IMAGE, sorted by binding (post-remap) + List extraUniformNames, // SEPARATE_SAMPLERS - registered in nameToLocation only + List storageImageNames, // SEPARATE_IMAGE + STORAGE_IMAGE (RO + RW), sorted by binding (post-remap) + int uboSize, // binding-0 UBO total size in bytes; 0 if absent + List uboMembers, // members of the binding-0 UBO + List vsInputs, // VS only (FS leaves empty); binary offset for in-place patch + List vsOutputs, // VS only (FS leaves empty); for varying matching + List fsInputs, // FS only (VS leaves empty); for varying matching + int maxOutputLocation, // FS only; highest fragment output location, -1 if none + int numReadonlyStorageBuffers, + int numReadwriteStorageBuffers, + int numReadonlyStorageTextures, + int numReadwriteStorageTextures, + BlockReflection[] blocks + ) { + public static final StageReflection EMPTY = new StageReflection( + ResourceCounts.EMPTY, List.of(), List.of(), List.of(), 0, List.of(), List.of(), List.of(), List.of(), + -1, 0, 0, 0, 0, BlockReflection.emptyBlocks()); + } + + public record BlockReflection(int size, int binding, List members, boolean readOnly) { + public static final BlockReflection EMPTY = new BlockReflection(0, -1, List.of(), false); + + public static BlockReflection[] emptyBlocks() { + return new BlockReflection[] { EMPTY, EMPTY }; + } + } + + public record ComputeBindingMap( + int[] samplerGlSlots, + int[] roStorageTextureGlSlots, + int[] rwStorageTextureGlSlots, + int[] roSsboGlSlots, + int[] rwSsboGlSlots, + int[] uboGlSlots, + String[] samplerNames, + String[] roStorageTextureNames, + String[] rwStorageTextureNames, + boolean[] uboIsDefaultBlock, + int[] uboSizes, + int[] roStorageTextureFormats, + int[] rwStorageTextureFormats, + int[] roStorageTextureTargets, + int[] rwStorageTextureTargets + ) { + public static final ComputeBindingMap EMPTY = new ComputeBindingMap( + new int[0], new int[0], new int[0], new int[0], new int[0], new int[0], + new String[0], new String[0], new String[0], + new boolean[0], new int[0], + new int[0], new int[0], new int[0], new int[0]); + } + + public record GraphicsBindingMap(int[] roStorageTextureGlSlots, int[] rwStorageTextureGlSlots, int[] roSsboGlSlots) { + public static final GraphicsBindingMap EMPTY = new GraphicsBindingMap(new int[0], new int[0], new int[0]); + } + + public static StageReflection reflectStage(ByteBuffer spirv, boolean isVertex) { + if (spirv == null) return StageReflection.EMPTY; + return withSpvc(spirv, StageReflection.EMPTY, + (compiler, resources, stack) -> reflectStageImpl(compiler, resources, stack, isVertex)); + } + + private static StageReflection reflectStageImpl(long compiler, long resources, MemoryStack stack, boolean isVertex) { + final int numUBOs = countResourceTypeStatic(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack); + final int[] roRwBuf = CrossCompileUtil.countStorageBuffersSplit(resources, compiler, stack); + final int[] roRwImg = CrossCompileUtil.countStorageImagesSplit(resources, compiler, stack); + final int numStorageBuffers = roRwBuf[0] + roRwBuf[1]; + final int numStorageTextures = roRwImg[0] + roRwImg[1]; + + final IntArrayList samplerBindings = new IntArrayList(); + final List samplerNamesRaw = new ArrayList<>(); + collectSamplerEntries(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, samplerNamesRaw, samplerBindings, stack); + final int sCount = samplerBindings.size(); + final int[] perm = new int[sCount]; + for (int i = 0; i < sCount; i++) perm[i] = i; + IntArrays.quickSort(perm, (a, b) -> Integer.compare(samplerBindings.getInt(a), samplerBindings.getInt(b))); + final List samplerNames = new ArrayList<>(sCount); + for (int p : perm) samplerNames.add(samplerNamesRaw.get(p)); + + final List extraNames = new ArrayList<>(); + collectResourceNames(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, extraNames, stack); + + final IntArrayList storageImageBindings = new IntArrayList(); + final List storageImageNamesRaw = new ArrayList<>(); + collectSamplerEntries(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, storageImageNamesRaw, storageImageBindings, stack); + collectSamplerEntries(resources, compiler, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, storageImageNamesRaw, storageImageBindings, stack); + final int siCount = storageImageBindings.size(); + final int[] siPerm = new int[siCount]; + for (int i = 0; i < siCount; i++) siPerm[i] = i; + IntArrays.quickSort(siPerm, (a, b) -> Integer.compare(storageImageBindings.getInt(a), storageImageBindings.getInt(b))); + final List storageImageNames = new ArrayList<>(siCount); + for (int p : siPerm) storageImageNames.add(storageImageNamesRaw.get(p)); + + int uboSize = 0; + final List uboMembers = new ArrayList<>(); + final IntBuffer pOffset = stack.ints(0); + final IntBuffer pStride = stack.ints(0); + final PointerBuffer pSize = stack.pointers(0); + final PointerBuffer pUboList = stack.pointers(0); + final PointerBuffer pUboCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, pUboList, pUboCount) == Spvc.SPVC_SUCCESS) { + final int uboCount = (int) pUboCount.get(0); + if (uboCount > 0) { + final SpvcReflectedResource.Buffer ubos = SpvcReflectedResource.create(pUboList.get(0), uboCount); + for (int i = 0; i < uboCount; i++) { + final SpvcReflectedResource ubo = ubos.get(i); + final int uboBinding = Spvc.spvc_compiler_get_decoration(compiler, ubo.id(), Spv.SpvDecorationBinding); + if (uboBinding != 0) continue; + final long baseTypeHandle = Spvc.spvc_compiler_get_type_handle(compiler, ubo.base_type_id()); + if (Spvc.spvc_compiler_get_declared_struct_size(compiler, baseTypeHandle, pSize) == Spvc.SPVC_SUCCESS) { + uboSize = (int) pSize.get(0); + } + final int memberCount = Spvc.spvc_type_get_num_member_types(Spvc.spvc_compiler_get_type_handle(compiler, ubo.type_id())); + for (int m = 0; m < memberCount; m++) { + final String memberName = Spvc.spvc_compiler_get_member_name(compiler, ubo.base_type_id(), m); + if (memberName == null || memberName.isEmpty()) continue; + int memberOffset = 0; + if (Spvc.spvc_compiler_type_struct_member_offset(compiler, baseTypeHandle, m, pOffset) == Spvc.SPVC_SUCCESS) { + memberOffset = pOffset.get(0); + } + int memberSize = 0; + if (Spvc.spvc_compiler_get_declared_struct_member_size(compiler, baseTypeHandle, m, pSize) == Spvc.SPVC_SUCCESS) { + memberSize = (int) pSize.get(0); + } + int memberArrayStride = 0; + if (Spvc.spvc_compiler_type_struct_member_array_stride(compiler, baseTypeHandle, m, pStride) == Spvc.SPVC_SUCCESS) { + memberArrayStride = pStride.get(0); + } + final int memberTypeId = Spvc.spvc_type_get_member_type(baseTypeHandle, m); + final long memberTypeHandle = Spvc.spvc_compiler_get_type_handle(compiler, memberTypeId); + final int memberVectorSize = Spvc.spvc_type_get_vector_size(memberTypeHandle); + final int memberColumns = Spvc.spvc_type_get_columns(memberTypeHandle); + final int memberBaseType = Spvc.spvc_type_get_basetype(memberTypeHandle); + final int memberArrayLen = (memberArrayStride > 0) ? Math.max(1, memberSize / memberArrayStride) : 1; + uboMembers.add(new UboMember(memberName, memberOffset, memberSize, memberArrayStride, memberVectorSize, memberColumns, memberBaseType, memberArrayLen)); + } + } + } + } + + final BlockReflection[] blocks = BlockReflection.emptyBlocks(); + final PointerBuffer pSsboList = stack.pointers(0); + final PointerBuffer pSsboCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, pSsboList, pSsboCount) == Spvc.SPVC_SUCCESS) { + final int ssboCount = (int) pSsboCount.get(0); + if (ssboCount > 0) { + final SpvcReflectedResource.Buffer ssbos = SpvcReflectedResource.create(pSsboList.get(0), ssboCount); + for (int i = 0; i < ssboCount; i++) { + final SpvcReflectedResource ssbo = ssbos.get(i); + final String blockName = Spvc.spvc_compiler_get_name(compiler, ssbo.base_type_id()); + final int b = blockIndexForName(blockName); + if (b < 0) continue; + int blockSize = 0; + final long baseTypeHandle = Spvc.spvc_compiler_get_type_handle(compiler, ssbo.base_type_id()); + if (Spvc.spvc_compiler_get_declared_struct_size(compiler, baseTypeHandle, pSize) == Spvc.SPVC_SUCCESS) { + blockSize = (int) pSize.get(0); + } + final int blockBinding = Spvc.spvc_compiler_get_decoration(compiler, ssbo.id(), Spv.SpvDecorationBinding); + final boolean readOnly = CrossCompileUtil.isStorageBufferReadOnly(compiler, ssbo.id(), stack); + final List blockMembers = new ArrayList<>(); + collectBlockMembers(compiler, ssbo, baseTypeHandle, pOffset, pStride, pSize, blockMembers); + blocks[b] = new BlockReflection(blockSize, blockBinding, blockMembers, readOnly); + } + } + } + + final List vsInputs = new ArrayList<>(); + final List vsOutputs = new ArrayList<>(); + final List fsInputs = new ArrayList<>(); + int maxOutputLocation = -1; + final IntBuffer pBinaryOffset = stack.ints(0); + + final PointerBuffer pInList = stack.pointers(0); + final PointerBuffer pInCount = stack.pointers(0); + if (isVertex) { + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, pInList, pInCount) == Spvc.SPVC_SUCCESS) { + final int n = (int) pInCount.get(0); + if (n > 0) { + final SpvcReflectedResource.Buffer items = SpvcReflectedResource.create(pInList.get(0), n); + for (int i = 0; i < n; i++) { + final SpvcReflectedResource it = items.get(i); + final String name = it.nameString(); + if (name == null || name.isEmpty()) continue; + final int loc = Spvc.spvc_compiler_get_decoration(compiler, it.id(), Spv.SpvDecorationLocation); + final long typeHandle = Spvc.spvc_compiler_get_type_handle(compiler, it.type_id()); + final int vecSize = Spvc.spvc_type_get_vector_size(typeHandle); + final int baseType = Spvc.spvc_type_get_basetype(typeHandle); + if (!Spvc.spvc_compiler_get_binary_offset_for_decoration(compiler, it.id(), Spv.SpvDecorationLocation, pBinaryOffset)) continue; + vsInputs.add(new VsInput(name, pBinaryOffset.get(0), loc, vecSize, baseType)); + } + } + } + final PointerBuffer pOutList = stack.pointers(0); + final PointerBuffer pOutCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, pOutList, pOutCount) == Spvc.SPVC_SUCCESS) { + final int n = (int) pOutCount.get(0); + if (n > 0) { + final SpvcReflectedResource.Buffer items = SpvcReflectedResource.create(pOutList.get(0), n); + for (int i = 0; i < n; i++) { + final SpvcReflectedResource it = items.get(i); + final String name = it.nameString(); + if (name == null || name.isEmpty()) continue; + final int loc = Spvc.spvc_compiler_get_decoration(compiler, it.id(), Spv.SpvDecorationLocation); + vsOutputs.add(new VsOutput(name, loc)); + } + } + } + } else { + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, pInList, pInCount) == Spvc.SPVC_SUCCESS) { + final int n = (int) pInCount.get(0); + if (n > 0) { + final SpvcReflectedResource.Buffer items = SpvcReflectedResource.create(pInList.get(0), n); + for (int i = 0; i < n; i++) { + final SpvcReflectedResource it = items.get(i); + final String name = it.nameString(); + if (name == null || name.isEmpty()) continue; + final int loc = Spvc.spvc_compiler_get_decoration(compiler, it.id(), Spv.SpvDecorationLocation); + if (!Spvc.spvc_compiler_get_binary_offset_for_decoration(compiler, it.id(), Spv.SpvDecorationLocation, pBinaryOffset)) continue; + fsInputs.add(new FsInput(name, pBinaryOffset.get(0), loc)); + } + } + } + final PointerBuffer pFsOutList = stack.pointers(0); + final PointerBuffer pFsOutCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, pFsOutList, pFsOutCount) == Spvc.SPVC_SUCCESS) { + final int n = (int) pFsOutCount.get(0); + if (n > 0) { + final SpvcReflectedResource.Buffer items = SpvcReflectedResource.create(pFsOutList.get(0), n); + for (int i = 0; i < n; i++) { + maxOutputLocation = Math.max(maxOutputLocation, + Spvc.spvc_compiler_get_decoration(compiler, items.get(i).id(), Spv.SpvDecorationLocation)); + } + } + } + } + + return new StageReflection( + new ResourceCounts(samplerNames.size(), numUBOs, numStorageBuffers, numStorageTextures), + samplerNames, + extraNames, + storageImageNames, + uboSize, + uboMembers, + vsInputs, + vsOutputs, + fsInputs, + maxOutputLocation, + roRwBuf[0], roRwBuf[1], + roRwImg[0], roRwImg[1], + blocks); + } + + public static final String PER_FRAME_BLOCK_NAME = "AngelicaPerFrame"; + + public static final int PER_FRAME_BLOCK_BINDING = 15; + + public static final String PER_PASS_BLOCK_NAME = "AngelicaPerPass"; + + public static final int PER_PASS_BLOCK_BINDING = 14; + + public static final int BLOCK_PER_FRAME = 0; + public static final int BLOCK_PER_PASS = 1; + public static final int BLOCK_COUNT = 2; + public static final String[] BLOCK_NAMES = { PER_FRAME_BLOCK_NAME, PER_PASS_BLOCK_NAME }; + public static final int[] BLOCK_BINDINGS = { PER_FRAME_BLOCK_BINDING, PER_PASS_BLOCK_BINDING }; + + public static int blockIndexForName(String name) { + if (PER_FRAME_BLOCK_NAME.equals(name)) return BLOCK_PER_FRAME; + if (PER_PASS_BLOCK_NAME.equals(name)) return BLOCK_PER_PASS; + return -1; + } + + private static void collectBlockMembers(long compiler, SpvcReflectedResource block, long baseTypeHandle, IntBuffer pOffset, IntBuffer pStride, PointerBuffer pSize, List out) { + final int memberCount = Spvc.spvc_type_get_num_member_types(Spvc.spvc_compiler_get_type_handle(compiler, block.type_id())); + for (int m = 0; m < memberCount; m++) { + final String memberName = Spvc.spvc_compiler_get_member_name(compiler, block.base_type_id(), m); + if (memberName == null || memberName.isEmpty()) continue; + int memberOffset = 0; + if (Spvc.spvc_compiler_type_struct_member_offset(compiler, baseTypeHandle, m, pOffset) == Spvc.SPVC_SUCCESS) { + memberOffset = pOffset.get(0); + } + int memberSize = 0; + if (Spvc.spvc_compiler_get_declared_struct_member_size(compiler, baseTypeHandle, m, pSize) == Spvc.SPVC_SUCCESS) { + memberSize = (int) pSize.get(0); + } + int memberArrayStride = 0; + if (Spvc.spvc_compiler_type_struct_member_array_stride(compiler, baseTypeHandle, m, pStride) == Spvc.SPVC_SUCCESS) { + memberArrayStride = pStride.get(0); + } + final int memberTypeId = Spvc.spvc_type_get_member_type(baseTypeHandle, m); + final long memberTypeHandle = Spvc.spvc_compiler_get_type_handle(compiler, memberTypeId); + out.add(new UboMember(memberName, memberOffset, memberSize, memberArrayStride, + Spvc.spvc_type_get_vector_size(memberTypeHandle), + Spvc.spvc_type_get_columns(memberTypeHandle), + Spvc.spvc_type_get_basetype(memberTypeHandle), + (memberArrayStride > 0) ? Math.max(1, memberSize / memberArrayStride) : 1)); + } + } + + private static int countResourceTypeStatic(long resources, int resourceType, MemoryStack stack) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) { + return 0; + } + return (int) pCount.get(0); + } + + private static void collectSamplerEntries(long resources, long compiler, int resourceType, List namesOut, IntArrayList bindingsOut, MemoryStack stack) { + forEachResource(resources, resourceType, stack, (i, r) -> { + final String name = Spvc.spvc_compiler_get_name(compiler, r.id()); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, r.id(), Spv.SpvDecorationBinding); + namesOut.add(name != null ? name : ("sampler_" + i)); + bindingsOut.add(binding); + }); + } + + private static void collectResourceNames(long resources, long compiler, int resourceType, List out, MemoryStack stack) { + forEachResource(resources, resourceType, stack, (i, r) -> { + final String name = r.nameString(); + if (name != null && !name.isEmpty()) out.add(name); + }); + } + + public static UniformMemberInfo getMemberInfo(ProgramObject prog, int location, boolean vertex) { + if (vertex) { + final UniformMemberInfo vi = prog.vertexMemberInfo.get(location); + if (vi != null) return vi; + } else { + final UniformMemberInfo fi = prog.fragmentMemberInfo.get(location); + if (fi != null) return fi; + } + final UniformMemberInfo info = prog.locationToMemberInfo.get(location); + return (info != null && info.isVertex() == vertex) ? info : null; + } + + public static final class VertexVariant { + public ByteBuffer spirv; + public long sdlShader; + public int inputMask; + public final int[] inputVecSize = new int[16]; + public final int[] inputBaseType = new int[16]; + } + + public static final class ProgramObject { + public ByteBuffer computeSpirv; + public ByteBuffer fragmentSpirv; + public ByteBuffer geometrySpirv; + public ByteBuffer vertexSpirv; + public ComputeBindingMap computeBindingMap = ComputeBindingMap.EMPTY; + public GraphicsBindingMap vertexGraphicsBindingMap = GraphicsBindingMap.EMPTY; + public GraphicsBindingMap fragmentGraphicsBindingMap = GraphicsBindingMap.EMPTY; + public List fragmentSamplerNames = List.of(); + public List vertexSamplerNames = List.of(); + public List fragmentImageNames = List.of(); + public List vertexImageNames = List.of(); + public final HashSet allImageNames = new HashSet<>(); + public ResourceCounts computeResources = ResourceCounts.EMPTY; + public ResourceCounts fragmentResources = ResourceCounts.EMPTY; + public ResourceCounts vertexResources = ResourceCounts.EMPTY; + public String infoLog = ""; + public int externalUboBinding = -1; + public boolean deletePending; + public boolean linked; + public final Int2ObjectOpenHashMap locationToName = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectOpenHashMap fragmentMemberInfo = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectOpenHashMap locationToMemberInfo = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectOpenHashMap vertexMemberInfo = new Int2ObjectOpenHashMap<>(); + + @SuppressWarnings("unchecked") + public final Int2ObjectOpenHashMap[] blockMemberInfo = new Int2ObjectOpenHashMap[] { new Int2ObjectOpenHashMap<>(), new Int2ObjectOpenHashMap<>() }; + public final UniformMemberInfo[][] blockInfoBySlot = { EMPTY_INFO, EMPTY_INFO }; + public final int[] blockSize = new int[BLOCK_COUNT]; + public final int[] blockBinding = { -1, -1 }; + + public UniformMemberInfo anyBlockMemberInfo(int loc) { + final UniformMemberInfo m = blockMemberInfo[BLOCK_PER_FRAME].get(loc); + return m != null ? m : blockMemberInfo[BLOCK_PER_PASS].get(loc); + } + + private static final UniformMemberInfo[] EMPTY_INFO = new UniformMemberInfo[0]; + + public UniformMemberInfo[] vsInfoBySlot; + public UniformMemberInfo[] fsInfoBySlot; + public int uniformSlotCount; + public final int[] vertexInputBaseType = new int[16]; + public final int[] vertexInputVecSize = new int[16]; + public final String[] vertexInputName = new String[16]; + public String vertexSource = ""; + public int maxFragOutputLocation = -1; + public StageReflection vertexReflection = StageReflection.EMPTY; + public final Long2ObjectOpenHashMap vertexVariants = new Long2ObjectOpenHashMap<>(); + public final LongOpenHashSet vertexVariantFailed = new LongOpenHashSet(); + public final Object2IntOpenHashMap attribLocationBindings = newLocMap(); + public final Object2IntOpenHashMap resolvedAttribLocations = newLocMap(); + public final Object2IntOpenHashMap nameToLocation = newLocMap(); + public final Object2IntOpenHashMap samplerTextureUnits = newLocMap(); + public final Object2IntOpenHashMap imageTextureUnits = newLocMap(); + + public int[] vertexSamplerUnits = EMPTY_UNITS; + public int[] fragmentSamplerUnits = EMPTY_UNITS; + public boolean samplerUnitsDirty = true; + + private static final int[] EMPTY_UNITS = new int[0]; + + private static Object2IntOpenHashMap newLocMap() { + final Object2IntOpenHashMap m = new Object2IntOpenHashMap<>(); + m.defaultReturnValue(-1); + return m; + } + public final HashSet allSamplerNames = new HashSet<>(); + public final HashSet boolUniforms = new HashSet<>(); + public List activeUniformNames; + public List activeAttribNames; + + public List getActiveUniformNames() { + if (activeUniformNames == null) { + activeUniformNames = new ArrayList<>(nameToLocation.keySet()); + Collections.sort(activeUniformNames); + } + return activeUniformNames; + } + public List getActiveAttribNames() { + if (activeAttribNames == null) { + activeAttribNames = new ArrayList<>(linked ? resolvedAttribLocations.keySet() : attribLocationBindings.keySet()); + Collections.sort(activeAttribNames); + } + return activeAttribNames; + } + + public int getAttribGlType(String name) { + final int loc = resolvedAttribLocations.getInt(name); + if (loc < 0 || loc >= 16) return GL20.GL_FLOAT_VEC4; + final int vec = Math.max(1, vertexInputVecSize[loc]); + final int base = vertexInputBaseType[loc]; + if (base == Spvc.SPVC_BASETYPE_INT32) { + return switch (vec) { + case 1 -> GL11.GL_INT; + case 2 -> GL20.GL_INT_VEC2; + case 3 -> GL20.GL_INT_VEC3; + default -> GL20.GL_INT_VEC4; + }; + } + if (base == Spvc.SPVC_BASETYPE_UINT32) { + return switch (vec) { + case 1 -> GL11.GL_UNSIGNED_INT; + case 2 -> GL30.GL_UNSIGNED_INT_VEC2; + case 3 -> GL30.GL_UNSIGNED_INT_VEC3; + default -> GL30.GL_UNSIGNED_INT_VEC4; + }; + } + return switch (vec) { + case 1 -> GL11.GL_FLOAT; + case 2 -> GL20.GL_FLOAT_VEC2; + case 3 -> GL20.GL_FLOAT_VEC3; + default -> GL20.GL_FLOAT_VEC4; + }; + } + public int computeShader; + public int fragmentShader; + public int fragmentUboSize; + public int geometryShader; + public int nextUniformLocation = 0; + public int vertexInputMask; + public int vertexShader; + public int vertexUboSize; + public long sdlComputePipeline; + public long sdlFragmentShader; + public long sdlVertexShader; + public long lastComputeCb; + public long lastComputeFrame; + public long[] lastComputeUboHash; + + public void buildUniformSlotArrays() { + final int n = nextUniformLocation; + uniformSlotCount = n; + vsInfoBySlot = new UniformMemberInfo[n]; + fsInfoBySlot = new UniformMemberInfo[n]; + for (int b = 0; b < BLOCK_COUNT; b++) { + blockInfoBySlot[b] = new UniformMemberInfo[n]; + for (var it = blockMemberInfo[b].int2ObjectEntrySet().fastIterator(); it.hasNext(); ) { + final var e = it.next(); + final int k = e.getIntKey(); + if (k >= 0 && k < n) blockInfoBySlot[b][k] = e.getValue(); + } + } + for (var it = vertexMemberInfo.int2ObjectEntrySet().fastIterator(); it.hasNext(); ) { + final var e = it.next(); + final int k = e.getIntKey(); + if (k >= 0 && k < n) vsInfoBySlot[k] = e.getValue(); + } + for (var it = fragmentMemberInfo.int2ObjectEntrySet().fastIterator(); it.hasNext(); ) { + final var e = it.next(); + final int k = e.getIntKey(); + if (k >= 0 && k < n) fsInfoBySlot[k] = e.getValue(); + } + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvImageFormatMap.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvImageFormatMap.java new file mode 100644 index 000000000..2c2eaee58 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvImageFormatMap.java @@ -0,0 +1,75 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL30; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; + +public final class SpvImageFormatMap { + private SpvImageFormatMap() {} + + public static int glInternalFormat(int spvImageFormat) { + final InternalTextureFormat fmt = switch (spvImageFormat) { + case Spv.SpvImageFormatRgba32f -> InternalTextureFormat.RGBA32F; + case Spv.SpvImageFormatRgba16f -> InternalTextureFormat.RGBA16F; + case Spv.SpvImageFormatR32f -> InternalTextureFormat.R32F; + case Spv.SpvImageFormatRgba8 -> InternalTextureFormat.RGBA8; + case Spv.SpvImageFormatRgba8Snorm -> InternalTextureFormat.RGBA8_SNORM; + case Spv.SpvImageFormatRg32f -> InternalTextureFormat.RG32F; + case Spv.SpvImageFormatRg16f -> InternalTextureFormat.RG16F; + case Spv.SpvImageFormatR11fG11fB10f -> InternalTextureFormat.R11F_G11F_B10F; + case Spv.SpvImageFormatR16f -> InternalTextureFormat.R16F; + case Spv.SpvImageFormatRgba16 -> InternalTextureFormat.RGBA16; + case Spv.SpvImageFormatRgb10A2 -> InternalTextureFormat.RGB10_A2; + case Spv.SpvImageFormatRg16 -> InternalTextureFormat.RG16; + case Spv.SpvImageFormatRg8 -> InternalTextureFormat.RG8; + case Spv.SpvImageFormatR16 -> InternalTextureFormat.R16; + case Spv.SpvImageFormatR8 -> InternalTextureFormat.R8; + case Spv.SpvImageFormatRgba16Snorm -> InternalTextureFormat.RGBA16_SNORM; + case Spv.SpvImageFormatRg16Snorm -> InternalTextureFormat.RG16_SNORM; + case Spv.SpvImageFormatRg8Snorm -> InternalTextureFormat.RG8_SNORM; + case Spv.SpvImageFormatR16Snorm -> InternalTextureFormat.R16_SNORM; + case Spv.SpvImageFormatR8Snorm -> InternalTextureFormat.R8_SNORM; + case Spv.SpvImageFormatRgba32i -> InternalTextureFormat.RGBA32I; + case Spv.SpvImageFormatRgba16i -> InternalTextureFormat.RGBA16I; + case Spv.SpvImageFormatRgba8i -> InternalTextureFormat.RGBA8I; + case Spv.SpvImageFormatR32i -> InternalTextureFormat.R32I; + case Spv.SpvImageFormatRg32i -> InternalTextureFormat.RG32I; + case Spv.SpvImageFormatRg16i -> InternalTextureFormat.RG16I; + case Spv.SpvImageFormatRg8i -> InternalTextureFormat.RG8I; + case Spv.SpvImageFormatR16i -> InternalTextureFormat.R16I; + case Spv.SpvImageFormatR8i -> InternalTextureFormat.R8I; + case Spv.SpvImageFormatRgba32ui -> InternalTextureFormat.RGBA32UI; + case Spv.SpvImageFormatRgba16ui -> InternalTextureFormat.RGBA16UI; + case Spv.SpvImageFormatRgba8ui -> InternalTextureFormat.RGBA8UI; + case Spv.SpvImageFormatR32ui -> InternalTextureFormat.R32UI; + case Spv.SpvImageFormatRgb10a2ui -> InternalTextureFormat.RGB10_A2UI; + case Spv.SpvImageFormatRg32ui -> InternalTextureFormat.RG32UI; + case Spv.SpvImageFormatRg16ui -> InternalTextureFormat.RG16UI; + case Spv.SpvImageFormatRg8ui -> InternalTextureFormat.RG8UI; + case Spv.SpvImageFormatR16ui -> InternalTextureFormat.R16UI; + case Spv.SpvImageFormatR8ui -> InternalTextureFormat.R8UI; + default -> null; + }; + return fmt != null ? fmt.getGlFormat() : 0; + } + + public static int glTextureTarget(int spvDim, boolean arrayed) { + return switch (spvDim) { + case Spv.SpvDim3D -> GL12.GL_TEXTURE_3D; + case Spv.SpvDimCube -> GL13.GL_TEXTURE_CUBE_MAP; + default -> arrayed ? GL30.GL_TEXTURE_2D_ARRAY : GL11.GL_TEXTURE_2D; + }; + } + + public static int glFormatForSampledType(int spvBaseType) { + return switch (spvBaseType) { + case Spvc.SPVC_BASETYPE_UINT32 -> InternalTextureFormat.R32UI.getGlFormat(); + case Spvc.SPVC_BASETYPE_INT32 -> InternalTextureFormat.R32I.getGlFormat(); + default -> InternalTextureFormat.RGBA8.getGlFormat(); + }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140Writer.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140Writer.java new file mode 100644 index 000000000..46a702575 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140Writer.java @@ -0,0 +1,80 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess; +import org.lwjgl.system.MemoryUtil; + +import java.nio.FloatBuffer; + +public final class Std140Writer { + + private static final int MAT_COLUMN_STRIDE_BYTES = 16; + private static final int MAT_COLUMN_STRIDE_FLOATS = MAT_COLUMN_STRIDE_BYTES / 4; + + private Std140Writer() {} + + public static void write(FloatBuffer ubo, ShaderManager.UniformMemberInfo info, float[] src, int srcCount) { + final int rows = info.vectorSize(); + final int cols = info.columns(); + if (rows <= 0 || cols <= 0) { + throw new IllegalStateException("ShaderManager.UniformMemberInfo missing type descriptor (vectorSize=" + rows + ", columns=" + cols + "). SPVC reflection failed to capture the member's type - cannot dispatch std140 layout."); + } + final int floatsPerElement = rows * cols; + if (floatsPerElement == 0) return; + + final int arrayLen = info.arrayLen(); + final int maxFromSrc = src.length / floatsPerElement; + final int count = Math.min(Math.min(srcCount, arrayLen), maxFromSrc); + if (count <= 0) return; + + final int byteOffset = info.offset(); + final int elementStrideBytes = info.arrayStride() > 0 ? info.arrayStride() : floatsPerElement * 4; + + final boolean elementContig = (cols == 1) || rows == 4; + + if (elementContig) { + if (elementStrideBytes == floatsPerElement * 4) { + bulkPut(ubo, byteOffset >> 2, src, 0, floatsPerElement * count); + } else { + for (int e = 0; e < count; e++) { + bulkPut(ubo, (byteOffset + e * elementStrideBytes) >> 2, + src, e * floatsPerElement, floatsPerElement); + } + } + return; + } + + for (int e = 0; e < count; e++) { + final int elementByteOffset = byteOffset + e * elementStrideBytes; + final int srcOffset = e * floatsPerElement; + for (int c = 0; c < cols; c++) { + writeColumn(ubo, elementByteOffset + c * MAT_COLUMN_STRIDE_BYTES, src, srcOffset + c * rows, rows); + } + } + } + + private static void bulkPut(FloatBuffer ubo, int dstFloatIdx, float[] src, int srcOff, int floats) { + if (floats <= 0) return; + final int writableFloats = ubo.capacity() - dstFloatIdx; + if (writableFloats <= 0) return; + final int writeN = Math.min(floats, writableFloats); + final long dstAddr = MemoryUtil.memAddress(ubo) + ((long) dstFloatIdx) * 4L; + MemoryAccess.copyFloatsToAddr(src, srcOff, dstAddr, writeN); + } + + private static void writeColumn(FloatBuffer ubo, int byteOffset, float[] src, int srcOffset, int n) { + final int floatOffset = byteOffset >> 2; + final int writableFloats = Math.max(0, ubo.capacity() - floatOffset); + final int writeN = Math.min(n, writableFloats); + if (writeN > 0) { + final long dstAddr = MemoryUtil.memAddress(ubo) + ((long) floatOffset) * 4L; + MemoryAccess.copyFloatsToAddr(src, srcOffset, dstAddr, writeN); + } + final int padN = Math.min(MAT_COLUMN_STRIDE_FLOATS, writableFloats) - writeN; + if (padN > 0) { + final long padAddr = MemoryUtil.memAddress(ubo) + ((long) (floatOffset + writeN)) * 4L; + for (int i = 0; i < padN; i++) { + MemoryUtil.memPutFloat(padAddr + ((long) i) * 4L, 0f); + } + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformStaging.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformStaging.java new file mode 100644 index 000000000..3a392c5cb --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformStaging.java @@ -0,0 +1,35 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; + +public final class UniformStaging { + public ByteBuffer vsUniformBuf; + public FloatBuffer vsUniformFb; + public ByteBuffer fsUniformBuf; + public FloatBuffer fsUniformFb; + public boolean vsUniformDirty; + public boolean fsUniformDirty; + public float[][] uniformDataBySlot; + public long[] uniformValueHashBySlot; + + public void allocate(ShaderManager.ProgramObject prog) { + if (prog.vertexUboSize > 0) { + vsUniformBuf = MemoryUtil.memCalloc(prog.vertexUboSize); + vsUniformFb = vsUniformBuf.asFloatBuffer(); + } + if (prog.fragmentUboSize > 0) { + fsUniformBuf = MemoryUtil.memCalloc(prog.fragmentUboSize); + fsUniformFb = fsUniformBuf.asFloatBuffer(); + } + uniformDataBySlot = new float[prog.uniformSlotCount][]; + uniformValueHashBySlot = new long[prog.uniformSlotCount]; + } + + public void free() { + if (vsUniformBuf != null) { MemoryUtil.memFree(vsUniformBuf); vsUniformBuf = null; vsUniformFb = null; } + if (fsUniformBuf != null) { MemoryUtil.memFree(fsUniformBuf); fsUniformBuf = null; fsUniformFb = null; } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetype.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetype.java new file mode 100644 index 000000000..8bb62fe29 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetype.java @@ -0,0 +1,116 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLParserBaseListener; + +import java.util.ArrayList; +import java.util.List; + +import static com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.applyEdits; + +public final class UscaledRetype { + + static final String SUFFIX = "_i"; + + public record Attrib(String name, int location, int declVecSize, int boundVecSize, boolean signed) {} + + private UscaledRetype() {} + + public static String retype(String source, List attribs) { + if (attribs.isEmpty()) return source; + + final GLSLParser.Translation_unitContext root; + try { + root = GlslTransformUtils.parseFullQuiet(source); + } catch (Exception e) { + return null; + } + + final List edits = new ArrayList<>(); + final boolean[] found = new boolean[attribs.size()]; + + ParseTreeWalker.DEFAULT.walk(new GLSLParserBaseListener() { + @Override + public void enterDeclaration(GLSLParser.DeclarationContext ctx) { + final GLSLParser.Init_declarator_listContext idl = ctx.init_declarator_list(); + if (idl == null) return; + final GLSLParser.Single_declarationContext single = idl.single_declaration(); + if (single == null || single.fully_specified_type() == null) return; + final GLSLParser.Fully_specified_typeContext fst = single.fully_specified_type(); + if (fst.type_qualifier() == null) return; + + boolean isIn = false; + for (GLSLParser.Single_type_qualifierContext stq : fst.type_qualifier().single_type_qualifier()) { + if (stq.storage_qualifier() != null && "in".equals(stq.storage_qualifier().getText())) { + isIn = true; + break; + } + } + if (!isIn) return; + if (fst.type_specifier() == null || fst.type_specifier().type_specifier_nonarray() == null) return; + if (single.typeless_declaration() == null || single.typeless_declaration().IDENTIFIER() == null) return; + + final String name = single.typeless_declaration().IDENTIFIER().getText(); + int idx = -1; + for (int i = 0; i < attribs.size(); i++) { + if (attribs.get(i).name().equals(name)) { idx = i; break; } + } + if (idx < 0 || found[idx]) return; + found[idx] = true; + final Attrib a = attribs.get(idx); + + final GLSLParser.Type_specifier_nonarrayContext typeCtx = fst.type_specifier().type_specifier_nonarray(); + edits.add(new Edit(typeCtx.getStart().getStartIndex(), typeCtx.getStop().getStopIndex(), intTypeName(a.boundVecSize(), a.signed()))); + + final Token nameTok = single.typeless_declaration().IDENTIFIER().getSymbol(); + edits.add(new Edit(nameTok.getStartIndex(), nameTok.getStopIndex(), name + SUFFIX)); + + final int declEnd = ctx.getStop().getStopIndex(); + edits.add(new Edit(declEnd + 1, declEnd, "\n" + floatTypeName(a.declVecSize()) + " " + name + " = " + conversion(a) + ";")); + } + }, root); + + for (int i = 0; i < found.length; i++) { + if (!found[i]) return null; + } + + return applyEdits(source, edits); + } + + private static String conversion(Attrib a) { + final int decl = a.declVecSize(); + final int bound = a.boundVecSize(); + final String src = a.name() + SUFFIX; + if (bound >= decl) { + return floatTypeName(decl) + "(" + src + swizzle(decl, bound) + ")"; + } + final StringBuilder sb = new StringBuilder(floatTypeName(decl)).append('(').append(floatTypeName(bound)).append('(').append(src).append(')'); + for (int i = bound; i < decl; i++) { + sb.append(i == 3 ? ", 1.0" : ", 0.0"); + } + return sb.append(')').toString(); + } + + private static String intTypeName(int size, boolean signed) { + if (size <= 1) return signed ? "int" : "uint"; + return (signed ? "ivec" : "uvec") + size; + } + + private static String floatTypeName(int size) { + return size <= 1 ? "float" : "vec" + size; + } + + private static String swizzle(int declSize, int boundSize) { + if (boundSize <= declSize) return ""; + return switch (declSize) { + case 1 -> ".x"; + case 2 -> ".xy"; + case 3 -> ".xyz"; + default -> ""; + }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/CrossCompileUtil.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/CrossCompileUtil.java new file mode 100644 index 000000000..717853f14 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/CrossCompileUtil.java @@ -0,0 +1,174 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.cross; + +import org.lwjgl.system.MemoryUtil; +import com.gtnewhorizons.angelica.config.SystemProperties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicInteger; + +public final class CrossCompileUtil { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + + public static final AtomicInteger SHADER_DUMP_COUNTER = new AtomicInteger(); + + private CrossCompileUtil() {} + + public static String stageSuffix(int glShaderType) { + if (glShaderType == GL20.GL_VERTEX_SHADER) return "vert"; + if (glShaderType == GL20.GL_FRAGMENT_SHADER) return "frag"; + if (glShaderType == GL32.GL_GEOMETRY_SHADER) return "geom"; + if (glShaderType == GL43.GL_COMPUTE_SHADER) return "comp"; + return "unknown"; + } + + public static void dumpSpirv(ByteBuffer spirv, int id, int glShaderType) { + final Path dir = SystemProperties.shaderDumpDir("cross"); + if (dir == null) return; + try { + Files.createDirectories(dir); + final ByteBuffer dup = spirv.duplicate(); + final byte[] bytes = new byte[dup.remaining()]; + dup.get(bytes); + Files.write(dir.resolve(id + "." + stageSuffix(glShaderType) + ".spv"), bytes); + } catch (IOException e) { + LOG.warn("Failed to dump SPIR-V #{}: {}", id, e.getMessage()); + } + } + + public static void dumpText(String src, int id, int glShaderType, String ext) { + final Path dir = SystemProperties.shaderDumpDir("cross"); + if (dir == null) return; + try { + Files.createDirectories(dir); + Files.writeString(dir.resolve(id + "." + stageSuffix(glShaderType) + "." + ext), src, StandardCharsets.UTF_8); + } catch (IOException e) { + LOG.warn("Failed to dump {} #{}: {}", ext, id, e.getMessage()); + } + } + + public static void dumpBytes(ByteBuffer data, int id, int glShaderType, String ext) { + final Path dir = SystemProperties.shaderDumpDir("cross"); + if (dir == null) return; + try { + Files.createDirectories(dir); + final ByteBuffer dup = data.duplicate(); + final byte[] bytes = new byte[dup.remaining()]; + dup.get(bytes); + Files.write(dir.resolve(id + "." + stageSuffix(glShaderType) + "." + ext), bytes); + } catch (IOException e) { + LOG.warn("Failed to dump {} #{}: {}", ext, id, e.getMessage()); + } + } + + public static int countResources(long resources, int resourceType, MemoryStack stack) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) { + return 0; + } + return (int) pCount.get(0); + } + + public static RuntimeException spvcError(long ctx, String backend, String stage) { + final String msg = Spvc.spvc_context_get_last_error_string(ctx); + return new RuntimeException(backend + " cross-compile failed at " + stage + ": " + (msg != null ? msg : "(no message)")); + } + + public static int[] countStorageImagesSplit(long resources, long compiler, MemoryStack stack) { + int ro = countResources(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, stack); + int rw = 0; + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, pList, pCount) != Spvc.SPVC_SUCCESS) { + return new int[] { ro, rw }; + } + final int count = (int) pCount.get(0); + if (count == 0) return new int[] { ro, rw }; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + if (Spvc.spvc_compiler_has_decoration(compiler, list.get(i).id(), Spv.SpvDecorationNonWritable)) ro++; + else rw++; + } + return new int[] { ro, rw }; + } + + public static int[] countStorageBuffersSplit(long resources, long compiler, MemoryStack stack) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, pList, pCount) != Spvc.SPVC_SUCCESS) { + return new int[] { 0, 0 }; + } + final int count = (int) pCount.get(0); + if (count == 0) return new int[] { 0, 0 }; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + int ro = 0, rw = 0; + for (int i = 0; i < count; i++) { + if (isStorageBufferReadOnly(compiler, list.get(i).id(), stack)) ro++; + else rw++; + } + return new int[] { ro, rw }; + } + + public static boolean isStorageBufferReadOnly(long compiler, int varId, MemoryStack stack) { + final PointerBuffer pDecorations = stack.pointers(0); + final PointerBuffer pNumDecorations = stack.pointers(0); + if (Spvc.spvc_compiler_get_buffer_block_decorations(compiler, varId, pDecorations, pNumDecorations) != Spvc.SPVC_SUCCESS) { + return false; + } + final long n = pNumDecorations.get(0); + if (n <= 0) return false; + final long ptr = pDecorations.get(0); + final IntBuffer decs = MemoryUtil.memIntBuffer(ptr, (int) n); + for (int i = 0; i < n; i++) { + if (decs.get(i) == Spv.SpvDecorationNonWritable) return true; + } + return false; + } + + public static int[] parseLocalSize(ByteBuffer spirv) { + final IntBuffer w = spirv.asIntBuffer(); + final int wordCount = w.limit(); + int i = 5; // 5-word SPIR-V header (magic, version, generator, bound, schema) + int lx = 1, ly = 1, lz = 1; + boolean foundLiteral = false; + boolean sawExecutionModeId = false; + while (i < wordCount) { + final int word0 = w.get(i); + final int opcode = word0 & 0xFFFF; + final int instrLen = (word0 >>> 16) & 0xFFFF; + if (instrLen == 0) break; + if (opcode == 16 && instrLen >= 6) { // SpvOpExecutionMode + final int mode = w.get(i + 2); + if (mode == 17) { // SpvExecutionModeLocalSize + lx = w.get(i + 3); + ly = w.get(i + 4); + lz = w.get(i + 5); + foundLiteral = true; + } + } else if (opcode == 331) { // SpvOpExecutionModeId + sawExecutionModeId = true; + } + i += instrLen; + } + if (!foundLiteral && sawExecutionModeId) { + LOG.warn("SPIR-V uses OpExecutionModeId (spec-constant LocalSizeId); falling back to {{1,1,1}} - not supported by parseLocalSize"); + } + return new int[] { lx, ly, lz }; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/D3DCompiler.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/D3DCompiler.java new file mode 100644 index 000000000..be874bc1e --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/D3DCompiler.java @@ -0,0 +1,170 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.dxbc; + +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.JNI; +import org.lwjgl.system.Library; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.Pointer; +import org.lwjgl.system.SharedLibrary; +import org.lwjgl.system.libffi.FFICIF; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.charset.StandardCharsets; + +import static org.lwjgl.system.APIUtil.apiGetFunctionAddress; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.NULL; +import static org.lwjgl.system.MemoryUtil.memAddress; +import static org.lwjgl.system.MemoryUtil.memAlloc; +import static org.lwjgl.system.MemoryUtil.memCopy; +import static org.lwjgl.system.MemoryUtil.memGetAddress; +import static org.lwjgl.system.libffi.LibFFI.FFI_DEFAULT_ABI; +import static org.lwjgl.system.libffi.LibFFI.FFI_OK; +import static org.lwjgl.system.libffi.LibFFI.ffi_call; +import static org.lwjgl.system.libffi.LibFFI.ffi_prep_cif; +import static org.lwjgl.system.libffi.LibFFI.ffi_type_pointer; +import static org.lwjgl.system.libffi.LibFFI.ffi_type_sint32; +import static org.lwjgl.system.libffi.LibFFI.ffi_type_uint32; +import static org.lwjgl.system.libffi.LibFFI.ffi_type_uint64; + +public final class D3DCompiler { + + private static final SharedLibrary D3DCOMPILER = Library.loadNative(D3DCompiler.class, "com.gtnewhorizons.angelica.sdlgpu", null, "d3dcompiler_47", "d3dcompiler"); + + private static final long D3D_COMPILE_ADDR = apiGetFunctionAddress(D3DCOMPILER, "D3DCompile"); + + public static final int D3DCOMPILE_ENABLE_STRICTNESS = 0x800; + public static final int D3DCOMPILE_OPTIMIZATION_LEVEL3 = 0xC000; + + private static final FFICIF CIF; + private static final PointerBuffer ATYPES; + static { + ATYPES = MemoryUtil.memAllocPointer(11); + ATYPES.put(0, ffi_type_pointer.address()) // LPCVOID pSrcData + .put(1, ffi_type_uint64.address()) // SIZE_T SrcDataSize + .put(2, ffi_type_pointer.address()) // LPCSTR pSourceName + .put(3, ffi_type_pointer.address()) // const D3D_SHADER_MACRO* pDefines + .put(4, ffi_type_pointer.address()) // ID3DInclude* pInclude + .put(5, ffi_type_pointer.address()) // LPCSTR pEntrypoint + .put(6, ffi_type_pointer.address()) // LPCSTR pTarget + .put(7, ffi_type_uint32.address()) // UINT Flags1 + .put(8, ffi_type_uint32.address()) // UINT Flags2 + .put(9, ffi_type_pointer.address()) // ID3DBlob** ppCode + .put(10, ffi_type_pointer.address());// ID3DBlob** ppErrorMsgs + CIF = FFICIF.malloc(); + final int status = ffi_prep_cif(CIF, FFI_DEFAULT_ABI, ffi_type_sint32, ATYPES); + if (status != FFI_OK) { + throw new IllegalStateException("ffi_prep_cif failed for D3DCompile: " + status); + } + } + + private static final long VTBL_RELEASE = 2L * Pointer.POINTER_SIZE; + private static final long VTBL_GET_BUFFER_POINTER = 3L * Pointer.POINTER_SIZE; + private static final long VTBL_GET_BUFFER_SIZE = 4L * Pointer.POINTER_SIZE; + + private D3DCompiler() {} + + public static ByteBuffer compile(String hlsl, String entry, String target, int flags1, int flags2) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer src = stack.UTF8(hlsl, false); + return compile(memAddress(src), src.remaining(), entry, target, flags1, flags2); + } + } + + public static ByteBuffer compile(long srcAddr, int srcLen, String entry, String target, int flags1, int flags2) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer entryBuf = stack.ASCII(entry); + final ByteBuffer targetBuf = stack.ASCII(target); + final PointerBuffer ppCode = stack.callocPointer(1); + final PointerBuffer ppErr = stack.callocPointer(1); + + final PointerBuffer slotSrcData = stack.pointers(srcAddr); + final LongBuffer slotSrcDataSize = stack.longs(srcLen); + final PointerBuffer slotSourceName = stack.pointers(NULL); + final PointerBuffer slotDefines = stack.pointers(NULL); + final PointerBuffer slotInclude = stack.pointers(NULL); + final PointerBuffer slotEntrypoint = stack.pointers(memAddress(entryBuf)); + final PointerBuffer slotTarget = stack.pointers(memAddress(targetBuf)); + final IntBuffer slotFlags1 = stack.ints(flags1); + final IntBuffer slotFlags2 = stack.ints(flags2); + final PointerBuffer slotPpCode = stack.pointers(memAddress(ppCode)); + final PointerBuffer slotPpErr = stack.pointers(memAddress(ppErr)); + + final PointerBuffer avalues = stack.mallocPointer(11); + avalues.put(0, memAddress(slotSrcData)); + avalues.put(1, memAddress(slotSrcDataSize)); + avalues.put(2, memAddress(slotSourceName)); + avalues.put(3, memAddress(slotDefines)); + avalues.put(4, memAddress(slotInclude)); + avalues.put(5, memAddress(slotEntrypoint)); + avalues.put(6, memAddress(slotTarget)); + avalues.put(7, memAddress(slotFlags1)); + avalues.put(8, memAddress(slotFlags2)); + avalues.put(9, memAddress(slotPpCode)); + avalues.put(10, memAddress(slotPpErr)); + + final ByteBuffer rvalue = stack.malloc(4); + ffi_call(CIF, D3D_COMPILE_ADDR, rvalue, avalues); + final int hresult = rvalue.getInt(0); + + final long codeBlob = ppCode.get(0); + final long errBlob = ppErr.get(0); + + if (hresult != 0) { + final String msg = errBlob != NULL ? readBlobAsAscii(errBlob) : "(no error blob)"; + if (errBlob != NULL) releaseBlob(errBlob); + if (codeBlob != NULL) releaseBlob(codeBlob); + throw new RuntimeException("D3DCompile failed (HRESULT=0x" + Integer.toHexString(hresult) + "): " + msg); + } + + try { + if (codeBlob == NULL) { + throw new RuntimeException("D3DCompile succeeded but produced no code blob"); + } + return copyBlobBytes(codeBlob); + } finally { + if (codeBlob != NULL) releaseBlob(codeBlob); + if (errBlob != NULL) releaseBlob(errBlob); + } + } + } + + private static ByteBuffer copyBlobBytes(long blob) { + final long vtbl = memGetAddress(blob); + final long getPtr = memGetAddress(vtbl + VTBL_GET_BUFFER_POINTER); + final long getSize = memGetAddress(vtbl + VTBL_GET_BUFFER_SIZE); + final long dataPtr = JNI.invokePP(blob, getPtr); + final long dataLen = JNI.invokePP(blob, getSize); + final ByteBuffer out = memAlloc((int) dataLen); + memCopy(dataPtr, memAddress(out), dataLen); + return out; + } + + private static String readBlobAsAscii(long blob) { + final long vtbl = memGetAddress(blob); + final long getPtr = memGetAddress(vtbl + VTBL_GET_BUFFER_POINTER); + final long getSize = memGetAddress(vtbl + VTBL_GET_BUFFER_SIZE); + final long dataPtr = JNI.invokePP(blob, getPtr); + final long dataLen = JNI.invokePP(blob, getSize); + if (dataPtr == NULL || dataLen <= 0) return "(empty)"; + final ByteBuffer view = MemoryUtil.memByteBuffer(dataPtr, (int) dataLen); + int end = view.remaining(); + while (end > 0) { + final byte b = view.get(end - 1); + if (b != 0 && b != '\n' && b != '\r' && b != ' ') break; + end--; + } + final byte[] bytes = new byte[end]; + view.duplicate().get(bytes, 0, end); + return new String(bytes, StandardCharsets.US_ASCII); + } + + private static void releaseBlob(long blob) { + final long vtbl = memGetAddress(blob); + final long releaseAddr = memGetAddress(vtbl + VTBL_RELEASE); + JNI.invokePP(blob, releaseAddr); + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCrossCompile.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCrossCompile.java new file mode 100644 index 000000000..ee9b00d19 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCrossCompile.java @@ -0,0 +1,243 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.dxbc; + +import org.lwjgl.system.MemoryUtil; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.sdlgpu.shader.cross.CrossCompileUtil; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcHLSLResourceBinding; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Arrays; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.memAddress; +import static org.lwjgl.system.MemoryUtil.memAlloc; +import static org.lwjgl.system.MemoryUtil.memByteBufferNT1; +import static org.lwjgl.system.MemoryUtil.memUTF8; + +public final class DxbcCrossCompile { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final String BACKEND = "DXBC"; + + public record Output(ByteBuffer code, String entrypoint) {} + + private static final int CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap CACHE = new Object2ObjectLinkedOpenHashMap<>(); + + private static final class CacheKey { + public final byte[] spirvBytes; + public final int glShaderType; + public final int hash; + public CacheKey(byte[] b, int t) { + this.spirvBytes = b; + this.glShaderType = t; + this.hash = Arrays.hashCode(b) * 31 + t; + } + @Override public int hashCode() { return hash; } + @Override public boolean equals(Object o) { + if (!(o instanceof CacheKey k)) return false; + return k.glShaderType == glShaderType && k.hash == hash && Arrays.equals(k.spirvBytes, spirvBytes); + } + } + + private record CacheValue(byte[] codeBytes, String entrypoint) {} + + public static void clearCache() { + synchronized (CACHE) { CACHE.clear(); } + } + + private DxbcCrossCompile() {} + + public static Output compile(ByteBuffer spirv, int glShaderType) { + final boolean isCompute = (glShaderType == GL43.GL_COMPUTE_SHADER); + final String target; + if (glShaderType == GL20.GL_VERTEX_SHADER) target = "vs_5_1"; + else if (glShaderType == GL20.GL_FRAGMENT_SHADER) target = "ps_5_1"; + else if (isCompute) target = "cs_5_1"; + else throw new UnsupportedOperationException("Unsupported shader type for DXBC cross-compile: 0x" + Integer.toHexString(glShaderType)); + + final byte[] spirvHeap = new byte[spirv.remaining()]; + spirv.duplicate().get(spirvHeap); + final CacheKey key = new CacheKey(spirvHeap, glShaderType); + final CacheValue cached; + synchronized (CACHE) { + cached = CACHE.getAndMoveToFirst(key); + } + if (cached != null) { + final ByteBuffer copy = memAlloc(cached.codeBytes.length); + copy.put(cached.codeBytes).flip(); + return new Output(copy, cached.entrypoint); + } + + final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1; + if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType); + + final String hlsl = compileToHlsl(spirv, glShaderType); + if (dumpId >= 0) CrossCompileUtil.dumpText(hlsl, dumpId, glShaderType, "hlsl"); + + final ByteBuffer hlslNative = memUTF8(hlsl, false); + try { + final ByteBuffer dxbc = D3DCompiler.compile(memAddress(hlslNative), hlslNative.remaining(), "main", target, D3DCompiler.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCompiler.D3DCOMPILE_ENABLE_STRICTNESS, 0); + if (dumpId >= 0) CrossCompileUtil.dumpBytes(dxbc, dumpId, glShaderType, "dxbc"); + final byte[] dxbcHeap = new byte[dxbc.remaining()]; + dxbc.duplicate().get(dxbcHeap); + synchronized (CACHE) { + CACHE.putAndMoveToFirst(key, new CacheValue(dxbcHeap, "main")); + while (CACHE.size() > CACHE_MAX) CACHE.removeLast(); + } + return new Output(dxbc, "main"); + } finally { + MemoryUtil.memFree(hlslNative); + } + } + + static String compileToHlsl(ByteBuffer spirv, int glShaderType) { + final boolean isCompute = (glShaderType == GL43.GL_COMPUTE_SHADER); + try (MemoryStack stack = stackPush()) { + final PointerBuffer pContext = stack.pointers(0); + if (Spvc.spvc_context_create(pContext) != Spvc.SPVC_SUCCESS) { + throw new RuntimeException("DXBC cross-compile failed: spvc_context_create"); + } + final long ctx = pContext.get(0); + try { + final IntBuffer spirvWords = spirv.asIntBuffer(); + final PointerBuffer pParsedIR = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, spirvWords, spirvWords.remaining(), pParsedIR) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "parse_spirv"); + } + + final PointerBuffer pCompiler = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_HLSL, pParsedIR.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_compiler(HLSL)"); + } + final long compiler = pCompiler.get(0); + + final PointerBuffer pOpts = stack.pointers(0); + if (Spvc.spvc_compiler_create_compiler_options(compiler, pOpts) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_compiler_options"); + } + final long opts = pOpts.get(0); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_HLSL_SHADER_MODEL, 51); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_HLSL_POINT_COORD_COMPAT, 1); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_HLSL_POINT_SIZE_COMPAT, 1); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_HLSL_USE_ENTRY_POINT_NAME, 1); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_HLSL_NONWRITABLE_UAV_TEXTURE_AS_SRV, 1); + if (Spvc.spvc_compiler_install_compiler_options(compiler, opts) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "install_compiler_options"); + } + + final PointerBuffer pResources = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(compiler, pResources) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_shader_resources"); + } + final long resources = pResources.get(0); + + addStageBindings(compiler, resources, layoutFor(glShaderType), stack); + + final PointerBuffer pSrc = stack.pointers(0); + if (Spvc.spvc_compiler_compile(compiler, pSrc) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "compile"); + } + return memUTF8(memByteBufferNT1(pSrc.get(0))); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + } + + private record StageBindingLayout(int execModel, int srvSpace, int uboSpace, int uavSpace) {} + + private static final StageBindingLayout VS = new StageBindingLayout(Spv.SpvExecutionModelVertex, 0, 1, -1); + private static final StageBindingLayout FS = new StageBindingLayout(Spv.SpvExecutionModelFragment, 2, 3, -1); + private static final StageBindingLayout CS = new StageBindingLayout(Spv.SpvExecutionModelGLCompute, 0, 2, 1); + + private static StageBindingLayout layoutFor(int glShaderType) { + return switch (glShaderType) { + case GL20.GL_VERTEX_SHADER -> VS; + case GL20.GL_FRAGMENT_SHADER -> FS; + case GL43.GL_COMPUTE_SHADER -> CS; + default -> throw new UnsupportedOperationException("Unsupported shader type: 0x" + Integer.toHexString(glShaderType)); + }; + } + + private enum ResourceClass { SRV_WITH_SAMPLER, SAMPLER_ONLY, CBV } + + @FunctionalInterface + private interface ReadOnlyClassifier { + boolean isReadOnly(long compiler, int spvId, MemoryStack stack); + } + + private static void addStageBindings(long compiler, long resources, StageBindingLayout layout, MemoryStack stack) { + addBindingsForType(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, layout, stack, ResourceClass.SRV_WITH_SAMPLER, layout.srvSpace); + addBindingsForType(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, layout, stack, ResourceClass.SAMPLER_ONLY, layout.srvSpace); + addBindingsForType(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, layout, stack, ResourceClass.CBV, layout.uboSpace); + addStorageBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, layout, stack, (c, id, st) -> true); + addStorageBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, layout, stack, (c, id, st) -> Spvc.spvc_compiler_has_decoration(c, id, Spv.SpvDecorationNonWritable)); + addStorageBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, layout, stack, CrossCompileUtil::isStorageBufferReadOnly); + } + + private static void addBindingsForType(long compiler, long resources, int resourceType, StageBindingLayout layout, MemoryStack stack, ResourceClass cls, int space) { + forEachResource(compiler, resources, resourceType, stack, (spvId, set, binding) -> { + final SpvcHLSLResourceBinding b = SpvcHLSLResourceBinding.calloc(stack); + Spvc.spvc_hlsl_resource_binding_init(b); + b.stage(layout.execModel).desc_set(set).binding(binding); + switch (cls) { + case SRV_WITH_SAMPLER -> { + b.srv().set(space, binding); + b.sampler().set(space, binding); + } + case SAMPLER_ONLY -> b.sampler().set(space, binding); + case CBV -> b.cbv().set(space, binding); + } + if (Spvc.spvc_compiler_hlsl_add_resource_binding(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("hlsl_add_resource_binding failed: stage=0x{} cls={} id={} set={} binding={}", Integer.toHexString(layout.execModel), cls, spvId, set, binding); + } + }); + } + + private static void addStorageBindings(long compiler, long resources, int resourceType, StageBindingLayout layout, MemoryStack stack, ReadOnlyClassifier classifier) { + forEachResource(compiler, resources, resourceType, stack, (spvId, set, binding) -> { + final boolean readOnly = classifier.isReadOnly(compiler, spvId, stack); + final SpvcHLSLResourceBinding b = SpvcHLSLResourceBinding.calloc(stack); + Spvc.spvc_hlsl_resource_binding_init(b); + b.stage(layout.execModel).desc_set(set).binding(binding); + if (readOnly || layout.uavSpace < 0) { + b.srv().set(layout.srvSpace, binding); + } else { + b.uav().set(layout.uavSpace, binding); + } + if (Spvc.spvc_compiler_hlsl_add_resource_binding(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("hlsl_add_resource_binding (storage) failed: stage=0x{} type=0x{} id={} set={} binding={} ro={}", Integer.toHexString(layout.execModel), Integer.toHexString(resourceType), spvId, set, binding, readOnly); + } + }); + } + + @FunctionalInterface + private interface ResourceVisitor { void accept(int spvId, int set, int binding); } + + private static void forEachResource(long compiler, long resources, int resourceType, MemoryStack stack, ResourceVisitor visitor) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int count = (int) pCount.get(0); + if (count == 0) return; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + final int spvId = list.get(i).id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + visitor.accept(spvId, set, binding); + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompile.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompile.java new file mode 100644 index 000000000..5da592194 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompile.java @@ -0,0 +1,354 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.msl; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.sdlgpu.shader.cross.CrossCompileUtil; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcMslResourceBinding2; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Arrays; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.memAlloc; +import static org.lwjgl.system.MemoryUtil.memUTF8; + +public final class MslCrossCompile { + + private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU"); + private static final String BACKEND = "MSL"; + + public record Output(ByteBuffer code, String entrypoint) {} + + private static final int CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap CACHE = new Object2ObjectLinkedOpenHashMap<>(); + + private static final class CacheKey { + public final byte[] spirvBytes; + public final int glShaderType; + public final int hash; + public CacheKey(byte[] b, int t) { + this.spirvBytes = b; + this.glShaderType = t; + this.hash = Arrays.hashCode(b) * 31 + t; + } + @Override public int hashCode() { return hash; } + @Override public boolean equals(Object o) { + if (!(o instanceof CacheKey k)) return false; + return k.glShaderType == glShaderType && k.hash == hash && Arrays.equals(k.spirvBytes, spirvBytes); + } + } + + private record CacheValue(byte[] codeBytes, String entrypoint) {} + + public static void clearCache() { + synchronized (CACHE) { CACHE.clear(); } + } + + @FunctionalInterface + private interface BufferSlotFn { public int slot(int set, int binding); } + + @FunctionalInterface + private interface IntSlotFn { public int slot(int binding); } + + private MslCrossCompile() {} + + public static Output compile(ByteBuffer spirv, int glShaderType) { + final int executionModel; + if (glShaderType == GL20.GL_VERTEX_SHADER) { + executionModel = Spv.SpvExecutionModelVertex; + } else if (glShaderType == GL20.GL_FRAGMENT_SHADER) { + executionModel = Spv.SpvExecutionModelFragment; + } else if (glShaderType == GL43.GL_COMPUTE_SHADER) { + executionModel = Spv.SpvExecutionModelGLCompute; + } else { + throw new UnsupportedOperationException("Unsupported shader type for MSL cross-compile: 0x" + Integer.toHexString(glShaderType)); + } + + final byte[] spirvHeap = new byte[spirv.remaining()]; + spirv.duplicate().get(spirvHeap); + final CacheKey key = new CacheKey(spirvHeap, glShaderType); + final CacheValue cached; + synchronized (CACHE) { + cached = CACHE.getAndMoveToFirst(key); + } + if (cached != null) { + final ByteBuffer copy = memAlloc(cached.codeBytes.length); + copy.put(cached.codeBytes).flip(); + return new Output(copy, cached.entrypoint); + } + + final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1; + if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType); + + try (MemoryStack stack = stackPush()) { + final PointerBuffer pContext = stack.pointers(0); + if (Spvc.spvc_context_create(pContext) != Spvc.SPVC_SUCCESS) { + throw new RuntimeException("MSL cross-compile failed: spvc_context_create"); + } + final long ctx = pContext.get(0); + try { + final IntBuffer spirvWords = spirv.asIntBuffer(); + final PointerBuffer pParsedIR = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, spirvWords, spirvWords.remaining(), pParsedIR) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "parse_spirv"); + } + + final PointerBuffer pCompiler = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_MSL, pParsedIR.get(0), + Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_compiler(MSL)"); + } + final long compiler = pCompiler.get(0); + + final PointerBuffer pOpts = stack.pointers(0); + if (Spvc.spvc_compiler_create_compiler_options(compiler, pOpts) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_compiler_options"); + } + final long opts = pOpts.get(0); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_MSL_VERSION, mslVersion(2, 2, 0)); + Spvc.spvc_compiler_options_set_uint(opts, Spvc.SPVC_COMPILER_OPTION_MSL_PLATFORM, Spvc.SPVC_MSL_PLATFORM_MACOS); + if (Spvc.spvc_compiler_install_compiler_options(compiler, opts) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "install_compiler_options"); + } + + final PointerBuffer pResources = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(compiler, pResources) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "create_shader_resources"); + } + final long resources = pResources.get(0); + + if (glShaderType == GL43.GL_COMPUTE_SHADER) { + addComputeBindings(compiler, resources, stack); + } else { + addGraphicsBindings(compiler, resources, executionModel, stack); + } + + final PointerBuffer pSrc = stack.pointers(0); + if (Spvc.spvc_compiler_compile(compiler, pSrc) != Spvc.SPVC_SUCCESS) { + throw CrossCompileUtil.spvcError(ctx, BACKEND, "compile"); + } + final String mslSrc = memUTF8(pSrc.get(0)); + if (dumpId >= 0) CrossCompileUtil.dumpText(mslSrc, dumpId, glShaderType, "msl"); + final ByteBuffer code = memUTF8(mslSrc, true); + final String rawEntry = Spvc.spvc_compiler_get_cleansed_entry_point_name(compiler, "main", executionModel); + final String entry = rawEntry != null ? rawEntry : "main0"; + final byte[] codeHeap = new byte[code.remaining()]; + code.duplicate().get(codeHeap); + synchronized (CACHE) { + CACHE.putAndMoveToFirst(key, new CacheValue(codeHeap, entry)); + while (CACHE.size() > CACHE_MAX) CACHE.removeLast(); + } + return new Output(code, entry); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + } + + private static int mslVersion(int major, int minor, int patch) { + return (major * 10000) + (minor * 100) + patch; + } + + private static void addGraphicsBindings(long compiler, long resources, int executionModel, MemoryStack stack) { + final int numUBOs = CrossCompileUtil.countResources(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack); + + addTextureBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, executionModel, stack); + addTextureBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, executionModel, stack); + addTextureBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, executionModel, stack); + + addBufferBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, executionModel, stack, (set, binding) -> binding); + + final int[] ssboIdx = {0}; + addBufferBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, executionModel, stack, (set, binding) -> numUBOs + ssboIdx[0]++); + } + + private static int addTextureBindings(long compiler, long resources, int resourceType, int executionModel, MemoryStack stack) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) { + return 0; + } + final int count = (int) pCount.get(0); + if (count == 0) return 0; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + final SpvcReflectedResource res = list.get(i); + final int spvId = res.id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + + final SpvcMslResourceBinding2 b = SpvcMslResourceBinding2.calloc(stack); + Spvc.spvc_msl_resource_binding_init_2(b); + b.stage(executionModel) + .desc_set(set) + .binding(binding) + .count(1) + .msl_texture(binding) + .msl_sampler(binding); + if (Spvc.spvc_compiler_msl_add_resource_binding_2(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("spvc_compiler_msl_add_resource_binding_2 failed for texture id={} set={} binding={}", spvId, set, binding); + } + } + return count; + } + + private static void addBufferBindings(long compiler, long resources, int resourceType, int executionModel, MemoryStack stack, BufferSlotFn slotFn) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) { + return; + } + final int count = (int) pCount.get(0); + if (count == 0) return; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + final SpvcReflectedResource res = list.get(i); + final int spvId = res.id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + + final SpvcMslResourceBinding2 b = SpvcMslResourceBinding2.calloc(stack); + Spvc.spvc_msl_resource_binding_init_2(b); + b.stage(executionModel) + .desc_set(set) + .binding(binding) + .count(1) + .msl_buffer(slotFn.slot(set, binding)); + if (Spvc.spvc_compiler_msl_add_resource_binding_2(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("spvc_compiler_msl_add_resource_binding_2 failed for buffer id={} set={} binding={}", spvId, set, binding); + } + } + } + + private static void addComputeBindings(long compiler, long resources, MemoryStack stack) { + final int execModel = Spv.SpvExecutionModelGLCompute; + + final int numSamplers = CrossCompileUtil.countResources(resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, stack); + final int[] roRwTex = CrossCompileUtil.countStorageImagesSplit(resources, compiler, stack); + final int[] roRwBuf = CrossCompileUtil.countStorageBuffersSplit(resources, compiler, stack); + final int numROTex = roRwTex[0]; + final int numROBuf = roRwBuf[0]; + final int numRWBuf = roRwBuf[1]; + final int numUBOs = CrossCompileUtil.countResources(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack); + + addComputeTextureBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, execModel, stack, binding -> binding, /*hasSampler*/ true); + addComputeTextureBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, execModel, stack, binding -> binding, false); + + final int auxBufStart = numUBOs + numROBuf + numRWBuf; + addComputeStorageImageBindings(compiler, resources, execModel, stack, + /*roSlot*/ binding -> binding, + /*rwSlot*/ binding -> numSamplers + numROTex + binding, + auxBufStart); + + addComputeBufferBindings(compiler, resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, execModel, stack, (set, binding) -> binding); + + final int[] roSsboIdx = {0}; + final int[] rwSsboIdx = {0}; + addComputeStorageBufferBindings(compiler, resources, execModel, stack, /*roSlot*/ binding -> numUBOs + roSsboIdx[0]++, /*rwSlot*/ binding -> numUBOs + numROBuf + rwSsboIdx[0]++); + } + + private static void addComputeTextureBindings(long compiler, long resources, int resourceType, int executionModel, MemoryStack stack, IntSlotFn slotFn, boolean hasSampler) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int count = (int) pCount.get(0); + if (count == 0) return; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + final SpvcReflectedResource res = list.get(i); + final int spvId = res.id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + final int mslSlot = slotFn.slot(binding); + + final SpvcMslResourceBinding2 b = SpvcMslResourceBinding2.calloc(stack); + Spvc.spvc_msl_resource_binding_init_2(b); + b.stage(executionModel) + .desc_set(set) + .binding(binding) + .count(1) + .msl_texture(mslSlot); + if (hasSampler) b.msl_sampler(mslSlot); + if (Spvc.spvc_compiler_msl_add_resource_binding_2(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("spvc_compiler_msl_add_resource_binding_2 failed for compute texture id={} set={} binding={}", spvId, set, binding); + } + } + } + + private static void addComputeStorageImageBindings(long compiler, long resources, int executionModel, MemoryStack stack, IntSlotFn roSlot, IntSlotFn rwSlot, int auxBufStart) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int count = (int) pCount.get(0); + if (count == 0) return; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + int auxIdx = 0; + for (int i = 0; i < count; i++) { + final SpvcReflectedResource res = list.get(i); + final int spvId = res.id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + final boolean readOnly = Spvc.spvc_compiler_has_decoration(compiler, spvId, Spv.SpvDecorationNonWritable); + final int mslSlot = readOnly ? roSlot.slot(binding) : rwSlot.slot(binding); + + final SpvcMslResourceBinding2 b = SpvcMslResourceBinding2.calloc(stack); + Spvc.spvc_msl_resource_binding_init_2(b); + b.stage(executionModel) + .desc_set(set) + .binding(binding) + .count(1) + .msl_texture(mslSlot) + .msl_buffer(auxBufStart + auxIdx++); + if (Spvc.spvc_compiler_msl_add_resource_binding_2(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("spvc_compiler_msl_add_resource_binding_2 failed for compute storage image id={} set={} binding={} ro={}", spvId, set, binding, readOnly); + } + } + } + + private static void addComputeBufferBindings(long compiler, long resources, int resourceType, int executionModel, MemoryStack stack, BufferSlotFn slotFn) { + addBufferBindings(compiler, resources, resourceType, executionModel, stack, slotFn); + } + + private static void addComputeStorageBufferBindings(long compiler, long resources, int executionModel, MemoryStack stack, IntSlotFn roSlot, IntSlotFn rwSlot) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int count = (int) pCount.get(0); + if (count == 0) return; + + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + final SpvcReflectedResource res = list.get(i); + final int spvId = res.id(); + final int set = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationDescriptorSet); + final int binding = Spvc.spvc_compiler_get_decoration(compiler, spvId, Spv.SpvDecorationBinding); + final boolean readOnly = CrossCompileUtil.isStorageBufferReadOnly(compiler, spvId, stack); + final int mslSlot = readOnly ? roSlot.slot(binding) : rwSlot.slot(binding); + + final SpvcMslResourceBinding2 b = SpvcMslResourceBinding2.calloc(stack); + Spvc.spvc_msl_resource_binding_init_2(b); + b.stage(executionModel) + .desc_set(set) + .binding(binding) + .count(1) + .msl_buffer(mslSlot); + if (Spvc.spvc_compiler_msl_add_resource_binding_2(compiler, b) != Spvc.SPVC_SUCCESS) { + LOG.warn("spvc_compiler_msl_add_resource_binding_2 failed for compute storage buffer id={} set={} binding={} ro={}", spvId, set, binding, readOnly); + } + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashDispatcher.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashDispatcher.java new file mode 100644 index 000000000..1cd23e125 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashDispatcher.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.sdlgpu.splash; + +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; + +public final class SplashDispatcher { + + private static volatile boolean frameReady; + private static volatile long drawnSize; + private static long lastBlitNanos; + private static final long MIN_INTERVAL_NS = 16_000_000L; + + private SplashDispatcher() {} + + public static void seedDrawnSize(int w, int h) { + drawnSize = pack(w, h); + } + + public static void signalFrameReady(int w, int h) { + drawnSize = pack(w, h); + frameReady = true; + } + + public static void signalFrameReady() { + frameReady = true; + } + + public static long getDrawnSize() { + return drawnSize; + } + + private static long pack(int w, int h) { + return (long) w << 32 | (h & 0xffffffffL); + } + + public static void tryDispatch(SDLGPURenderBackend backend, SplashOffscreenTarget target) { + if (!frameReady || target == null) return; + final long now = System.nanoTime(); + if (now - lastBlitNanos < MIN_INTERVAL_NS) return; + lastBlitNanos = now; + frameReady = false; + backend.dispatchSplashBlit(target); + } + + public static void reset() { + frameReady = false; + drawnSize = 0; + lastBlitNanos = 0; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashOffscreenTarget.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashOffscreenTarget.java new file mode 100644 index 000000000..ad1ff9925 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/splash/SplashOffscreenTarget.java @@ -0,0 +1,60 @@ +package com.gtnewhorizons.angelica.sdlgpu.splash; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.FboState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import org.lwjgl.opengl.GL11; + +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_SAMPLER; + +public final class SplashOffscreenTarget { + + private int fboGlId; + private int colorTexGlId; + private long colorTexHandle; + private int width; + private int height; + + public void create(Device device, ResourceManager rm, int width, int height, int swapchainSdlFormat) { + this.width = width; + this.height = height; + + this.colorTexGlId = rm.genTexture(); + this.colorTexHandle = rm.createTextureWithSdlFormat(colorTexGlId, GL11.GL_TEXTURE_2D, swapchainSdlFormat, GL11.GL_RGBA8, width, height, 1, 1, SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET); + + this.fboGlId = rm.genFboId(); + final FboState fbo = rm.createFbo(fboGlId); + fbo.colorTextures[0] = colorTexHandle; + fbo.colorGlIds[0] = colorTexGlId; + fbo.colorFormats[0] = swapchainSdlFormat; + fbo.colorAttachmentCount = 1; + fbo.drawBuffers = new int[]{0}; + fbo.width = width; + fbo.height = height; + fbo.targetsDirty = true; + fbo.cachedFormatsDirty = true; + } + + public int fboId() { return fboGlId; } + public long colorTexture() { return colorTexHandle; } + public int width() { return width; } + public int height() { return height; } + + public boolean isFor(ContextState st) { + return fboGlId != 0 && st.boundFboId == fboGlId; + } + + public void destroy(ResourceManager rm) { + if (fboGlId != 0) { + rm.deleteFbo(fboGlId); + fboGlId = 0; + } + if (colorTexGlId != 0) { + rm.deleteTexture(colorTexGlId); + colorTexGlId = 0; + colorTexHandle = 0; + } + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugLabels.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugLabels.java new file mode 100644 index 000000000..71455c610 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugLabels.java @@ -0,0 +1,101 @@ +package com.gtnewhorizons.angelica.sdlgpu.util; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import org.lwjgl.opengl.KHRDebug; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.lwjgl.sdl.SDLGPU.*; + +public final class DebugLabels { + private final FrameManager frameManager; + private final boolean enabled; + private Int2ObjectOpenHashMap programLabels; + private Int2ObjectOpenHashMap programLabelEncoded; + + public DebugLabels(FrameManager frameManager, boolean enabled) { + this.frameManager = frameManager; + this.enabled = enabled; + } + + public boolean isEnabled() { return enabled; } + + public void objectLabel(int identifier, int name, CharSequence label) { + if (!enabled || label == null) return; + if (identifier == KHRDebug.GL_PROGRAM) { + if (programLabels == null) programLabels = new Int2ObjectOpenHashMap<>(); + programLabels.put(name, label.toString()); + if (programLabelEncoded != null) { + final ByteBuffer prev = programLabelEncoded.remove(name); + if (prev != null) MemoryUtil.memFree(prev); + } + } + } + + public void pushDebugGroup(CharSequence message) { + if (!enabled || message == null) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + SDL_PushGPUDebugGroup(cb, message); + } + + public void popDebugGroup() { + if (!enabled) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + SDL_PopGPUDebugGroup(cb); + } + + public void debugMessageInsert(CharSequence message) { + if (!enabled || message == null) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + SDL_InsertGPUDebugLabel(cb, message); + } + + public void onProgramDeleted(int program) { + if (programLabelEncoded == null) return; + final ByteBuffer enc = programLabelEncoded.remove(program); + if (enc != null) MemoryUtil.memFree(enc); + } + + public void updateAutoDebugGroup(ContextState st, int newProgram) { + if (!enabled) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) return; + if (st.autoPushedProgram != 0) { + SDL_PopGPUDebugGroup(cb); + st.autoPushedProgram = 0; + } + if (newProgram != 0) { + final ByteBuffer encoded = encodedProgramLabel(newProgram); + nSDL_PushGPUDebugGroup(cb, MemoryUtil.memAddress(encoded)); + st.autoPushedProgram = newProgram; + } + } + + public void popAutoDebugGroup(ContextState st) { + if (st.autoPushedProgram == 0) return; + final long cb = frameManager.getCommandBuffer(); + if (cb == 0) { + st.autoPushedProgram = 0; + return; + } + SDL_PopGPUDebugGroup(cb); + st.autoPushedProgram = 0; + } + + private ByteBuffer encodedProgramLabel(int program) { + if (programLabelEncoded == null) programLabelEncoded = new Int2ObjectOpenHashMap<>(); + ByteBuffer cached = programLabelEncoded.get(program); + if (cached != null) return cached; + final String label = programLabels == null ? null : programLabels.get(program); + final String groupName = label != null ? label : ("program " + program); + cached = MemoryUtil.memUTF8(groupName, true); + programLabelEncoded.put(program, cached); + return cached; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelay.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelay.java new file mode 100644 index 000000000..a368cb931 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelay.java @@ -0,0 +1,97 @@ +package com.gtnewhorizons.angelica.sdlgpu.util; + +import java.nio.charset.StandardCharsets; +import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.KHRDebug; +import org.lwjgl.sdl.SDLLog; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +/** Presents SDL's validation output as a GL debug message stream. */ +public final class DebugMessageRelay { + + private static final Logger LOG = LogManager.getLogger("SDLGPU"); + private static final int RING_CAPACITY = 64; + + private static volatile GLDebugMessageListener listener; + private static volatile long listenerUserParam; + private static boolean warnedNoValidationLayer; + + private static final String[] ringMessages = new String[RING_CAPACITY]; + private static final int[] ringSeverities = new int[RING_CAPACITY]; + private static int ringHead; + private static int ringCount; + + private DebugMessageRelay() {} + + public static void setListener(GLDebugMessageListener newListener, long userParam, boolean validationLayerActive) { + listener = newListener; + listenerUserParam = userParam; + if (newListener != null && !validationLayerActive && !warnedNoValidationLayer) { + warnedNoValidationLayer = true; + LOG.warn("A GL debug message callback was registered, but the SDL validation layer is off so no driver messages exist to deliver. Run with -Dorg.lwjgl.util.Debug=true (or -Dangelica.sdlgpu.debug=true) to enable it. Labels and debug groups are unaffected."); + } + } + + public static void onSdlMessage(int priority, long message) { + final GLDebugMessageListener target = listener; + final int severity = mapSeverity(priority); + final int type = severity == KHRDebug.GL_DEBUG_SEVERITY_HIGH ? KHRDebug.GL_DEBUG_TYPE_ERROR : KHRDebug.GL_DEBUG_TYPE_OTHER; + + record(severity, message); + + if (target == null) return; + final int length = MemoryUtil.memByteBufferNT1(message).remaining(); + try { + target.onMessage(KHRDebug.GL_DEBUG_SOURCE_API, type, 0, severity, length, message, listenerUserParam); + } catch (Throwable t) { + LOG.warn("GL debug message callback threw", t); + } + } + + private static int mapSeverity(int priority) { + return switch (priority) { + case SDLLog.SDL_LOG_PRIORITY_ERROR, SDLLog.SDL_LOG_PRIORITY_CRITICAL -> KHRDebug.GL_DEBUG_SEVERITY_HIGH; + case SDLLog.SDL_LOG_PRIORITY_WARN -> KHRDebug.GL_DEBUG_SEVERITY_MEDIUM; + case SDLLog.SDL_LOG_PRIORITY_INFO -> KHRDebug.GL_DEBUG_SEVERITY_LOW; + default -> KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION; + }; + } + + private static synchronized void record(int severity, long message) { + ringMessages[ringHead] = MemoryUtil.memUTF8(message); + ringSeverities[ringHead] = severity; + ringHead = (ringHead + 1) % RING_CAPACITY; + if (ringCount < RING_CAPACITY) ringCount++; + } + + public static synchronized int drain(int count, IntBuffer sources, IntBuffer types, IntBuffer ids, + IntBuffer severities, IntBuffer lengths, ByteBuffer messageLog) { + int written = 0; + while (written < count && ringCount > 0) { + final int tail = (ringHead - ringCount + RING_CAPACITY) % RING_CAPACITY; + final byte[] utf8 = ringMessages[tail].getBytes(StandardCharsets.UTF_8); + final int needed = utf8.length + 1; // GL counts the NUL terminator in `lengths` + if (messageLog != null && messageLog.remaining() < needed) break; + + if (messageLog != null) { + messageLog.put(utf8).put((byte) 0); + } + final int severity = ringSeverities[tail]; + if (sources != null) sources.put(KHRDebug.GL_DEBUG_SOURCE_API); + if (types != null) types.put(severity == KHRDebug.GL_DEBUG_SEVERITY_HIGH ? KHRDebug.GL_DEBUG_TYPE_ERROR : KHRDebug.GL_DEBUG_TYPE_OTHER); + if (ids != null) ids.put(0); + if (severities != null) severities.put(severity); + if (lengths != null) lengths.put(needed); + + ringMessages[tail] = null; + ringCount--; + written++; + } + return written; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/MemoryAccess.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/MemoryAccess.java new file mode 100644 index 000000000..8f4d424bd --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/util/MemoryAccess.java @@ -0,0 +1,129 @@ +package com.gtnewhorizons.angelica.sdlgpu.util; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.system.MemoryUtil; + +@SuppressWarnings("all") +public final class MemoryAccess { + + private static final Logger LOG = LogManager.getLogger("Angelica-MemoryAccess"); + private static final boolean USE_UNSAFE; + private static final sun.misc.Unsafe UNSAFE; + private static final long FLOAT_ARRAY_BASE_OFFSET; + + static { + sun.misc.Unsafe u = null; + try { + var f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + u = (sun.misc.Unsafe) f.get(null); + } catch (Throwable ignored) {} + UNSAFE = u; + FLOAT_ARRAY_BASE_OFFSET = (u != null) ? u.arrayBaseOffset(float[].class) : 0L; + + boolean canUse; + int javaVersion = Runtime.version().feature(); + if (javaVersion < 26) { + canUse = u != null; + } else { + canUse = u != null && probeUnsafeMemoryAccess(u); + } + USE_UNSAFE = canUse; + LOG.info("MemoryAccess: Java {}, using {} path", javaVersion, USE_UNSAFE ? "Unsafe (GTNHLib)" : "VarHandle (LWJGL3 fallback)"); + } + + private static boolean probeUnsafeMemoryAccess(sun.misc.Unsafe unsafe) { + try { + long probe = MemoryUtil.nmemAlloc(8); + try { + unsafe.putLong(probe, 0L); + unsafe.getLong(probe); + return true; + } finally { + MemoryUtil.nmemFree(probe); + } + } catch (Throwable t) { + LOG.warn("Unsafe memory access not available, falling back to VarHandle: {}", t.getMessage()); + return false; + } + } + + public static boolean isUsingUnsafe() { return USE_UNSAFE; } + + public static byte getByte(long p) { + return USE_UNSAFE ? GTNHUnsafe.getByte(p) : MemoryUtil.memGetByte(p); + } + + public static short getShort(long p) { + return USE_UNSAFE ? GTNHUnsafe.getShort(p) : MemoryUtil.memGetShort(p); + } + + public static int getInt(long p) { + return USE_UNSAFE ? GTNHUnsafe.getInt(p) : MemoryUtil.memGetInt(p); + } + + public static float getFloat(long p) { + return USE_UNSAFE ? GTNHUnsafe.getFloat(p) : MemoryUtil.memGetFloat(p); + } + + public static long getLong(long p) { + return USE_UNSAFE ? GTNHUnsafe.getLong(p) : MemoryUtil.memGetLong(p); + } + + public static long getAddress(long p) { + return USE_UNSAFE ? GTNHUnsafe.getAddress(p) : MemoryUtil.memGetAddress(p); + } + + public static void putByte(long p, byte v) { + if (USE_UNSAFE) GTNHUnsafe.putByte(p, v); else MemoryUtil.memPutByte(p, v); + } + + public static void putShort(long p, short v) { + if (USE_UNSAFE) GTNHUnsafe.putShort(p, v); else MemoryUtil.memPutShort(p, v); + } + + public static void putInt(long p, int v) { + if (USE_UNSAFE) GTNHUnsafe.putInt(p, v); else MemoryUtil.memPutInt(p, v); + } + + public static void putFloat(long p, float v) { + if (USE_UNSAFE) GTNHUnsafe.putFloat(p, v); else MemoryUtil.memPutFloat(p, v); + } + + public static void putLong(long p, long v) { + if (USE_UNSAFE) GTNHUnsafe.putLong(p, v); else MemoryUtil.memPutLong(p, v); + } + + public static void putAddress(long p, long v) { + if (USE_UNSAFE) GTNHUnsafe.putAddress(p, v); else MemoryUtil.memPutAddress(p, v); + } + + public static void copyFloatsToAddr(float[] src, int srcOff, long dstAddr, int floats) { + if (floats <= 0) return; + if (USE_UNSAFE) { + UNSAFE.copyMemory(src, FLOAT_ARRAY_BASE_OFFSET + ((long) srcOff) * 4L, + null, dstAddr, ((long) floats) * 4L); + } else { + for (int i = 0; i < floats; i++) { + MemoryUtil.memPutFloat(dstAddr + ((long) i) * 4L, src[srcOff + i]); + } + } + } + + private static final class GTNHUnsafe { + public static byte getByte(long p) { return MemoryUtilities.memGetByte(p); } + public static short getShort(long p) { return MemoryUtilities.memGetShort(p); } + public static int getInt(long p) { return MemoryUtilities.memGetInt(p); } + public static float getFloat(long p) { return MemoryUtilities.memGetFloat(p); } + public static long getLong(long p) { return MemoryUtilities.memGetLong(p); } + public static long getAddress(long p) { return MemoryUtilities.memGetAddress(p); } + public static void putByte(long p, byte v) { MemoryUtilities.memPutByte(p, v); } + public static void putShort(long p, short v) { MemoryUtilities.memPutShort(p, v); } + public static void putInt(long p, int v) { MemoryUtilities.memPutInt(p, v); } + public static void putFloat(long p, float v) { MemoryUtilities.memPutFloat(p, v); } + public static void putLong(long p, long v) { MemoryUtilities.memPutLong(p, v); } + public static void putAddress(long p, long v) { MemoryUtilities.memPutAddress(p, v); } + } +} diff --git a/sdl-gpu/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.backend.RenderBackend b/sdl-gpu/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.backend.RenderBackend new file mode 100644 index 000000000..988642f36 --- /dev/null +++ b/sdl-gpu/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.backend.RenderBackend @@ -0,0 +1 @@ +com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend diff --git a/sdl-gpu/src/main/resources/META-INF/services/com.mitchej123.lwjgl.LWJGLService b/sdl-gpu/src/main/resources/META-INF/services/com.mitchej123.lwjgl.LWJGLService new file mode 100644 index 000000000..5b37d99b4 --- /dev/null +++ b/sdl-gpu/src/main/resources/META-INF/services/com.mitchej123.lwjgl.LWJGLService @@ -0,0 +1 @@ +com.gtnewhorizons.angelica.sdlgpu.SDLGPULWJGLService diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageAccessUsageMappingTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageAccessUsageMappingTest.java new file mode 100644 index 000000000..ed89374fa --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageAccessUsageMappingTest.java @@ -0,0 +1,38 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL15; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE; + +class ImageAccessUsageMappingTest { + + @Test + void readOnlyRequestsOnlyStorageRead() { + assertEquals(SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ, SDLGPURenderBackend.imageUsageForAccess(GL15.GL_READ_ONLY)); + } + + @Test + void writeOnlyRequestsOnlyStorageWrite() { + assertEquals(SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE, SDLGPURenderBackend.imageUsageForAccess(GL15.GL_WRITE_ONLY)); + } + + @Test + void readWriteRequestsOnlyStorageWrite() { + assertEquals(SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE, SDLGPURenderBackend.imageUsageForAccess(GL15.GL_READ_WRITE)); + } + + @Test + void noAccessModeRequestsBothStorageBits() { + final int both = SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE; + for (int access : new int[] { GL15.GL_READ_ONLY, GL15.GL_WRITE_ONLY, GL15.GL_READ_WRITE }) { + final int usage = SDLGPURenderBackend.imageUsageForAccess(access); + assertEquals(0, usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE); + assertNotEquals(both, usage & both, "READ|WRITE together leaves SDL's DefaultTextureUsageMode ambiguous on a sampled texture"); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageUnitBindingStateTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageUnitBindingStateTest.java new file mode 100644 index 000000000..e3e1954d0 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/ImageUnitBindingStateTest.java @@ -0,0 +1,67 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL42; + +import java.lang.reflect.Field; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ImageUnitBindingStateTest { + + @SuppressWarnings("unchecked") + private static ContextState state() throws Exception { + final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState"); + f.setAccessible(true); + return ((ThreadLocal) f.get(null)).get(); + } + + @Test + void bindImageTextureRecordsTheFullTuple() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.bindImageTexture(2, 77, 3, true, 5, GL15.GL_READ_WRITE, GL30.GL_R32UI); + + assertEquals(77, st.boundStorageTextureByUnit[2]); + assertEquals(3, st.boundStorageTextureLevel[2]); + assertTrue(st.boundStorageTextureLayered[2]); + assertEquals(5, st.boundStorageTextureLayer[2]); + assertEquals(GL15.GL_READ_WRITE, st.boundStorageTextureAccess[2]); + assertEquals(GL30.GL_R32UI, st.boundStorageTextureFormat[2]); + } + + @Test + void getIntegerIndexedAnswersImageBindingsFromState() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + + backend.bindImageTexture(1, 42, 2, false, 4, GL15.GL_READ_ONLY, GL30.GL_RGBA32UI); + + assertEquals(42, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_NAME, 1)); + assertEquals(2, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_LEVEL, 1)); + assertEquals(GL11.GL_FALSE, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_LAYERED, 1)); + assertEquals(4, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_LAYER, 1)); + assertEquals(GL15.GL_READ_ONLY, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_ACCESS, 1)); + assertEquals(GL30.GL_RGBA32UI, backend.getIntegerIndexed(GL42.GL_IMAGE_BINDING_FORMAT, 1)); + } + + @Test + void outOfRangeUnitIsIgnored() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.bindImageTexture(0, 11, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + backend.bindImageTexture(ContextState.MAX_IMAGE_UNITS, 99, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI); + + assertEquals(11, st.boundStorageTextureByUnit[0], "an out-of-range unit must not disturb a valid one"); + for (int i = 0; i < ContextState.MAX_IMAGE_UNITS; i++) { + assertFalse(st.boundStorageTextureByUnit[i] == 99, "unit " + i + " took an out-of-range bind"); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUBufferQueryTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUBufferQueryTest.java new file mode 100644 index 000000000..dd63c5bd1 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPUBufferQueryTest.java @@ -0,0 +1,70 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SDLGPUBufferQueryTest { + + @Test + void fbo0IsTheSwapchainAndReadsAsBack() { + assertEquals(GL11.GL_BACK, SDLGPURenderBackend.bufferEnum(0, 0)); + assertEquals(GL11.GL_BACK, SDLGPURenderBackend.bufferEnum(0, 3), "FBO 0 has no configurable draw buffer"); + assertEquals(GL11.GL_BACK, SDLGPURenderBackend.bufferEnum(0, -1)); + } + + @Test + void boundFboReadsAsItsColourAttachment() { + assertEquals(GL30.GL_COLOR_ATTACHMENT0, SDLGPURenderBackend.bufferEnum(7, 0)); + assertEquals(GL30.GL_COLOR_ATTACHMENT0 + 3, SDLGPURenderBackend.bufferEnum(7, 3)); + } + + @Test + void emptyDrawBufferListReadsAsNone() { + assertEquals(GL11.GL_NONE, SDLGPURenderBackend.bufferEnum(7, -1)); + } + + @Test + void defaultMatchesGLStateManagerDeclaredDefault() { + assertEquals(0x405, SDLGPURenderBackend.bufferEnum(0, 0)); + } + + @Test + void boundTextureReadsTheActiveUnitsSlot() { + final int[] bound = {11, 22, 33, 44}; + assertEquals(11, SDLGPURenderBackend.boundTextureOf(0, bound)); + assertEquals(44, SDLGPURenderBackend.boundTextureOf(3, bound)); + } + + @Test + void outOfRangeUnitReadsZero() { + final int[] bound = {11, 22}; + assertEquals(0, SDLGPURenderBackend.boundTextureOf(-1, bound)); + assertEquals(0, SDLGPURenderBackend.boundTextureOf(2, bound)); + assertEquals(0, SDLGPURenderBackend.boundTextureOf(-33984, bound)); + assertEquals(0, SDLGPURenderBackend.boundTextureOf(0, new int[0])); + } + + @Test + void deviceLimitsAreAnswered() { + assertEquals(1024, SDLGPURenderBackend.deviceLimit(GL20.GL_MAX_VERTEX_UNIFORM_COMPONENTS)); + assertEquals(1024, SDLGPURenderBackend.deviceLimit(GL20.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS)); + assertEquals(256, SDLGPURenderBackend.deviceLimit(GL30.GL_MAX_ARRAY_TEXTURE_LAYERS)); + } + + @Test + void uniformLimitFitsSdlsUboSection() { + assertTrue(SDLGPURenderBackend.deviceLimit(GL20.GL_MAX_VERTEX_UNIFORM_COMPONENTS) * 4 <= 4096); + assertTrue(SDLGPURenderBackend.deviceLimit(GL30.GL_MAX_ARRAY_TEXTURE_LAYERS) <= 256); + } + + @Test + void nonLimitPnamesAreNotClaimed() { + assertEquals(-1, SDLGPURenderBackend.deviceLimit(GL11.GL_DRAW_BUFFER)); + assertEquals(-1, SDLGPURenderBackend.deviceLimit(0x1234)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SdlTestRig.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SdlTestRig.java new file mode 100644 index 000000000..08a867864 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/SdlTestRig.java @@ -0,0 +1,81 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDLInit; + +import java.lang.reflect.Field; + +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.lwjgl.sdl.SDLGPU.SDL_CreateGPUDevice; +import static org.lwjgl.sdl.SDLGPU.SDL_DestroyGPUDevice; +import static org.lwjgl.sdl.SDLGPU.SDL_GetGPUShaderFormats; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERFORMAT_DXBC; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERFORMAT_DXIL; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERFORMAT_MSL; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERFORMAT_SPIRV; +import static org.lwjgl.sdl.SDLGPU.SDL_WaitForGPUIdle; +import static org.lwjgl.sdl.SDLInit.SDL_INIT_VIDEO; + +public final class SdlTestRig { + + public final Device device; + public final FrameManager frameManager; + public final ResourceManager resourceManager; + public final long sdlHandle; + + private SdlTestRig(long sdlHandle) throws ReflectiveOperationException { + this.sdlHandle = sdlHandle; + this.device = new Device(); + if (sdlHandle != 0L) { + final Field deviceField = Device.class.getDeclaredField("device"); + deviceField.setAccessible(true); + deviceField.setLong(this.device, sdlHandle); + final Field formatsField = Device.class.getDeclaredField("supportedShaderFormats"); + formatsField.setAccessible(true); + formatsField.setInt(this.device, SDL_GetGPUShaderFormats(sdlHandle)); + } + this.frameManager = new FrameManager(device); + this.resourceManager = new ResourceManager(device, frameManager); + } + + public static SdlTestRig create() { + try { + return new SdlTestRig(0L); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + public static ResourceManager resourceManager() { + return create().resourceManager; + } + + public static FrameManager frameManager() { + return create().frameManager; + } + + private static long realSdlDevice; + + private static final int SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL; + + public static SdlTestRig acquireRealDevice() throws ReflectiveOperationException { + assumeTrue(SDLInit.SDL_Init(SDL_INIT_VIDEO), "SDL_Init failed: " + SDLError.SDL_GetError()); + realSdlDevice = SDL_CreateGPUDevice(SHADER_FORMATS, true, (CharSequence) null); + assumeTrue(realSdlDevice != 0, "No SDL GPU device: " + SDLError.SDL_GetError()); + + final SdlTestRig rig = new SdlTestRig(realSdlDevice); + rig.frameManager.setResourceManager(rig.resourceManager); + return rig; + } + + public static void releaseRealDevice() { + if (realSdlDevice != 0) { + SDL_WaitForGPUIdle(realSdlDevice); + SDL_DestroyGPUDevice(realSdlDevice); + realSdlDevice = 0; + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/UniformNegativeLocationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/UniformNegativeLocationTest.java new file mode 100644 index 000000000..c105a439e --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/UniformNegativeLocationTest.java @@ -0,0 +1,125 @@ +package com.gtnewhorizons.angelica.sdlgpu; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineApplier; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.UniformStaging; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.lang.reflect.Field; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UniformNegativeLocationTest { + + private PipelineApplier applier; + private ContextState st; + private ShaderManager.ProgramObject prog; + private UniformStaging us; + + @BeforeEach + void setUp() { + applier = new PipelineApplier(null, null, null, null, null, null, null, null, null); + st = new ContextState(); + prog = new ShaderManager.ProgramObject(); + prog.linked = true; + prog.vertexUboSize = 128; + prog.nextUniformLocation = 2; + prog.vertexMemberInfo.put(0, new ShaderManager.UniformMemberInfo(0, 64, 0, true, 4, 4, 0, 1)); + prog.vertexMemberInfo.put(1, new ShaderManager.UniformMemberInfo(64, 16, 0, true, 4, 1, 0, 1)); + prog.buildUniformSlotArrays(); + st.boundProgramObj = prog; + st.boundProgram = 1; + us = st.uniformStaging(prog); + } + + @AfterEach + void tearDown() { + st.releaseUniformStaging(prog); + } + + @SuppressWarnings("unchecked") + private static ContextState threadState() throws Exception { + final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState"); + f.setAccessible(true); + return ((ThreadLocal) f.get(null)).get(); + } + + private static void clearApplier(SDLGPURenderBackend backend) throws Exception { + final Field f = SDLGPURenderBackend.class.getDeclaredField("pipelineApplier"); + f.setAccessible(true); + f.set(backend, null); + assertNull(f.get(backend), "test rig failed to null the applier"); + } + + @Test + void scalarAndVectorEntryPointsNeverReachTheApplier() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + clearApplier(backend); + threadState().boundProgramObj = null; + + final IntBuffer iv = MemoryUtil.memAllocInt(4); + try { + iv.put(0, 1).put(1, 2).put(2, 3).put(3, 4); + assertDoesNotThrow(() -> { + backend.uniform1i(-1, 0); + backend.uniform1f(-1, 1f); + backend.uniform2f(-1, 1f, 2f); + backend.uniform2i(-1, 1, 2); + backend.uniform3f(-1, 1f, 2f, 3f); + backend.uniform3i(-1, 1, 2, 3); + backend.uniform4f(-1, 1f, 2f, 3f, 4f); + backend.uniform4i(-1, 1, 2, 3, 4); + backend.uniform1iv(-1, iv); + backend.uniform2iv(-1, iv); + backend.uniform3iv(-1, iv); + backend.uniform4iv(-1, iv); + }); + assertThrows(NullPointerException.class, () -> backend.uniform4f(0, 1f, 2f, 3f, 4f), "a valid location must still reach the applier, or the -1 assertions prove nothing"); + } finally { + MemoryUtil.memFree(iv); + } + } + + @Test + void negativeLocationLeavesStagingAndSourceBufferUntouched() { + final FloatBuffer fb = MemoryUtil.memAllocFloat(16); + try { + for (int i = 0; i < 16; i++) fb.put(i, i + 1f); + + applier.storeMatrix(st, -1, false, fb, 4); + applier.storeMatrix(st, -1, false, fb, 3); + applier.storeMatrix(st, -1, true, fb, 2); + applier.putUniformFv(st, -1, fb); + applier.putUniform(st, -1, new float[]{1f, 2f, 3f, 4f}); + + assertFalse(us.vsUniformDirty); + assertFalse(us.fsUniformDirty); + for (int slot = 0; slot < prog.uniformSlotCount; slot++) { + assertNull(us.uniformDataBySlot[slot], "slot " + slot + " was staged"); + assertEquals(0L, us.uniformValueHashBySlot[slot], "slot " + slot + " hash was written"); + } + for (ContextState.UniformBlockState block : st.uniformBlocks) { + assertFalse(block.dirty); + } + assertEquals(0, fb.position()); + assertEquals(16, fb.limit()); + + applier.storeMatrix(st, 0, false, fb, 4); + assertTrue(us.vsUniformDirty, "location 0 must still write, or the -1 assertions prove nothing"); + assertEquals(1f, us.vsUniformFb.get(0)); + } finally { + MemoryUtil.memFree(fb); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShimTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShimTest.java new file mode 100644 index 000000000..056b5de68 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compat/Lwjgl3GLCapabilitiesShimTest.java @@ -0,0 +1,120 @@ +package com.gtnewhorizons.angelica.sdlgpu.compat; + +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GLCapabilities; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class Lwjgl3GLCapabilitiesShimTest { + + private static boolean flag(GLCapabilities caps, String name) throws ReflectiveOperationException { + final Field f = GLCapabilities.class.getField(name); + return (boolean) f.get(caps); + } + + @Test + void constructsFromTheAdvertisedSet() { + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(SDLGPURenderBackend.advertisedCapabilities()); + assertTrue(caps.forwardCompatible, "SDL reports Core Profile Equivalent, so forwardCompatible must be true"); + } + + @Test + void everyAdvertisedVersionFlagIsTrue() throws ReflectiveOperationException { + final Set advertised = SDLGPURenderBackend.advertisedCapabilities(); + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(advertised); + + final Set missing = new TreeSet<>(); + for (String name : advertised) { + if (name.startsWith("OpenGL") && !flag(caps, name)) missing.add(name); + } + assertTrue(missing.isEmpty(), () -> "advertised but reported unsupported: " + missing); + } + + @Test + void advertises46() throws ReflectiveOperationException { + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(SDLGPURenderBackend.advertisedCapabilities()); + assertTrue(flag(caps, "OpenGL46"), "getString(GL_VERSION) and GL_MAJOR/MINOR_VERSION already claim 4.6; the capability view must agree"); + } + + @Test + void everyAdvertisedExtensionFlagIsTrue() throws ReflectiveOperationException { + final Set advertised = SDLGPURenderBackend.advertisedCapabilities(); + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(advertised); + + final Set missing = new TreeSet<>(); + for (String name : advertised) { + if (name.startsWith("GL_") && !flag(caps, name)) missing.add(name); + } + assertTrue(missing.isEmpty(), () -> "advertised but reported unsupported: " + missing); + } + + @Test + void unadvertisedExtensionIsFalse() throws ReflectiveOperationException { + final Set advertised = SDLGPURenderBackend.advertisedCapabilities(); + assertFalse(advertised.contains("GL_ARB_bindless_texture"), "test fixture assumption"); + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(advertised); + assertFalse(flag(caps, "GL_ARB_bindless_texture"), "capabilities must not be fabricated wholesale"); + } + + @Test + void advertisedSetIsTheOnlyVersionSource() throws ReflectiveOperationException { + final Set advertised = SDLGPURenderBackend.advertisedCapabilities(); + final GLCapabilities caps = Lwjgl3GLCapabilitiesShim.create(advertised); + + final Set fromSet = new TreeSet<>(); + for (String name : advertised) if (name.startsWith("OpenGL")) fromSet.add(name); + + final Set fromCaps = new TreeSet<>(); + for (Field f : GLCapabilities.class.getFields()) { + if (f.getName().startsWith("OpenGL") && f.getType() == boolean.class && (boolean) f.get(caps)) { + fromCaps.add(f.getName()); + } + } + assertEquals(fromSet, fromCaps); + } + + @Test + void installIsPerThreadAndClearable() throws Exception { + Lwjgl3GLCapabilitiesShim.installOnCurrentThread(SDLGPURenderBackend.advertisedCapabilities()); + try { + assertNotNull(GL.getCapabilities()); + + final AtomicReference onOtherThread = new AtomicReference<>(); + final Thread other = new Thread(() -> { + try { + GL.getCapabilities(); + } catch (Throwable t) { + onOtherThread.set(t); + } + }, "no-context-thread"); + other.start(); + other.join(); + assertInstanceOf(IllegalStateException.class, onOtherThread.get(), "a thread that does not own the context must not look like the render thread"); + } finally { + Lwjgl3GLCapabilitiesShim.clearOnCurrentThread(); + } + assertThrows(IllegalStateException.class, GL::getCapabilities, "clearing on release must stop the thread answering yes to runningOnRenderThread()"); + } + + @Test + void advertisedSetHasNoDuplicatesOrBlanks() { + final Set advertised = SDLGPURenderBackend.advertisedCapabilities(); + assertEquals(new HashSet<>(advertised).size(), advertised.size()); + for (String name : advertised) { + assertTrue(name.startsWith("OpenGL") || name.startsWith("GL_"), () -> "malformed capability name: " + name); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ChunkCullSpirvCompileTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ChunkCullSpirvCompileTest.java new file mode 100644 index 000000000..e02d6d07e --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ChunkCullSpirvCompileTest.java @@ -0,0 +1,47 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ChunkCullSpirvCompileTest { + + private static final String SHADER = "chunk_cull.csh"; + + private static String source() { + return TestPaths.readString("src/main/resources/assets/angelica/shaders/culling/" + SHADER); + } + + @Test + void chunkCullReflectsExpectedBindings() { + final SpirvCompiler.Result r = SpirvCompiler.compile(source(), Shaderc.shaderc_compute_shader, SHADER, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) fail(SHADER + " failed to compile: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + final ShaderManager.ComputeBindingMap map = ShaderManager.remapSpirvForComputeSDLGPU(spirv); + assertEquals(0, map.samplerGlSlots().length, "the frustum cull samples no textures"); + assertEquals(1, map.uboGlSlots().length, "Frustum UBO"); + assertEquals(0, map.uboGlSlots()[0], "Frustum UBO is at binding 0"); + assertEquals(160, map.uboSizes()[0], "Frustum UBO is 160 bytes"); + assertEquals(3, map.roSsboGlSlots().length + map.rwSsboGlSlots().length, "visible + meta + indirect"); + assertTrue(IntStream.concat(Arrays.stream(map.roSsboGlSlots()), Arrays.stream(map.rwSsboGlSlots())).allMatch(s -> s >= 0 && s < 8), "a storage binding outside 0..7 exceeds the GL 4.3 guaranteed minimum"); + assertEquals(0, map.roStorageTextureFormats().length, "declares no images"); + assertEquals(0, map.rwStorageTextureFormats().length, "declares no images"); + assertEquals(0, map.roStorageTextureTargets().length, "declares no images"); + assertEquals(0, map.rwStorageTextureTargets().length, "declares no images"); + } finally { + MemoryUtil.memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBatchJoinTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBatchJoinTest.java new file mode 100644 index 000000000..5b07475d2 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBatchJoinTest.java @@ -0,0 +1,66 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.SdlReflect; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ComputeBatchJoinTest { + + private static final int RGBA8 = InternalTextureFormat.RGBA8.getGlFormat(); + private static final long STAND_IN_RW = 0x515A_0001L; + + private ResourceManager rm; + private ComputeBinder binder; + private ContextState st; + private ShaderManager.ProgramObject prog; + + @BeforeEach + void setUp() { + rm = SdlTestRig.resourceManager(); + SdlReflect.putComputeStandIn(rm, RGBA8, GL11.GL_TEXTURE_2D, true, STAND_IN_RW); + binder = new ComputeBinder(null, rm, null, null); + st = new ContextState(); + st.boundProgram = 1; + st.computeBatchProgram = 1; + prog = new ShaderManager.ProgramObject(); + prog.linked = true; + prog.sdlComputePipeline = 0x9001L; + prog.computeBindingMap = new ShaderManager.ComputeBindingMap( + new int[0], new int[0], new int[] { 0 }, new int[0], new int[0], new int[0], + new String[0], new String[0], new String[1], + new boolean[0], new int[0], + new int[0], new int[] { RGBA8 }, new int[0], new int[] { GL11.GL_TEXTURE_2D }); + } + + @Test + void substitutedRwImageStillJoinsItsOwnBatch() { + snapshot(); + assertTrue(canJoin(), "the second dispatch resolves the same stand-in the snapshot recorded"); + } + + @Test + void realBindingAppearingAfterSnapshotBreaksTheBatch() { + snapshot(); + SdlReflect.putTextureHandle(rm, 77, 0xBEEF_0077L); + st.boundStorageTextureByUnit[0] = 77; + assertFalse(canJoin(), "a real texture is a different RW binding and needs its own pass"); + } + + private void snapshot() { + Reflect.invoke(binder, "snapshotRwBindings", new Class[] { ContextState.class, ShaderManager.ProgramObject.class }, st, prog); + } + + private boolean canJoin() { + return Reflect.invoke(binder, "canJoinBatch", new Class[] { ContextState.class, ShaderManager.ProgramObject.class }, st, prog); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinderFallbackTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinderFallbackTest.java new file mode 100644 index 000000000..ec436ab3a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/ComputeBinderFallbackTest.java @@ -0,0 +1,114 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import com.gtnewhorizons.angelica.sdlgpu.resource.SdlReflect; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.sdl.SDL_GPUStorageBufferReadWriteBinding; +import org.lwjgl.sdl.SDL_GPUStorageTextureReadWriteBinding; +import org.lwjgl.system.MemoryStack; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ComputeBinderFallbackTest { + + private static final int RGBA8 = InternalTextureFormat.RGBA8.getGlFormat(); + private static final long STAND_IN_RW = 0x515A_0001L; + private static final long STAND_IN_RO = 0x515A_0002L; + + private ResourceManager rm; + private ComputeBinder binder; + private ContextState st; + private ShaderManager.ProgramObject prog; + + @BeforeEach + void setUp() { + rm = SdlTestRig.resourceManager(); + SdlReflect.putComputeStandIn(rm, RGBA8, GL11.GL_TEXTURE_2D, true, STAND_IN_RW); + SdlReflect.putComputeStandIn(rm, RGBA8, GL11.GL_TEXTURE_2D, false, STAND_IN_RO); + binder = new ComputeBinder(null, rm, null, null); + st = new ContextState(); + st.boundProgram = 1; + prog = new ShaderManager.ProgramObject(); + prog.linked = true; + } + + private static ShaderManager.ComputeBindingMap mapWith(int[] roImages, int[] rwImages, int[] rwSsbos, int[] formats, int[] targets) { + return new ShaderManager.ComputeBindingMap( + new int[0], roImages, rwImages, new int[0], rwSsbos, new int[0], + new String[0], new String[roImages.length], new String[rwImages.length], + new boolean[0], new int[0], + roImages.length == 0 ? new int[0] : formats, + rwImages.length == 0 ? new int[0] : formats, + roImages.length == 0 ? new int[0] : targets, + rwImages.length == 0 ? new int[0] : targets); + } + + @Test + void rwStorageImageSubstitutesStandInAtMipZero() { + prog.computeBindingMap = mapWith(new int[0], new int[] { 0 }, new int[0], new int[] { RGBA8 }, new int[] { GL11.GL_TEXTURE_2D }); + st.boundStorageTextureLevel[0] = 3; + + try (MemoryStack stack = MemoryStack.stackPush()) { + final SDL_GPUStorageTextureReadWriteBinding.Buffer buf = Reflect.invoke(binder, "buildRwTextureBindings", + new Class[] { ContextState.class, ShaderManager.ProgramObject.class, ShaderManager.ComputeBindingMap.class, MemoryStack.class }, + st, prog, prog.computeBindingMap, stack); + assertNotNull(buf, "an unbound RW image substitutes rather than dropping the dispatch"); + assertEquals(STAND_IN_RW, buf.get(0).texture()); + assertEquals(0, buf.get(0).mip_level(), "the stand-in has a single level, so the bound level cannot carry over"); + } + } + + @Test + void rwStorageBufferStillDropsTheDispatch() { + prog.computeBindingMap = mapWith(new int[0], new int[0], new int[] { 2 }, new int[0], new int[0]); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final SDL_GPUStorageBufferReadWriteBinding.Buffer buf = Reflect.invoke(binder, "buildRwBufferBindings", + new Class[] { ContextState.class, int[].class, MemoryStack.class, boolean.class }, + st, new int[] { 2 }, stack, true); + assertNull(buf, "no robust buffer access, so an undersized stand-in would make an OOB write undefined"); + } + } + + @Test + void storageImageStandInIsPickedByDeclaredFormatAndRole() { + final ShaderManager.ComputeBindingMap map = mapWith(new int[] { 0 }, new int[] { 0 }, new int[0], new int[] { RGBA8 }, new int[] { GL11.GL_TEXTURE_2D }); + assertEquals(STAND_IN_RO, standIn(map, 0, false)); + assertEquals(STAND_IN_RW, standIn(map, 0, true), "SDL forbids reading a texture bound read-write without SIMULTANEOUS"); + } + + @Test + void storageImageWithoutDeclaredFormatHasNoStandIn() { + final ShaderManager.ComputeBindingMap map = mapWith(new int[0], new int[] { 0 }, new int[0], new int[] { 0 }, new int[] { GL11.GL_TEXTURE_2D }); + assertEquals(0L, standIn(map, 0, true)); + } + + @Test + void unqualifiedStorageImageFallsBackToTheBoundImageFormat() { + final ShaderManager.ComputeBindingMap map = mapWith(new int[0], new int[] { 0 }, new int[0], new int[] { 0 }, new int[] { GL11.GL_TEXTURE_2D }); + st.boundStorageTextureFormat[0] = RGBA8; + assertEquals(STAND_IN_RW, standIn(map, 0, true)); + } + + @Test + void declaredFormatOutranksTheBoundImageFormat() { + final ShaderManager.ComputeBindingMap map = mapWith(new int[0], new int[] { 0 }, new int[0], new int[] { RGBA8 }, new int[] { GL11.GL_TEXTURE_2D }); + st.boundStorageTextureFormat[0] = InternalTextureFormat.R32UI.getGlFormat(); + assertEquals(STAND_IN_RW, standIn(map, 0, true), "Vulkan needs the view format to match the shader declaration"); + } + + private long standIn(ShaderManager.ComputeBindingMap map, int index, boolean readWrite) { + return Reflect.invoke(binder, "standInStorageTex", + new Class[] { ContextState.class, ShaderManager.ComputeBindingMap.class, int.class, int.class, boolean.class }, + st, map, index, 0, readWrite); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcherTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcherTest.java new file mode 100644 index 000000000..115c04fd4 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/compute/VoxelizationDispatcherTest.java @@ -0,0 +1,107 @@ +package com.gtnewhorizons.angelica.sdlgpu.compute; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VoxelizationDispatcherTest { + + private static final long PASS_HANDLE = 0xDEADBEEFL; + + private static final class RecordingSink implements ComputeDispatchSink { + int beginCount; + int endCount; + int uniformPushCount; + int rebindCount; + boolean lastCycleRwBuffers = true; + final List dispatches = new ArrayList<>(); + + @Override public long beginBatchedComputeDispatch(ContextState st, boolean cycleRwBuffers) { + beginCount++; + lastCycleRwBuffers = cycleRwBuffers; + return PASS_HANDLE; + } + @Override public void dispatchInBatch(long pass, int gx, int gy, int gz) { dispatches.add(new int[]{gx, gy, gz}); } + @Override public void rebindRoStorageBuffers(ContextState st, long pass) { rebindCount++; } + @Override public void endBatchedComputeDispatch(long pass) { endCount++; } + @Override public void pushPendingComputeUniforms(ContextState st) { uniformPushCount++; } + } + + @Test + void beginBatch_opensPassWithCycleFalse() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + assertEquals(PASS_HANDLE, d.beginBatch(new ContextState())); + assertEquals(1, sink.beginCount); + assertFalse(sink.lastCycleRwBuffers, "voxelization must open the batched pass with cycle=false on rw SSBO bindings"); + } + + @Test + void dispatchRange_pushesUniformsBeforeEachDispatch() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + final ContextState st = new ContextState(); + d.dispatchRange(PASS_HANDLE, -1, -1, 0, 64, st); + d.dispatchRange(PASS_HANDLE, -1, -1, 64, 64, st); + assertEquals(2, sink.dispatches.size()); + assertTrue(sink.uniformPushCount >= sink.dispatches.size(), "pushPendingComputeUniforms must run at least once per dispatchInBatch so per-range uniforms land; pushes=" + sink.uniformPushCount + " dispatches=" + sink.dispatches.size()); + } + + @Test + void dispatchRange_roundsGroupsUpToWorkgroupSize() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + final ContextState st = new ContextState(); + d.dispatchRange(PASS_HANDLE, -1, -1, 0, 1, st); + d.dispatchRange(PASS_HANDLE, -1, -1, 0, 64, st); + d.dispatchRange(PASS_HANDLE, -1, -1, 0, 65, st); + assertEquals(1, sink.dispatches.get(0)[0]); + assertEquals(1, sink.dispatches.get(1)[0]); + assertEquals(2, sink.dispatches.get(2)[0]); + for (int[] groups : sink.dispatches) { + assertEquals(1, groups[1]); + assertEquals(1, groups[2]); + } + } + + @Test + void dispatchRange_ignoresEmptyRangeAndNullPass() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + final ContextState st = new ContextState(); + d.dispatchRange(PASS_HANDLE, -1, -1, 0, 0, st); + d.dispatchRange(0, -1, -1, 0, 64, st); + assertEquals(0, sink.dispatches.size()); + assertEquals(0, sink.uniformPushCount); + } + + @Test + void endBatch_ignoresNullPass() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + d.endBatch(0); + assertEquals(0, sink.endCount); + d.endBatch(PASS_HANDLE); + assertEquals(1, sink.endCount); + } + + @Test + void rebindVertexBuffer_forwardsToTheOpenPass() { + final RecordingSink sink = new RecordingSink(); + final VoxelizationDispatcher d = new VoxelizationDispatcher(sink); + d.rebindVertexBuffer(new ContextState(), PASS_HANDLE); + assertEquals(1, sink.rebindCount, "a region change inside one encoder must rebind the vertex buffer"); + assertEquals(0, sink.beginCount, "rebinding must not open a second pass"); + } + + @Test + void constants_matchExpectations() { + assertEquals(64, VoxelizationDispatcher.workgroupSize()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/device/DriverSelectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/device/DriverSelectionTest.java new file mode 100644 index 000000000..d58ecbed5 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/device/DriverSelectionTest.java @@ -0,0 +1,27 @@ +package com.gtnewhorizons.angelica.sdlgpu.device; + +import org.junit.jupiter.api.Test; + +import static com.gtnewhorizons.angelica.sdlgpu.device.Device.resolveDriverName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class DriverSelectionTest { + + @Test + void windowsWithoutUserHintForcesVulkan() { + assertEquals("vulkan", resolveDriverName("", true)); + } + + @Test + void userHintWinsOnWindows() { + assertNull(resolveDriverName("direct3d12", true)); + assertNull(resolveDriverName("vulkan", true)); + } + + @Test + void nonWindowsIsUntouched() { + assertNull(resolveDriverName("", false)); + assertNull(resolveDriverName("direct3d12", false)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextCounterAggregationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextCounterAggregationTest.java new file mode 100644 index 000000000..d410366a6 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/frame/ContextCounterAggregationTest.java @@ -0,0 +1,71 @@ +package com.gtnewhorizons.angelica.sdlgpu.frame; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ContextCounterAggregationTest { + + private List registered; + private ContextState a; + private ContextState b; + + @BeforeEach + void register() { + registered = Reflect.getStatic(SDLGPURenderBackend.class, "registeredStates"); + a = new ContextState(); + b = new ContextState(); + registered.add(a); + registered.add(b); + } + + @AfterEach + void unregister() { + registered.remove(a); + registered.remove(b); + } + + @Test + void sumsAcrossContextsAndZeroesThem() { + a.slotWrites = 3; + a.slotWritesElided = 1; + a.ssboBinds = 5; + a.pipeline.keyRecomputes = 7; + a.pipeline.fastPathHits = 11; + + b.slotWrites = 4; + b.slotWritesElided = 2; + b.ssboBinds = 6; + b.pipeline.keyRecomputes = 8; + b.pipeline.fastPathHits = 12; + + final int[] out = new int[SDLGPURenderBackend.CTR_COUNT]; + SDLGPURenderBackend.takeContextCounters(out); + + assertEquals(7, out[SDLGPURenderBackend.CTR_SLOT_WRITES]); + assertEquals(3, out[SDLGPURenderBackend.CTR_SLOT_WRITES_ELIDED]); + assertEquals(11, out[SDLGPURenderBackend.CTR_SSBO_BINDS]); + assertEquals(15, out[SDLGPURenderBackend.CTR_KEY_RECOMPUTES]); + assertEquals(23, out[SDLGPURenderBackend.CTR_FAST_PATH_HITS]); + + assertEquals(0, a.slotWrites); + assertEquals(0, b.pipeline.fastPathHits); + } + + @Test + void reusedOutputArrayDoesNotAccumulateAcrossDrains() { + final int[] out = new int[SDLGPURenderBackend.CTR_COUNT]; + a.ssboBinds = 9; + SDLGPURenderBackend.takeContextCounters(out); + assertEquals(9, out[SDLGPURenderBackend.CTR_SSBO_BINDS]); + + SDLGPURenderBackend.takeContextCounters(out); + assertEquals(0, out[SDLGPURenderBackend.CTR_SSBO_BINDS], "a claimed count must not be replotted"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PerFrameBlockDedupTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PerFrameBlockDedupTest.java new file mode 100644 index 000000000..bae771861 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PerFrameBlockDedupTest.java @@ -0,0 +1,96 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager.ProgramObject; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager.UniformMemberInfo; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.spvc.Spvc; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PerFrameBlockDedupTest { + + private static final int BLOCK_SIZE = 64; + + private static ProgramObject programWithBlockMemberAt(int offset, int blockIdx) { + final ProgramObject prog = new ProgramObject(); + prog.blockSize[blockIdx] = BLOCK_SIZE; + prog.nextUniformLocation = 1; + prog.blockMemberInfo[blockIdx].put(0, new UniformMemberInfo(offset, 4, 0, false, 1, 1, Spvc.SPVC_BASETYPE_FP32, 1)); + prog.buildUniformSlotArrays(); + return prog; + } + + private final PipelineApplier applier = new PipelineApplier(null, null, null, null, null, null, null, null, null); + private final ContextState st = new ContextState(); + + @Test + void identicalValueFromASecondProgramDoesNotDirtyTheBlock() { + for (int b = 0; b < ShaderManager.BLOCK_COUNT; b++) { + final ProgramObject a = programWithBlockMemberAt(16, b); + final ProgramObject c = programWithBlockMemberAt(16, b); + + st.boundProgramObj = a; + applier.putUniform(st, 0, new float[]{0.75f}); + assertTrue(st.uniformBlocks[b].dirty, "first write must dirty block " + b); + + st.uniformBlocks[b].dirty = false; + st.boundProgramObj = c; + applier.putUniform(st, 0, new float[]{0.75f}); + assertFalse(st.uniformBlocks[b].dirty, "a second program writing the same value must not dirty block " + b + " - that is what breaks a render pass"); + } + } + + @Test + void changedValueFromASecondProgramStillDirties() { + final ProgramObject a = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + final ProgramObject b = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + + st.boundProgramObj = a; + applier.putUniform(st, 0, new float[]{0.75f}); + st.uniformBlocks[0].dirty = false; + + st.boundProgramObj = b; + applier.putUniform(st, 0, new float[]{0.25f}); + assertTrue(st.uniformBlocks[0].dirty, "a genuinely new value must still reach the buffer"); + } + + @Test + void distinctOffsetsAreTrackedSeparately() { + st.boundProgramObj = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + applier.putUniform(st, 0, new float[]{0.75f}); + st.uniformBlocks[0].dirty = false; + + st.boundProgramObj = programWithBlockMemberAt(32, ShaderManager.BLOCK_PER_FRAME); + applier.putUniform(st, 0, new float[]{0.75f}); + assertTrue(st.uniformBlocks[0].dirty, "same value at a different offset is a different member"); + } + + @Test + void blocksTrackHashesIndependently() { + st.boundProgramObj = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + applier.putUniform(st, 0, new float[]{0.75f}); + st.uniformBlocks[0].dirty = false; + + st.boundProgramObj = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_PASS); + applier.putUniform(st, 0, new float[]{0.75f}); + assertTrue(st.uniformBlocks[1].dirty, "per-pass block has its own hash slots"); + assertFalse(st.uniformBlocks[0].dirty, "per-frame block untouched"); + } + + @Test + void dedupDoesNotDropTheValueItself() { + st.boundProgramObj = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + applier.putUniform(st, 0, new float[]{0.75f}); + final float first = st.uniformBlocks[0].staging(BLOCK_SIZE).get(16 >> 2); + + st.boundProgramObj = programWithBlockMemberAt(16, ShaderManager.BLOCK_PER_FRAME); + applier.putUniform(st, 0, new float[]{0.25f}); + final float second = st.uniformBlocks[0].staging(BLOCK_SIZE).get(16 >> 2); + + assertNotEquals(first, second, "the new value must be in the staging buffer"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplierContentEqualsTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplierContentEqualsTest.java new file mode 100644 index 000000000..8189c9683 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplierContentEqualsTest.java @@ -0,0 +1,55 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PipelineApplierContentEqualsTest { + + private static FloatBuffer direct(float... values) { + final FloatBuffer buf = ByteBuffer.allocateDirect(values.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); + buf.put(values).flip(); + return buf; + } + + @Test + void identicalContentMatches() { + final float[] existing = {1f, 2f, 3f, 30000f}; + assertTrue(PipelineApplier.contentEquals(existing, direct(1f, 2f, 3f, 30000f), 0, 4)); + } + + @Test + void differingElementMismatches() { + final float[] existing = {1f, 2f, 3f, 4f}; + assertFalse(PipelineApplier.contentEquals(existing, direct(1f, 2f, 3.5f, 4f), 0, 4)); + assertFalse(PipelineApplier.contentEquals(existing, direct(0f, 2f, 3f, 4f), 0, 4)); + assertFalse(PipelineApplier.contentEquals(existing, direct(1f, 2f, 3f, 5f), 0, 4)); + } + + @Test + void positionOffsetIsHonored() { + final float[] existing = {7f, 8f}; + final FloatBuffer buf = direct(0f, 7f, 8f); + buf.position(1); + assertTrue(PipelineApplier.contentEquals(existing, buf, buf.position(), 2)); + } + + @Test + void nanBitPatternsCompareEqual() { + final float nan = Float.intBitsToFloat(0x7FC00001); + final float[] existing = {nan, 1f}; + assertTrue(PipelineApplier.contentEquals(existing, direct(nan, 1f), 0, 2)); + assertFalse(PipelineApplier.contentEquals(existing, direct(Float.NaN, 1f), 0, 2)); + } + + @Test + void signedZeroIsAMismatch() { + final float[] existing = {0.0f}; + assertFalse(PipelineApplier.contentEquals(existing, direct(-0.0f), 0, 1)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java new file mode 100644 index 000000000..9756a21d5 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java @@ -0,0 +1,181 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +class PipelineCacheKeyTest { + + @BeforeEach + void setUp() { + VAOManager.init(0); + PipelineCache.setSwapchainFormats(new int[]{SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM}); + } + + private PipelineCache createCache() { + return new PipelineCache(); + } + + @Test + void freshContextStateRequestsSeeding() { + final ContextState st = new ContextState(); + assertTrue(st.needsSeed, "a fresh recording stream must request a state seed"); + assertEquals(SDL_GPU_COMPAREOP_LESS, st.pipeline.depthCompareOp); + } + + @Test + void testIdenticalStateProducesSameKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + + final long keyA = computeKey(a); + final long keyB = computeKey(b); + assertEquals(keyA, keyB, "Identical state should produce identical keys"); + } + + @Test + void testBlendChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.blendEnabledPerAttachment[0] = true; + + assertNotEquals(computeKey(a), computeKey(b), "Blend state change should produce different key"); + } + + @Test + void testDepthTestChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + a.hasDepthTarget = true; + b.hasDepthTarget = true; + b.depthTestEnabled = true; + + assertNotEquals(computeKey(a), computeKey(b), "Depth test change should produce different key"); + } + + @Test + void testDepthTestWithoutDsvCollapsesToSameKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.depthTestEnabled = true; + + assertEquals(computeKey(a), computeKey(b), "Depth test without DSV must produce same key"); + } + + @Test + void testCullEnableChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.cullEnabled = true; + + assertNotEquals(computeKey(a), computeKey(b), "Enabling cull should produce different key"); + } + + @Test + void testCullFaceChangeOnlyMattersWhenEnabled() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.cullFaceMode = SDL_GPU_CULLMODE_FRONT; + assertEquals(computeKey(a), computeKey(b), "cullFaceMode change must NOT change key when culling is disabled"); + + a.cullEnabled = true; + b.cullEnabled = true; + assertNotEquals(computeKey(a), computeKey(b), + "cullFaceMode change should change key when culling is enabled"); + } + + @Test + void testPrimitiveTypeChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.primitiveType = SDL_GPU_PRIMITIVETYPE_LINELIST; + + assertNotEquals(computeKey(a), computeKey(b), "Primitive type change should produce different key"); + } + + @Test + void testBlendFactorChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.srcColorFactor = SDL_GPU_BLENDFACTOR_SRC_ALPHA; + b.dstColorFactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + + assertNotEquals(computeKey(a), computeKey(b), "Blend factor change should produce different key"); + } + + @Test + void testColorWriteMaskChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.colorWriteMask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B; + + assertNotEquals(computeKey(a), computeKey(b), "Color write mask change should produce different key"); + } + + @Test + void testShaderChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.vertexShader = 12345L; + b.fragmentShader = 67890L; + + assertNotEquals(computeKey(a), computeKey(b), "Shader change should produce different key"); + } + + @Test + void testDepthCompareOpChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.depthCompareOp = SDL_GPU_COMPAREOP_LESS_OR_EQUAL; + + assertNotEquals(computeKey(a), computeKey(b), "Depth compare op change should produce different key"); + } + + @Test + void testColorTargetFormatChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.setColorTargetFormats(new int[]{SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT}); + + assertNotEquals(computeKey(a), computeKey(b), "Color target format change should produce different key"); + } + + @Test + void testDepthBiasChangeProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.depthBiasConstant = 1.0f; + b.depthBiasSlopeFactor = 2.0f; + + assertNotEquals(computeKey(a), computeKey(b), "Depth bias change should produce different key"); + } + + @Test + void testDepthBiasClampProducesDifferentKey() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + a.depthBiasConstant = b.depthBiasConstant = 1.0f; + a.depthBiasSlopeFactor = b.depthBiasSlopeFactor = 2.0f; + b.depthBiasClamp = 0.5f; + + assertNotEquals(computeKey(a), computeKey(b), "two draws differing only in polygon-offset clamp must not share a pipeline"); + } + + private long computeKey(PipelineCache cache) { + try { + final Method m = PipelineCache.class.getDeclaredMethod("computeKey", PipelineStore.class, ContextState.class); + m.setAccessible(true); + return (long) m.invoke(cache, (PipelineStore) null, (ContextState) null); + } catch (Exception e) { + throw new RuntimeException("Failed to invoke computeKey", e); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexFormatTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexFormatTest.java new file mode 100644 index 000000000..aa627fd64 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexFormatTest.java @@ -0,0 +1,169 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +class PipelineCacheVertexFormatTest { + + private static int mapVertexFormat(int size, int glType, boolean normalized) { + return PipelineCache.mapVertexFormat(size, glType, normalized, false); + } + + @Test + void requestedDiffersFromUsedForUnnormalizedUByte4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, PipelineCache.requestedVertexFormat(4, GL11.GL_UNSIGNED_BYTE, false)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, false)); + } + + @Test + void requestedDiffersFromUsedForUnnormalizedShort2AndUShort4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT2, PipelineCache.requestedVertexFormat(2, GL11.GL_SHORT, false)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_USHORT4, PipelineCache.requestedVertexFormat(4, GL11.GL_UNSIGNED_SHORT, false)); + } + + @Test + void requestedMatchesUsedForFloatAndInt() { + assertEquals(mapVertexFormat(4, GL11.GL_FLOAT, false), PipelineCache.requestedVertexFormat(4, GL11.GL_FLOAT, false)); + assertEquals(mapVertexFormat(4, GL11.GL_INT, false), PipelineCache.requestedVertexFormat(4, GL11.GL_INT, false)); + } + + @Test + void requestedMatchesUsedWhenNormalizedWasAsked() { + assertEquals(mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, true), PipelineCache.requestedVertexFormat(4, GL11.GL_UNSIGNED_BYTE, true)); + } + + @Test + void requestedIsInvalidForPromotedSizes() { + assertEquals(PipelineCache.INVALID_FMT, PipelineCache.requestedVertexFormat(3, GL11.GL_UNSIGNED_BYTE, false)); + assertEquals(PipelineCache.INVALID_FMT, PipelineCache.requestedVertexFormat(1, GL11.GL_SHORT, false)); + } + + @Test + void integerRequestBypassesCoercionAtEveryConvertibleType() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, PipelineCache.mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, false, true)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_BYTE4, PipelineCache.mapVertexFormat(4, GL11.GL_BYTE, false, true)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_USHORT2, PipelineCache.mapVertexFormat(2, GL11.GL_UNSIGNED_SHORT, false, true)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT2, PipelineCache.mapVertexFormat(2, GL11.GL_SHORT, false, true)); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_BYTE4, PipelineCache.mapVertexFormat(3, GL11.GL_BYTE, false, true)); + } + + @Test + void requestedRejectsUnknownTypeAndSize() { + assertEquals(PipelineCache.INVALID_FMT, PipelineCache.requestedVertexFormat(5, GL11.GL_FLOAT, false)); + assertEquals(PipelineCache.INVALID_FMT, PipelineCache.requestedVertexFormat(4, GL11.GL_DOUBLE, false)); + } + + @Test + void testFloat1() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT, mapVertexFormat(1, GL11.GL_FLOAT, false)); + } + + @Test + void testFloat2() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, mapVertexFormat(2, GL11.GL_FLOAT, false)); + } + + @Test + void testFloat3() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, mapVertexFormat(3, GL11.GL_FLOAT, false)); + } + + @Test + void testFloat4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, mapVertexFormat(4, GL11.GL_FLOAT, false)); + } + + @Test + void testUByte4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, false)); + } + + @Test + void testUByte4Norm() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, true)); + } + + @Test + void testUByte4Integer() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, PipelineCache.mapVertexFormat(4, GL11.GL_UNSIGNED_BYTE, false, true)); + } + + @Test + void testShort2() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT2_NORM, mapVertexFormat(2, GL11.GL_SHORT, false)); + } + + @Test + void testShort2Norm() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT2_NORM, mapVertexFormat(2, GL11.GL_SHORT, true)); + } + + @Test + void testShort4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT4_NORM, mapVertexFormat(4, GL11.GL_SHORT, false)); + } + + @Test + void testShort4Integer() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_SHORT4, PipelineCache.mapVertexFormat(4, GL11.GL_SHORT, false, true)); + } + + @Test + void testInt1() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_INT, mapVertexFormat(1, GL11.GL_INT, false)); + } + + @Test + void testInt4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_INT4, mapVertexFormat(4, GL11.GL_INT, false)); + } + + @Test + void testUInt2() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UINT2, mapVertexFormat(2, GL11.GL_UNSIGNED_INT, false)); + } + + @Test + void testHalf2() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_HALF2, mapVertexFormat(2, GL30.GL_HALF_FLOAT, false)); + } + + @Test + void testHalf4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_HALF4, mapVertexFormat(4, GL30.GL_HALF_FLOAT, false)); + } + + @Test + void testByte4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_BYTE4_NORM, mapVertexFormat(4, GL11.GL_BYTE, false)); + } + + @Test + void testByte4Norm() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_BYTE4_NORM, mapVertexFormat(4, GL11.GL_BYTE, true)); + } + + @Test + void testByte4Integer() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_BYTE4, PipelineCache.mapVertexFormat(4, GL11.GL_BYTE, false, true)); + } + + @Test + void testUShort2Norm() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_USHORT2_NORM, mapVertexFormat(2, GL11.GL_UNSIGNED_SHORT, true)); + } + + @Test + void testUShort4() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_USHORT4_NORM, mapVertexFormat(4, GL11.GL_UNSIGNED_SHORT, false)); + } + + @Test + void testUShort4Integer() { + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_USHORT4, PipelineCache.mapVertexFormat(4, GL11.GL_UNSIGNED_SHORT, false, true)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java new file mode 100644 index 000000000..5b53135d5 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java @@ -0,0 +1,479 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.spvc.Spvc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXINPUTRATE_INSTANCE; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXINPUTRATE_VERTEX; + +class PipelineCacheVertexInputTest { + private static final int PLACEHOLDER_PITCH = 16; + + private PipelineStore store; + + @BeforeEach + void setUp() { + VAOManager.init(0); + PipelineCache.setSwapchainFormats(new int[]{SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM}); + store = new PipelineStore(null); + } + + private static PipelineCache cache(int shaderInputMask, int[] vecSizes, int[] baseTypes) { + final PipelineCache c = new PipelineCache(); + c.maxAttribs = ContextState.MAX_VERTEX_ATTRIBS; + c.shaderInputMask = shaderInputMask; + c.shaderInputVecSize = vecSizes; + c.shaderInputBaseType = baseTypes; + return c; + } + + private static void enableFloatAttrib(ContextState cs, int loc, int size, int stride) { + final ContextState.VAOState vao = cs.currentVao; + vao.attribEnabled[loc] = true; + vao.attribEnabledMask |= (1 << loc); + vao.attribSize[loc] = size; + vao.attribType[loc] = GL11.GL_FLOAT; + vao.attribNormalized[loc] = false; + vao.attribIsInteger[loc] = false; + vao.attribStride[loc] = stride; + vao.bindingStride[loc] = stride; // attribBinding[loc]=loc by VAOState default + } + + private static void enableAttrib(ContextState cs, int loc, int size, int glType, boolean normalized, boolean isInteger, int stride) { + final ContextState.VAOState vao = cs.currentVao; + vao.attribEnabled[loc] = true; + vao.attribEnabledMask |= (1 << loc); + vao.attribSize[loc] = size; + vao.attribType[loc] = glType; + vao.attribNormalized[loc] = normalized; + vao.attribIsInteger[loc] = isInteger; + vao.attribStride[loc] = stride; + vao.bindingStride[loc] = stride; + } + + private static PipelineCache coercionCache(String name) { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(1, vecSizes, baseTypes); + final String[] names = new String[ContextState.MAX_VERTEX_ATTRIBS]; + names[0] = name; + c.shaderInputName = names; + return c; + } + + @Test + void unnormalizedUByte4_withoutResolver_fallsBackToNormAndWarnsOnce() { + final ContextState cs = new ContextState(); + cs.boundProgram = 7; + enableAttrib(cs, 0, 4, GL11.GL_UNSIGNED_BYTE, false, false, 4); + final PipelineCache c = coercionCache("a_Object"); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(0L, r.vertexShaderOverride()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, r.attrs().get(0).format()); + } + assertEquals(1, store.loggedFormatSubstitution.size()); + + try (MemoryStack stack = MemoryStack.stackPush()) { + c.buildVertexInput(store, cs, stack); + } + assertEquals(1, store.loggedFormatSubstitution.size(), "warning must not repeat per pipeline rebuild"); + } + + @Test + void unnormalizedUByte4_withResolver_bindsIntegerFormatAndUsesVariantShader() { + final ContextState cs = new ContextState(); + cs.boundProgram = 7; + enableAttrib(cs, 0, 4, GL11.GL_UNSIGNED_BYTE, false, false, 4); + final PipelineCache c = coercionCache("a_Object"); + + final ShaderManager.VertexVariant variant = new ShaderManager.VertexVariant(); + variant.sdlShader = 0xABCDL; + variant.inputBaseType[0] = Spvc.SPVC_BASETYPE_UINT32; + final int[] seenKey = { 0 }; + store.setVertexVariantResolver((program, key, attribs) -> { + seenKey[0]++; + assertEquals(7, program); + assertEquals(1, attribs.size()); + assertEquals("a_Object", attribs.get(0).name()); + assertEquals(0, attribs.get(0).location(), "the attribute's bound location must reach the retype"); + assertEquals(4, attribs.get(0).declVecSize()); + assertEquals(4, attribs.get(0).boundVecSize()); + assertFalse(attribs.get(0).signed()); + return variant; + }); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(0xABCDL, r.vertexShaderOverride()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4, r.attrs().get(0).format()); + } + assertEquals(1, seenKey[0]); + assertTrue(store.loggedFormatSubstitution.isEmpty(), "a converted attribute must not warn"); + } + + @Test + void normalizedAndIntegerAttribsAreNotCoerced() { + final ContextState cs = new ContextState(); + cs.boundProgram = 7; + enableAttrib(cs, 0, 4, GL11.GL_UNSIGNED_BYTE, true, false, 4); + final PipelineCache c = coercionCache("a_Color"); + store.setVertexVariantResolver((program, key, attribs) -> { + throw new AssertionError("normalized attribute must not request a variant"); + }); + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertEquals(0L, r.vertexShaderOverride()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, r.attrs().get(0).format()); + } + assertTrue(store.loggedFormatSubstitution.isEmpty()); + } + + @Test + void sparseLayout_locations0and2_buildsDenseBindingArray() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[2] = 2; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[2] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x5, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 20); + enableFloatAttrib(cs, 2, 2, 20); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r, "expected non-null result for valid VS layout"); + assertEquals(3, r.numBuffers(), "bindings array must cover slots [0, maxSlot]=[0,2]"); + assertEquals(3, r.numAttributes(), "every binding (including gap slot 1) must have a referencing attribute"); + + assertEquals(0, r.bindings().get(0).slot()); + assertEquals(20, r.bindings().get(0).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_VERTEX, r.bindings().get(0).input_rate()); + assertEquals(1, r.bindings().get(1).slot()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(1).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(1).input_rate()); + assertEquals(2, r.bindings().get(2).slot()); + assertEquals(20, r.bindings().get(2).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_VERTEX, r.bindings().get(2).input_rate()); + + assertEquals(0, r.attrs().get(0).location()); + assertEquals(0, r.attrs().get(0).buffer_slot()); + assertEquals(1, r.attrs().get(1).location()); + assertEquals(1, r.attrs().get(1).buffer_slot()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, r.attrs().get(1).format()); + assertEquals(2, r.attrs().get(2).location()); + assertEquals(2, r.attrs().get(2).buffer_slot()); + } + } + + @Test + void floatProducerAgainstIntShaderInput_refusesToBuild() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 1; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; + baseTypes[1] = Spvc.SPVC_BASETYPE_INT32; + final PipelineCache c = cache(0x3, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 12); + enableFloatAttrib(cs, 1, 4, 16); + + try (MemoryStack stack = MemoryStack.stackPush()) { + assertNull(c.buildVertexInput(store, cs, stack), "a float producer feeding an int shader input must not produce a pipeline"); + } + } + + @Test + void correctedDhGenericLayout_buildsSuccessfully() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; + baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x3, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 12); + enableFloatAttrib(cs, 1, 4, 16); + + try (MemoryStack stack = MemoryStack.stackPush()) { + assertNotNull(c.buildVertexInput(store, cs, stack)); + } + } + + @Test + void denseLayout_locations0_1_2_noPlaceholders() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; vecSizes[2] = 2; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; baseTypes[2] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x7, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 24); + enableFloatAttrib(cs, 1, 4, 24); + enableFloatAttrib(cs, 2, 2, 24); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(3, r.numBuffers()); + assertEquals(3, r.numAttributes()); + assertEquals(24, r.bindings().get(0).pitch()); + assertEquals(24, r.bindings().get(1).pitch()); + assertEquals(24, r.bindings().get(2).pitch()); + } + } + + @Test + void shaderExpectsButVaoMissing_emitsInstanceExpansion() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x3, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 12); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(2, r.numBuffers()); + assertEquals(2, r.numAttributes()); + assertEquals(1, r.bindings().get(1).slot()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(1).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(1).input_rate()); + assertEquals(1, r.attrs().get(1).location()); + assertEquals(1, r.attrs().get(1).buffer_slot()); + } + } + + @Test + void vaoExtraAttribNotInShader_droppedFromPipeline() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 4; vecSizes[2] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[2] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x5, vecSizes, baseTypes); // shaderInputMask = 0x5 + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 24); + enableFloatAttrib(cs, 2, 2, 24); + cs.currentVao.attribEnabled[4] = true; + cs.currentVao.attribEnabledMask |= (1 << 4); + cs.currentVao.attribSize[4] = 3; + cs.currentVao.attribType[4] = GL11.GL_BYTE; + cs.currentVao.attribNormalized[4] = true; + cs.currentVao.attribStride[4] = 24; + cs.currentVao.bindingStride[4] = 24; + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(3, r.numBuffers(), "bindings cover slots [0..maxSlot=2], not widened to loc 4"); + assertEquals(3, r.numAttributes(), "2 real + 1 dummy for gap slot 1; loc 4 stays dropped"); + for (int i = 0; i < r.numAttributes(); i++) { + final int loc = r.attrs().get(i).location(); + final int slot = r.attrs().get(i).buffer_slot(); + if (loc == 4 || slot == 4) { + throw new AssertionError("attr[" + i + "] references loc=" + loc + " buffer_slot=" + slot + " -- should have been filtered out"); + } + } + + assertEquals(1, r.attrs().get(1).location()); + assertEquals(1, r.attrs().get(1).buffer_slot()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, r.attrs().get(1).format()); + } + } + + @Test + void interiorGapWithoutExpansion_fillsGapWithPlaceholder() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[3] = 2; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[3] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x9, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 20); + enableFloatAttrib(cs, 3, 2, 20); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(4, r.numBuffers(), "maxSlot=3 -> 4 entries"); + assertEquals(4, r.numAttributes(), "2 real + 2 dummies for gap slots 1 and 2"); + + assertEquals(20, r.bindings().get(0).pitch()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(1).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(1).input_rate()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(2).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(2).input_rate()); + assertEquals(20, r.bindings().get(3).pitch()); + + assertEquals(0, r.attrs().get(0).buffer_slot()); + assertEquals(1, r.attrs().get(1).buffer_slot()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, r.attrs().get(1).format()); + assertEquals(2, r.attrs().get(2).buffer_slot()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, r.attrs().get(2).format()); + assertEquals(3, r.attrs().get(3).buffer_slot()); + } + } + + @Test + void enabledAttribWithoutPointer_treatedAsDisabled() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; vecSizes[3] = 2; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; baseTypes[3] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0xB, vecSizes, baseTypes); // locs 0, 1, 3 + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 16); + enableFloatAttrib(cs, 1, 4, 16); + cs.currentVao.attribEnabled[3] = true; + cs.currentVao.attribEnabledMask |= (1 << 3); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r, "enabled-but-unpointed attrib must not fail pipeline construction"); + assertEquals(4, r.numBuffers()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(3).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(3).input_rate()); + assertEquals(3, r.attrs().get(3).location()); + assertEquals(3, r.attrs().get(3).buffer_slot()); + } + } + + @Test + void everyBindingHasReferencingAttribute_evenAcrossGaps() { + // Metal MTLVertexDescriptor requirement: every declared buffer layout must be referenced by at least one attribute + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[15] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[15] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x8001, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 12); + enableFloatAttrib(cs, 15, 4, 16); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(16, r.numBuffers()); + assertEquals(16, r.numAttributes()); + for (int s = 0; s < r.numBuffers(); s++) { + boolean covered = false; + for (int k = 0; k < r.numAttributes(); k++) { + if (r.attrs().get(k).buffer_slot() == s) { covered = true; break; } + } + assertTrue(covered, "slot " + s + " has no referencing attribute -- Metal will reject"); + } + } + } + + @Test + void enabledAttribWithDeadBuffer_demotedToConstantExpansion() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x3, vecSizes, baseTypes); + store.setBufferHandleResolver(id -> id == 42 ? 0xBEEFL : 0L); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 16); + cs.currentVao.bindingBuffer[0] = 42; // live + enableFloatAttrib(cs, 1, 4, 4); + cs.currentVao.bindingBuffer[1] = 7; // dead handle + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(16, r.bindings().get(0).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_VERTEX, r.bindings().get(0).input_rate()); + assertEquals(PLACEHOLDER_PITCH, r.bindings().get(1).pitch()); + assertEquals(SDL_GPU_VERTEXINPUTRATE_INSTANCE, r.bindings().get(1).input_rate()); + assertEquals(SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, r.attrs().get(1).format()); + } + } + + @Test + void pipelineKeyDiffersBetweenDeadAndLiveBinding() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[1] = 4; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[1] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x3, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 16); + cs.currentVao.bindingBuffer[0] = 42; + enableFloatAttrib(cs, 1, 4, 4); + cs.currentVao.bindingBuffer[1] = 7; + + store.setBufferHandleResolver(id -> 0xBEEFL); // both live + final long liveKey = c.computeKey(store, cs); + store.setBufferHandleResolver(id -> id == 42 ? 0xBEEFL : 0L); // loc 1's buffer dead + final long deadKey = c.computeKey(store, cs); + + assertTrue(liveKey != deadKey, "demotion must produce a distinct pipeline key or a cached per-vertex pipeline would be reused for the constant layout"); + } + + @Test + void bindVertexBufferInvalidatesCachedKeyOnlyWhenLivenessFlips() { + final PipelineCache c = cache(0x1, new int[ContextState.MAX_VERTEX_ATTRIBS], new int[ContextState.MAX_VERTEX_ATTRIBS]); + store.setBufferHandleResolver(id -> id == 9 ? 0L : 0xBEEFL); + + assertTrue(c.markInputDirtyIfLivenessChanged(store, 42, 9), "live -> dead must invalidate the cached input layout"); + assertTrue(c.markInputDirtyIfLivenessChanged(store, 9, 42), "dead -> live must invalidate the cached input layout"); + assertFalse(c.markInputDirtyIfLivenessChanged(store, 42, 7), "swapping two live buffers must not force an input rehash"); + } + + @Test + void bindingsArrayIsDenseIndexedBySlot() { + // D3D12 requirement: SDL's D3D12 backend reads vertex_buffer_descriptions[buffer_slot] as a flat array, so bindings.get(i).slot() must equal i + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[0] = 3; vecSizes[5] = 2; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[0] = Spvc.SPVC_BASETYPE_FP32; baseTypes[5] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(0x21, vecSizes, baseTypes); + + final ContextState cs = new ContextState(); + enableFloatAttrib(cs, 0, 3, 12); + enableFloatAttrib(cs, 5, 2, 8); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(store, cs, stack); + assertNotNull(r); + assertEquals(6, r.numBuffers()); + for (int i = 0; i < r.numBuffers(); i++) { + assertEquals(i, r.bindings().get(i).slot(), "binding[" + i + "].slot must equal its array index"); + } + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PrimitiveRestartScanTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PrimitiveRestartScanTest.java new file mode 100644 index 000000000..b77407d2f --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PrimitiveRestartScanTest.java @@ -0,0 +1,138 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PrimitiveRestartScanTest { + + private static ByteBuffer shortBuf(int... values) { + final ByteBuffer b = MemoryUtil.memAlloc(values.length * 2).order(ByteOrder.nativeOrder()); + for (int v : values) b.putShort((short) v); + b.position(0); + return b; + } + + private static ByteBuffer intBuf(int... values) { + final ByteBuffer b = MemoryUtil.memAlloc(values.length * 4).order(ByteOrder.nativeOrder()); + for (int v : values) b.putInt(v); + b.position(0); + return b; + } + + private static void assertSplits(EBOSplitScanner.EboSplit[] actual, int... pairs) { + final EBOSplitScanner.EboSplit[] expected = new EBOSplitScanner.EboSplit[pairs.length / 2]; + for (int i = 0; i < expected.length; i++) { + expected[i] = new EBOSplitScanner.EboSplit(pairs[i * 2], pairs[i * 2 + 1]); + } + assertArrayEquals(expected, actual); + } + + private static EBOSplitScanner.EboSplit[] slice(EBOSplitScanner.EboSplit[] full, int firstIndex, int count) { + final int[] firsts = new int[full.length]; + final int[] counts = new int[full.length]; + final int n = EBOSplitScanner.sliceSplits(full, firstIndex, count, firsts, counts); + final EBOSplitScanner.EboSplit[] out = new EBOSplitScanner.EboSplit[n]; + for (int i = 0; i < n; i++) out[i] = new EBOSplitScanner.EboSplit(firsts[i], counts[i]); + return out; + } + + @Test + void shortBuffer_noSentinel_singleFullRun() { + final ByteBuffer b = shortBuf(0, 1, 2, 3, 4); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 5, GL11.GL_UNSIGNED_SHORT, 0xFFFF), 0, 5); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void shortBuffer_sentinelMiddle_twoRuns() { + final ByteBuffer b = shortBuf(0, 1, 2, 0xFFFF, 4, 5, 6); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 7, GL11.GL_UNSIGNED_SHORT, 0xFFFF), 0, 3, 4, 3); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void shortBuffer_sentinelLeading_skipsToFirstRun() { + final ByteBuffer b = shortBuf(0xFFFF, 1, 2, 3); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 4, GL11.GL_UNSIGNED_SHORT, 0xFFFF), 1, 3); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void shortBuffer_sentinelTrailing_dropsTail() { + final ByteBuffer b = shortBuf(0, 1, 2, 0xFFFF); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 4, GL11.GL_UNSIGNED_SHORT, 0xFFFF), 0, 3); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void shortBuffer_consecutiveSentinels_collapse() { + final ByteBuffer b = shortBuf(0, 1, 0xFFFF, 0xFFFF, 0xFFFF, 5, 6); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 7, GL11.GL_UNSIGNED_SHORT, 0xFFFF), 0, 2, 5, 2); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void shortBuffer_allSentinels_emptyOutput() { + final ByteBuffer b = shortBuf(0xFFFF, 0xFFFF, 0xFFFF); + try { + assertEquals(0, EBOSplitScanner.scanIndices(b, 3, GL11.GL_UNSIGNED_SHORT, 0xFFFF).length); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void intBuffer_largeSentinel() { + final ByteBuffer b = intBuf(0, 1, 2, 0xFFFFFFFF, 4, 5); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 6, GL11.GL_UNSIGNED_INT, 0xFFFFFFFF), 0, 3, 4, 2); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void intBuffer_customSentinelZero() { + final ByteBuffer b = intBuf(5, 6, 0, 7, 8, 0, 9); + try { + assertSplits(EBOSplitScanner.scanIndices(b, 7, GL11.GL_UNSIGNED_INT, 0), 0, 2, 3, 2, 6, 1); + } finally { MemoryUtil.memFree(b); } + } + + @Test + void sliceSplits_emptyFull_returnsEmpty() { + assertEquals(0, slice(new EBOSplitScanner.EboSplit[0], 0, 10).length); + } + + @Test + void sliceSplits_windowContainsOneRun_returnsTranslated() { + final EBOSplitScanner.EboSplit[] full = { new EBOSplitScanner.EboSplit(0, 3), new EBOSplitScanner.EboSplit(4, 3) }; + assertSplits(slice(full, 4, 3), 0, 3); + } + + @Test + void sliceSplits_windowSpansMultipleRuns() { + final EBOSplitScanner.EboSplit[] full = { new EBOSplitScanner.EboSplit(0, 3), new EBOSplitScanner.EboSplit(4, 3), new EBOSplitScanner.EboSplit(8, 2) }; + assertSplits(slice(full, 2, 7), 0, 1, 2, 3, 6, 1); + } + + @Test + void sliceSplits_windowOutsideAllRuns_returnsEmpty() { + final EBOSplitScanner.EboSplit[] full = { new EBOSplitScanner.EboSplit(0, 3), new EBOSplitScanner.EboSplit(4, 3) }; + assertEquals(0, slice(full, 100, 50).length); + } + + @Test + void sliceSplits_windowClipsRunStartAndEnd() { + final EBOSplitScanner.EboSplit[] full = { new EBOSplitScanner.EboSplit(2, 10) }; // [2, 12) + assertSplits(slice(full, 5, 4), 0, 4); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BgraStorageChannelTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BgraStorageChannelTest.java new file mode 100644 index 000000000..b606b78ae --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BgraStorageChannelTest.java @@ -0,0 +1,191 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +/** + * Covers the storage-format-aware R/B channel handling in SDL-GPU readback / upload paths. + */ +class BgraStorageChannelTest { + + private static final int RGBA = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + private static final int BGRA = SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; + private static final int BGRA_SRGB = SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB; + + private static ByteBuffer pixel(int c0, int c1, int c2, int c3) { + final ByteBuffer b = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()); + b.put((byte) c0).put((byte) c1).put((byte) c2).put((byte) c3).rewind(); + return b; + } + + private static byte[] toArray(ByteBuffer b, int len) { + final byte[] out = new byte[len]; + final int pos = b.position(); + for (int i = 0; i < len; i++) out[i] = b.get(pos + i); + return out; + } + + @Test + void isBgraSdlFormat_recognizesAllBgraVariants() { + assertTrue(PixelOps.isBgraSdlFormat(BGRA)); + assertTrue(PixelOps.isBgraSdlFormat(BGRA_SRGB)); + assertFalse(PixelOps.isBgraSdlFormat(RGBA)); + assertFalse(PixelOps.isBgraSdlFormat(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB)); + } + + @Test + void swapRedBlueIfNeeded_noOpWhenFalse() { + final ByteBuffer p = pixel(1, 2, 3, 4); + PixelOps.swapRedBlueIfNeeded(p, 1, 1, false); + assertArrayEquals(new byte[]{1, 2, 3, 4}, toArray(p, 4)); + } + + @Test + void swapRedBlueIfNeeded_swapsWhenTrue() { + final ByteBuffer p = pixel(1, 2, 3, 4); + PixelOps.swapRedBlueIfNeeded(p, 1, 1, true); + assertArrayEquals(new byte[]{3, 2, 1, 4}, toArray(p, 4)); + } + + @Test + void readback_rgbaStorage_rgbaRequest_passesThrough() { + final ByteBuffer p = pixel(0x11, 0x22, 0x33, 0x44); + PixelOps.postProcessReadback(p, 1, 1, GL11.GL_RGBA, RGBA, false); + assertArrayEquals(new byte[]{0x11, 0x22, 0x33, 0x44}, toArray(p, 4)); + } + + @Test + void readback_rgbaStorage_bgraRequest_swaps() { + final ByteBuffer p = pixel(0x11, 0x22, 0x33, 0x44); + PixelOps.postProcessReadback(p, 1, 1, GL12.GL_BGRA, RGBA, false); + assertArrayEquals(new byte[]{0x33, 0x22, 0x11, 0x44}, toArray(p, 4)); + } + + @Test + void readback_bgraStorage_bgraRequest_passesThrough() { + final ByteBuffer p = pixel(0x11, 0x22, 0x33, 0x44); + PixelOps.postProcessReadback(p, 1, 1, GL12.GL_BGRA, BGRA, false); + assertArrayEquals(new byte[]{0x11, 0x22, 0x33, 0x44}, toArray(p, 4)); + } + + @Test + void readback_bgraStorage_rgbaRequest_swaps() { + final ByteBuffer p = pixel(0x11, 0x22, 0x33, 0x44); + PixelOps.postProcessReadback(p, 1, 1, GL11.GL_RGBA, BGRA, false); + assertArrayEquals(new byte[]{0x33, 0x22, 0x11, 0x44}, toArray(p, 4)); + } + + @Test + void readback_jmAtlasWaterRoundTrip() { + final ByteBuffer p = pixel(223, 164, 64, 255); // BGRA storage of (R=64,G=164,B=223,A=255) + PixelOps.postProcessReadback(p, 1, 1, GL12.GL_BGRA, BGRA, false); + assertArrayEquals(new byte[]{(byte) 223, (byte) 164, (byte) 64, (byte) 255}, toArray(p, 4)); + } + + @Test + void readback_flipRowsAppliesBeforeChannelSwap() { + final ByteBuffer p = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + p.put(new byte[]{(byte) 0xAA, 0x01, 0x02, 0x03, (byte) 0xBB, 0x10, 0x20, 0x30}).rewind(); + PixelOps.postProcessReadback(p, 1, 2, GL12.GL_BGRA, RGBA, true); + + assertArrayEquals(new byte[]{0x20, 0x10, (byte) 0xBB, 0x30, 0x02, 0x01, (byte) 0xAA, 0x03}, toArray(p, 8)); + } + + @Test + void upload_rgbaSrc_rgbaStorage_passesThrough() { + final ByteBuffer src = pixel(0x11, 0x22, 0x33, 0x44); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL11.GL_RGBA, RGBA, src, 1, 1); + assertSame(src, out, "no transform expected"); + } + + @Test + void upload_bgraSrc_bgraStorage_passesThrough() { + final ByteBuffer src = pixel(0x11, 0x22, 0x33, 0x44); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL12.GL_BGRA, BGRA, src, 1, 1); + assertSame(src, out); + } + + @Test + void upload_rgbaSrc_bgraStorage_swaps() { + final ByteBuffer src = pixel(0x11, 0x22, 0x33, 0x44); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL11.GL_RGBA, BGRA, src, 1, 1); + try { + assertNotSame(src, out); + assertArrayEquals(new byte[]{0x33, 0x22, 0x11, 0x44}, toArray(out, 4)); + } finally { + MemoryUtil.memFree(out); + } + } + + @Test + void upload_bgraSrc_rgbaStorage_swaps() { + final ByteBuffer src = pixel(0x11, 0x22, 0x33, 0x44); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL12.GL_BGRA, RGBA, src, 1, 1); + try { + assertNotSame(src, out); + assertArrayEquals(new byte[]{0x33, 0x22, 0x11, 0x44}, toArray(out, 4)); + } finally { + MemoryUtil.memFree(out); + } + } + + @Test + void upload_luminanceSrc_rgbaStorage_expandsOnly() { + final ByteBuffer src = ByteBuffer.allocateDirect(1).order(ByteOrder.nativeOrder()); + src.put((byte) 0x77).rewind(); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL11.GL_LUMINANCE, RGBA, src, 1, 1); + try { + assertNotSame(src, out); + assertArrayEquals(new byte[]{0x77, 0x77, 0x77, (byte) 0xFF}, toArray(out, 4)); + } finally { + MemoryUtil.memFree(out); + } + } + + @Test + void upload_luminanceSrc_bgraStorage_expandsAndSwaps() { + final ByteBuffer src = ByteBuffer.allocateDirect(1).order(ByteOrder.nativeOrder()); + src.put((byte) 0x77).rewind(); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL11.GL_LUMINANCE, BGRA, src, 1, 1); + try { + assertNotSame(src, out); + assertArrayEquals(new byte[]{0x77, 0x77, 0x77, (byte) 0xFF}, toArray(out, 4)); + } finally { + MemoryUtil.memFree(out); + } + } + + @Test + void upload_luminanceAlphaSrc_bgraStorage_expandsAndSwaps() { + final ByteBuffer src = ByteBuffer.allocateDirect(2).order(ByteOrder.nativeOrder()); + src.put((byte) 0x42).put((byte) 0x88).rewind(); + final ByteBuffer out = PixelOps.prepareUploadBuffer(GL11.GL_LUMINANCE_ALPHA, BGRA, src, 1, 1); + try { + assertNotSame(src, out); + assertArrayEquals(new byte[]{0x42, 0x42, 0x42, (byte) 0x88}, toArray(out, 4)); + } finally { + MemoryUtil.memFree(out); + } + } + + @Test + void swapRedBlueCopy_independentOfSourcePosition() { + final ByteBuffer src = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + src.put(new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF, 0x11, 0x22, 0x33, 0x44}).position(4); + final ByteBuffer out = PixelOps.swapRedBlueCopy(src, 1, 1); + try { + assertArrayEquals(new byte[]{0x33, 0x22, 0x11, 0x44}, toArray(out, 4)); + assertEquals(4, src.position(), "source position must be preserved"); + } finally { + MemoryUtil.memFree(out); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BlitCopyDecisionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BlitCopyDecisionTest.java new file mode 100644 index 000000000..b26bbe867 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BlitCopyDecisionTest.java @@ -0,0 +1,40 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +class BlitCopyDecisionTest { + + private static ResourceManager.TextureMeta meta(int sdlFormat) { + return new ResourceManager.TextureMeta(GL11.GL_TEXTURE_2D, GL11.GL_RGBA8, sdlFormat, 1024, 1024, 1, 1, 0); + } + + @Test + void sameFormatOneToOneCopies() { + assertTrue(TextureOps.canCopyInsteadOfBlit(meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), 1024, 1024, 1024, 1024)); + } + + @Test + void formatMismatchBlits() { + assertFalse(TextureOps.canCopyInsteadOfBlit(meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), meta(SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM), 1024, 1024, 1024, 1024)); + } + + @Test + void scalingBlits() { + assertFalse(TextureOps.canCopyInsteadOfBlit(meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), 1024, 1024, 512, 512)); + } + + @Test + void flippedRegionBlits() { + assertFalse(TextureOps.canCopyInsteadOfBlit(meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), -1024, 1024, -1024, 1024)); + } + + @Test + void missingMetaBlits() { + assertFalse(TextureOps.canCopyInsteadOfBlit(null, meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), 1024, 1024, 1024, 1024)); + assertFalse(TextureOps.canCopyInsteadOfBlit(meta(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM), null, 1024, 1024, 1024, 1024)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferContentsDefinedTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferContentsDefinedTest.java new file mode 100644 index 000000000..4e736e3dd --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferContentsDefinedTest.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BufferContentsDefinedTest { + + private static ResourceManager newResourceManager() { + return SdlTestRig.resourceManager(); + } + + @Test + void unknownBuffer_isNotUndefined() { + assertFalse(newResourceManager().hasUndefinedContents(4242)); + } + + @Test + void markDefined_clearsTheFlag() { + final ResourceManager rm = newResourceManager(); + SdlReflect.markUndefined(rm, 7); + assertTrue(rm.hasUndefinedContents(7)); + + rm.markBufferContentsDefined(7); + assertFalse(rm.hasUndefinedContents(7)); + } + + @Test + void markDefined_isIdempotentAndIgnoresZero() { + final ResourceManager rm = newResourceManager(); + rm.markBufferContentsDefined(0); + rm.markBufferContentsDefined(9); + rm.markBufferContentsDefined(9); + assertFalse(rm.hasUndefinedContents(9)); + } + + @Test + void deleteBuffer_clearsTheFlag() { + final ResourceManager rm = newResourceManager(); + SdlReflect.markUndefined(rm, 5); + rm.recordBufferSizeOnly(5, 1000); + + rm.deleteBuffer(5); + + assertFalse(rm.hasUndefinedContents(5)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferGlParamsTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferGlParamsTest.java new file mode 100644 index 000000000..8c61831ff --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferGlParamsTest.java @@ -0,0 +1,64 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL44; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BufferGlParamsTest { + + private static ResourceManager newResourceManager() { + return SdlTestRig.resourceManager(); + } + + @Test + void unknownBuffer_reportsGlDefaults() { + final ResourceManager rm = newResourceManager(); + assertEquals(GL15.GL_STATIC_DRAW, rm.getBufferGlUsage(4242)); + assertEquals(BufferParams.MUTABLE_STORE, rm.getBufferStorageFlags(4242)); + assertEquals(0L, rm.getBufferSize(4242)); + } + + @Test + void recordedParams_roundTrip() { + final ResourceManager rm = newResourceManager(); + rm.recordBufferGlParams(1, GL15.GL_STREAM_DRAW, BufferParams.MUTABLE_STORE); + assertEquals(GL15.GL_STREAM_DRAW, rm.getBufferGlUsage(1)); + assertEquals(BufferParams.MUTABLE_STORE, rm.getBufferStorageFlags(1)); + + final int flags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT; + rm.recordBufferGlParams(2, GL15.GL_DYNAMIC_DRAW, flags); + assertEquals(GL15.GL_DYNAMIC_DRAW, rm.getBufferGlUsage(2)); + assertEquals(flags, rm.getBufferStorageFlags(2)); + } + + @Test + void recordedParams_overwrittenOnRespecification() { + final ResourceManager rm = newResourceManager(); + rm.recordBufferGlParams(3, GL15.GL_DYNAMIC_DRAW, GL30.GL_MAP_WRITE_BIT); + rm.recordBufferGlParams(3, GL15.GL_STATIC_DRAW, BufferParams.MUTABLE_STORE); + assertEquals(GL15.GL_STATIC_DRAW, rm.getBufferGlUsage(3)); + assertEquals(BufferParams.MUTABLE_STORE, rm.getBufferStorageFlags(3)); + } + + @Test + void deleteBuffer_clearsParamsBackToDefaults() { + final ResourceManager rm = newResourceManager(); + rm.recordBufferSizeOnly(5, 1000); + rm.recordBufferGlParams(5, GL15.GL_STREAM_READ, GL30.GL_MAP_READ_BIT); + + rm.deleteBuffer(5); + + assertEquals(GL15.GL_STATIC_DRAW, rm.getBufferGlUsage(5)); + assertEquals(BufferParams.MUTABLE_STORE, rm.getBufferStorageFlags(5)); + assertEquals(0L, rm.getBufferSize(5)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParamsTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParamsTest.java new file mode 100644 index 000000000..f339ba086 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferParamsTest.java @@ -0,0 +1,110 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL44; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BufferParamsTest { + + private static int unmapped(int pname, long size, int glUsage, int storageFlags) { + return BufferParams.resolve(pname, size, glUsage, storageFlags, false, 0, 0, 0); + } + + @Test + void untouchedBuffer_reportsGlInitialValues() { + final int storage = BufferParams.MUTABLE_STORE; + assertEquals(0, unmapped(GL15.GL_BUFFER_SIZE, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(GL15.GL_STATIC_DRAW, unmapped(GL15.GL_BUFFER_USAGE, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(GL11.GL_FALSE, unmapped(GL44.GL_BUFFER_IMMUTABLE_STORAGE, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(0, unmapped(GL44.GL_BUFFER_STORAGE_FLAGS, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(GL11.GL_FALSE, unmapped(GL15.GL_BUFFER_MAPPED, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(GL15.GL_READ_WRITE, unmapped(GL15.GL_BUFFER_ACCESS, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(0, unmapped(GL30.GL_BUFFER_ACCESS_FLAGS, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(0, unmapped(GL30.GL_BUFFER_MAP_OFFSET, 0, GL15.GL_STATIC_DRAW, storage)); + assertEquals(0, unmapped(GL30.GL_BUFFER_MAP_LENGTH, 0, GL15.GL_STATIC_DRAW, storage)); + } + + @Test + void bufferDataStore_reportsExactSizeAndUsageHint() { + assertEquals(1000, unmapped(GL15.GL_BUFFER_SIZE, 1000, GL15.GL_STREAM_DRAW, BufferParams.MUTABLE_STORE)); + assertEquals(GL15.GL_STREAM_DRAW, unmapped(GL15.GL_BUFFER_USAGE, 1000, GL15.GL_STREAM_DRAW, BufferParams.MUTABLE_STORE)); + } + + @Test + void bufferStorageStore_isImmutableWithFlagsAndDynamicDraw() { + final int flags = GL44.GL_MAP_PERSISTENT_BIT | GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_COHERENT_BIT; + assertEquals(GL11.GL_TRUE, unmapped(GL44.GL_BUFFER_IMMUTABLE_STORAGE, 64, GL15.GL_DYNAMIC_DRAW, flags)); + assertEquals(flags, unmapped(GL44.GL_BUFFER_STORAGE_FLAGS, 64, GL15.GL_DYNAMIC_DRAW, flags)); + assertEquals(GL15.GL_DYNAMIC_DRAW, unmapped(GL15.GL_BUFFER_USAGE, 64, GL15.GL_DYNAMIC_DRAW, flags)); + } + + @Test + void bufferStorageWithZeroFlags_isStillImmutable() { + assertEquals(GL11.GL_TRUE, unmapped(GL44.GL_BUFFER_IMMUTABLE_STORAGE, 64, GL15.GL_DYNAMIC_DRAW, 0)); + assertEquals(0, unmapped(GL44.GL_BUFFER_STORAGE_FLAGS, 64, GL15.GL_DYNAMIC_DRAW, 0)); + } + + @Test + void mappedBuffer_reportsRangeAndAccess() { + final int access = GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_FLUSH_EXPLICIT_BIT; + assertEquals(GL11.GL_TRUE, BufferParams.resolve(GL15.GL_BUFFER_MAPPED, 512, GL15.GL_STATIC_DRAW, -1, true, access, 128, 64)); + assertEquals(access, BufferParams.resolve(GL30.GL_BUFFER_ACCESS_FLAGS, 512, GL15.GL_STATIC_DRAW, -1, true, access, 128, 64)); + assertEquals(128, BufferParams.resolve(GL30.GL_BUFFER_MAP_OFFSET, 512, GL15.GL_STATIC_DRAW, -1, true, access, 128, 64)); + assertEquals(64, BufferParams.resolve(GL30.GL_BUFFER_MAP_LENGTH, 512, GL15.GL_STATIC_DRAW, -1, true, access, 128, 64)); + assertEquals(GL15.GL_WRITE_ONLY, BufferParams.resolve(GL15.GL_BUFFER_ACCESS, 512, GL15.GL_STATIC_DRAW, -1, true, access, 128, 64)); + } + + @Test + void unmappedBuffer_ignoresLeftoverMapFields() { + final int access = GL30.GL_MAP_READ_BIT; + assertEquals(0, BufferParams.resolve(GL30.GL_BUFFER_ACCESS_FLAGS, 512, GL15.GL_STATIC_DRAW, -1, false, access, 128, 64)); + assertEquals(0, BufferParams.resolve(GL30.GL_BUFFER_MAP_OFFSET, 512, GL15.GL_STATIC_DRAW, -1, false, access, 128, 64)); + assertEquals(0, BufferParams.resolve(GL30.GL_BUFFER_MAP_LENGTH, 512, GL15.GL_STATIC_DRAW, -1, false, access, 128, 64)); + assertEquals(GL15.GL_READ_WRITE, BufferParams.resolve(GL15.GL_BUFFER_ACCESS, 512, GL15.GL_STATIC_DRAW, -1, false, access, 128, 64)); + } + + @Test + void accessEnumToBits_doesNotAliasOntoInvalidateBit() { + assertEquals(GL30.GL_MAP_READ_BIT, BufferParams.accessEnumToBits(GL15.GL_READ_ONLY)); + assertEquals(GL30.GL_MAP_WRITE_BIT, BufferParams.accessEnumToBits(GL15.GL_WRITE_ONLY)); + assertEquals(GL30.GL_MAP_READ_BIT | GL30.GL_MAP_WRITE_BIT, + BufferParams.accessEnumToBits(GL15.GL_READ_WRITE)); + + for (int access : new int[] { GL15.GL_READ_ONLY, GL15.GL_WRITE_ONLY, GL15.GL_READ_WRITE }) { + assertTrue((access & GL30.GL_MAP_INVALIDATE_BUFFER_BIT) != 0, "precondition: raw enum aliases onto the invalidate bit"); + assertEquals(0, BufferParams.accessEnumToBits(access) & GL30.GL_MAP_INVALIDATE_BUFFER_BIT); + assertEquals(0, BufferParams.accessEnumToBits(access) & GL44.GL_MAP_PERSISTENT_BIT); + } + } + + @Test + void accessBitsToEnum_followsMapBufferRangeTable() { + assertEquals(GL15.GL_READ_ONLY, BufferParams.accessBitsToEnum(GL30.GL_MAP_READ_BIT)); + assertEquals(GL15.GL_WRITE_ONLY, BufferParams.accessBitsToEnum(GL30.GL_MAP_WRITE_BIT)); + assertEquals(GL15.GL_READ_WRITE, BufferParams.accessBitsToEnum(GL30.GL_MAP_READ_BIT | GL30.GL_MAP_WRITE_BIT)); + assertEquals(GL15.GL_READ_WRITE, BufferParams.accessBitsToEnum(0)); + assertEquals(GL15.GL_WRITE_ONLY, BufferParams.accessBitsToEnum(GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_UNSYNCHRONIZED_BIT)); + } + + @Test + void unknownPname_isReportedAndResolvesToZero() { + assertTrue(BufferParams.isUnknownPname(GL11.GL_TEXTURE_WIDTH)); + assertEquals(0, unmapped(GL11.GL_TEXTURE_WIDTH, 1000, GL15.GL_STREAM_DRAW, 0)); + + assertFalse(BufferParams.isUnknownPname(GL15.GL_BUFFER_SIZE)); + assertFalse(BufferParams.isUnknownPname(GL15.GL_BUFFER_USAGE)); + assertFalse(BufferParams.isUnknownPname(GL15.GL_BUFFER_ACCESS)); + assertFalse(BufferParams.isUnknownPname(GL15.GL_BUFFER_MAPPED)); + assertFalse(BufferParams.isUnknownPname(GL30.GL_BUFFER_ACCESS_FLAGS)); + assertFalse(BufferParams.isUnknownPname(GL30.GL_BUFFER_MAP_OFFSET)); + assertFalse(BufferParams.isUnknownPname(GL30.GL_BUFFER_MAP_LENGTH)); + assertFalse(BufferParams.isUnknownPname(GL44.GL_BUFFER_IMMUTABLE_STORAGE)); + assertFalse(BufferParams.isUnknownPname(GL44.GL_BUFFER_STORAGE_FLAGS)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferSizeGpuExactnessTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferSizeGpuExactnessTest.java new file mode 100644 index 000000000..35a97cdff --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/BufferSizeGpuExactnessTest.java @@ -0,0 +1,84 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL15; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BufferSizeGpuExactnessTest { + + private static Device device; + private static ResourceManager resourceManager; + private static long sdlDevice; + + @BeforeAll + static void setUp() throws Exception { + final SdlTestRig rig = SdlTestRig.acquireRealDevice(); + device = rig.device; + resourceManager = rig.resourceManager; + } + + @AfterAll + static void tearDown() { + if (resourceManager != null) resourceManager.shutdown(); + SdlTestRig.releaseRealDevice(); + } + + @Test + void subBucketSize_reportsRequestedNotBucketed() { + final int glId = 9001; + final long handle = resourceManager.createBuffer(glId, FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER), 1000); + assertNotEquals(0L, handle, "buffer creation failed"); + assertEquals(1000L, resourceManager.getBufferSize(glId)); + resourceManager.deleteBuffer(glId); + } + + @Test + void bucketBoundarySize_isUnchanged() { + final int glId = 9002; + resourceManager.createBuffer(glId, FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER), 4096); + assertEquals(4096L, resourceManager.getBufferSize(glId)); + resourceManager.deleteBuffer(glId); + } + + @Test + void freshStore_reportsUndefinedContents() { + final int glId = 9005; + resourceManager.createBuffer(glId, FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER), 1000); + assertTrue(resourceManager.hasUndefinedContents(glId)); + resourceManager.deleteBuffer(glId); + } + + @Test + void recycledStore_reportsUndefinedContents() { + final int usage = FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER); + final int first = 9006; + resourceManager.createBuffer(first, usage, 1000); + resourceManager.markBufferContentsDefined(first); + resourceManager.deleteBuffer(first); + + final int second = 9007; + resourceManager.createBuffer(second, usage, 1000); + assertTrue(resourceManager.hasUndefinedContents(second)); + resourceManager.deleteBuffer(second); + } + + @Test + void pooledReuse_afterSubBucketDelete_keepsExactSize() { + final int usage = FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER); + final int first = 9003; + resourceManager.createBuffer(first, usage, 1000); + resourceManager.deleteBuffer(first); + + final int second = 9004; + resourceManager.createBuffer(second, usage, 3000); + assertEquals(3000L, resourceManager.getBufferSize(second)); + resourceManager.deleteBuffer(second); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ClearTexImageFormatTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ClearTexImageFormatTest.java new file mode 100644 index 000000000..7dd4d2218 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ClearTexImageFormatTest.java @@ -0,0 +1,37 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.sdl.SDLGPU.*; + +class ClearTexImageFormatTest { + + @Test + void unsignedIntegerFormatsUseTheComputeClear() { + assertTrue(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R8_UINT)); + assertTrue(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R16_UINT), "voxel_img / wsr_img format"); + assertTrue(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R32_UINT)); + assertTrue(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT)); + } + + @Test + void signedFloatAndNormalizedFormatsDoNot() { + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R16_INT), "signed needs iimage3D"); + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R32_FLOAT)); + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R16_FLOAT)); + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R8_UNORM), "UNORM is not UINT"); + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM)); + assertFalse(PixelOps.isSdlFormatUnsignedInteger(SDL_GPU_TEXTUREFORMAT_D32_FLOAT)); + } + + @Test + void volumeSizingAccountsForDepth() { + final int bpp = PixelOps.sdlFormatTexelBytes(SDL_GPU_TEXTUREFORMAT_R16_UINT); + assertTrue(bpp == 2, "R16_UINT is two bytes per texel, got " + bpp); + final long slice = 512L * 256L * bpp; + final long volume = slice * 512L; + assertTrue(volume / slice == 512, "a depth-aware clear must cover every slice"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyAllMipsVolumeTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyAllMipsVolumeTest.java new file mode 100644 index 000000000..be07a4dbe --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyAllMipsVolumeTest.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CopyAllMipsVolumeTest { + + private record Copy(int level, int layer, int w, int h, int d) {} + + private static java.util.List plan(int glTarget, int width, int height, int depth, int levels) { + final java.util.List out = new java.util.ArrayList<>(); + final boolean volume = glTarget == GL12.GL_TEXTURE_3D; + final int layers = volume ? 1 : Math.max(1, depth); + for (int level = 0; level < Math.max(1, levels); level++) { + final int w = Math.max(1, width >> level); + final int h = Math.max(1, height >> level); + final int d = volume ? Math.max(1, depth >> level) : 1; + for (int layer = 0; layer < layers; layer++) out.add(new Copy(level, layer, w, h, d)); + } + return out; + } + + @Test + void volumeTextureIsCopiedAsOneRegionPerLevel() { + final var copies = plan(GL12.GL_TEXTURE_3D, 512, 256, 512, 1); + assertEquals(1, copies.size(), "a 3D texture is one copy per mip, not one per depth slice"); + assertEquals(0, copies.get(0).layer(), "slice must stay 0; Metal rejects anything else on a 3D texture"); + assertEquals(512, copies.get(0).d(), "the whole depth must be copied"); + } + + @Test + void arrayTextureStillCopiesPerLayer() { + final var copies = plan(GL11.GL_TEXTURE_2D, 64, 64, 6, 1); + assertEquals(6, copies.size(), "non-volume targets keep per-layer copies"); + for (Copy c : copies) assertEquals(1, c.d(), "layered copies stay one slice deep"); + } + + @Test + void volumeDepthShrinksWithMipLevel() { + final var copies = plan(GL12.GL_TEXTURE_3D, 512, 256, 512, 3); + assertEquals(3, copies.size()); + assertEquals(512, copies.get(0).d()); + assertEquals(256, copies.get(1).d()); + assertEquals(128, copies.get(2).d()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyMappedFromDataBoundsTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyMappedFromDataBoundsTest.java new file mode 100644 index 000000000..8bde957af --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CopyMappedFromDataBoundsTest.java @@ -0,0 +1,69 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CopyMappedFromDataBoundsTest { + + @Test + void throws_whenSizeExceedsDataRemaining() { + final ByteBuffer mapped = MemoryUtil.memAlloc(64); + final ByteBuffer data = MemoryUtil.memAlloc(32); + try { + assertThrows(IllegalStateException.class, + () -> ResourceManager.copyMappedFromData(mapped, data, 64, 1)); + } finally { + MemoryUtil.memFree(mapped); + MemoryUtil.memFree(data); + } + } + + @Test + void throws_whenSizeExceedsMappedCapacityFromPosition() { + final ByteBuffer mapped = MemoryUtil.memAlloc(64); + final ByteBuffer data = MemoryUtil.memAlloc(128); + mapped.position(48); + try { + assertThrows(IllegalStateException.class, + () -> ResourceManager.copyMappedFromData(mapped, data, 32, 1)); + } finally { + MemoryUtil.memFree(mapped); + MemoryUtil.memFree(data); + } + } + + @Test + void throws_onNegativeSize() { + final ByteBuffer mapped = MemoryUtil.memAlloc(16); + final ByteBuffer data = MemoryUtil.memAlloc(16); + try { + assertThrows(IllegalStateException.class, + () -> ResourceManager.copyMappedFromData(mapped, data, -1, 1)); + } finally { + MemoryUtil.memFree(mapped); + MemoryUtil.memFree(data); + } + } + + @Test + void copies_whenWithinBounds() { + final ByteBuffer mapped = MemoryUtil.memAlloc(64); + final ByteBuffer data = MemoryUtil.memAlloc(64); + for (int i = 0; i < 32; i++) data.put(i, (byte) (i + 1)); + try { + ResourceManager.copyMappedFromData(mapped, data, 32, 1); + for (int i = 0; i < 32; i++) { + if (mapped.get(i) != (byte) (i + 1)) { + throw new AssertionError("byte " + i + " mismatch"); + } + } + } finally { + MemoryUtil.memFree(mapped); + MemoryUtil.memFree(data); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CrossThreadUploadCBIsolationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CrossThreadUploadCBIsolationTest.java new file mode 100644 index 000000000..9df20040c --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/CrossThreadUploadCBIsolationTest.java @@ -0,0 +1,111 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicLong; + +import static com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.MAX_PENDING_UPLOAD_BYTES; +import static org.junit.jupiter.api.Assertions.*; + +class CrossThreadUploadCBIsolationTest { + + private static FrameManager newFM() { + return SdlTestRig.frameManager(); + } + + @Test + void differentThreadsHaveDistinctFrameStates() throws Exception { + final FrameManager fm = newFM(); + final FrameManager.FrameState testThreadFs = fm.frame(); + final AtomicReference workerFs = + new AtomicReference<>(); + final Thread t = new Thread(() -> workerFs.set(fm.frame()), "worker-thread"); + t.start(); + t.join(); + assertNotNull(workerFs.get()); + assertNotSame(testThreadFs, workerFs.get(), "each thread must get its own FrameManager.FrameState instance from the FrameManager ThreadLocal"); + } + + @Test + void clientThreadsRecordingsDoNotAppearInSplashThreadsState() throws Exception { + final FrameManager fm = newFM(); + + final CountDownLatch clientRecorded = new CountDownLatch(1); + final AtomicLong clientBytes = new AtomicLong(); + final AtomicBoolean clientShouldFlush = + new AtomicBoolean(); + + final Thread client = new Thread(() -> { + try { + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES + 64, 200); + clientBytes.set(fm.frame().pendingUploadBytes); + clientShouldFlush.set(fm.shouldAutoSubmitPendingUpload()); + } finally { + clientRecorded.countDown(); + } + }, "client-thread-stand-in"); + client.start(); + clientRecorded.await(); + + final AtomicLong splashBytes = new AtomicLong(); + final AtomicInteger splashCommands = + new AtomicInteger(); + final AtomicBoolean splashShouldFlush = + new AtomicBoolean(); + final Thread splash = new Thread(() -> { + splashBytes.set(fm.frame().pendingUploadBytes); + splashCommands.set(fm.frame().pendingUploadCommands); + splashShouldFlush.set(fm.shouldAutoSubmitPendingUpload()); + }, "splash-thread-stand-in"); + splash.start(); + splash.join(); + + assertTrue(clientBytes.get() > MAX_PENDING_UPLOAD_BYTES); + assertTrue(clientShouldFlush.get()); + + assertEquals(0L, splashBytes.get(), "splash thread's pendingUploadBytes must be 0 even though client recorded over threshold"); + assertEquals(0, splashCommands.get()); + assertFalse(splashShouldFlush.get(), "splash thread's shouldAutoSubmitPendingUpload must be false"); + } + + @Test + void perThreadFrameStateBatchFieldsAreIndependent() throws Exception { + final FrameManager fm = newFM(); + + final CountDownLatch workerSeeded = new CountDownLatch(1); + final AtomicInteger workerListSize = + new AtomicInteger(); + final Thread worker = new Thread(() -> { + try { + final FrameManager.FrameState f = fm.frame(); + f.pendingTexHandles.add(1L); + f.pendingTexX.add(0); + f.pendingTexY.add(0); + f.pendingTexW.add(16); + f.pendingTexH.add(16); + f.pendingTexLevels.add(0); + f.pendingTexOffsets.add(0); + f.batchOffset = 1024; + workerListSize.set(f.pendingTexHandles.size()); + } finally { + workerSeeded.countDown(); + } + }, "worker"); + worker.start(); + workerSeeded.await(); + + final FrameManager.FrameState mine = fm.frame(); + assertEquals(1, workerListSize.get(), "worker added one entry to its own list"); + assertTrue(mine.pendingTexHandles.isEmpty(), "test thread's batched-upload list is independent of worker's"); + assertEquals(0, mine.batchOffset); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMapBufferUsageTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMapBufferUsageTest.java new file mode 100644 index 000000000..455572cfb --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FormatMapBufferUsageTest.java @@ -0,0 +1,52 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_INDEX; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_INDIRECT; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_BUFFERUSAGE_VERTEX; + +class FormatMapBufferUsageTest { + + @Test + void geometryTargets_shareVertexAndIndexUsage() { + final int expected = SDL_GPU_BUFFERUSAGE_VERTEX | SDL_GPU_BUFFERUSAGE_INDEX | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ; + assertEquals(expected, FormatMap.mapBufferUsage(GL15.GL_ARRAY_BUFFER)); + assertEquals(expected, FormatMap.mapBufferUsage(GL15.GL_ELEMENT_ARRAY_BUFFER)); + } + + @Test + void storageBufferTarget_hasNoVertexUsage() { + assertEquals(0, FormatMap.mapBufferUsage(GL43.GL_SHADER_STORAGE_BUFFER) & SDL_GPU_BUFFERUSAGE_VERTEX); + } + + @Test + void drawIndirectBufferTarget_singleIndirectFlag() { + assertEquals(SDL_GPU_BUFFERUSAGE_INDIRECT, FormatMap.mapBufferUsage(GL40.GL_DRAW_INDIRECT_BUFFER)); + } + + @Test + void unknownTarget_multiFlagFallback() { + final int expected = SDL_GPU_BUFFERUSAGE_VERTEX | SDL_GPU_BUFFERUSAGE_INDEX | SDL_GPU_BUFFERUSAGE_INDIRECT; + assertEquals(expected, FormatMap.mapBufferUsage(0)); + } + + @Test + void uniformAndStorageBufferTargets_preserved() { + assertEquals(SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ, FormatMap.mapBufferUsage(GL31.GL_UNIFORM_BUFFER)); + + final int ssbo = SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ + | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ + | SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE + | SDL_GPU_BUFFERUSAGE_INDIRECT; + assertEquals(ssbo, FormatMap.mapBufferUsage(GL43.GL_SHADER_STORAGE_BUFFER)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FullCoverageClearDiscardTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FullCoverageClearDiscardTest.java new file mode 100644 index 000000000..44712bb76 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/FullCoverageClearDiscardTest.java @@ -0,0 +1,101 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + +class FullCoverageClearDiscardTest { + + private static final long HANDLE = 0xABCDL; + private static final int W = 1024; + private static final int H = 1024; + + private static FBOClearTracker tracker() { + final SdlTestRig rig = SdlTestRig.create(); + return new FBOClearTracker(rig.frameManager, rig.resourceManager, null); + } + + private static ResourceManager.TextureMeta meta() { + return new ResourceManager.TextureMeta(0, 0, SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, W, H, 1, 1, 0); + } + + @Test + void fullTargetColorBlitDropsThePendingClear() { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingColorClear(st, HANDLE, 1f, 0f, 0f, 1f); + + assertTrue(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, meta())); + assertFalse(st.pendingColorTextures.contains(HANDLE), "pending clear must be dropped, not left queued"); + assertFalse(st.pendingColorValues.containsKey(HANDLE)); + assertTrue(st.clearedTexturesThisFrame.contains(HANDLE), "the overwrite counts as the clear"); + } + + @Test + void fullTargetDepthBlitDropsThePendingClear() { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingDepthClear(st, HANDLE, 1f); + + assertTrue(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, meta())); + assertFalse(st.pendingDepthTextures.contains(HANDLE)); + assertTrue(st.clearedTexturesThisFrame.contains(HANDLE)); + } + + @Test + void partialCoverageKeepsTheClear() { + final int[][] partial = { + { 0, 0, 0, W / 2, H }, // narrower + { 0, 0, 0, W, H / 2 }, // shorter + { 1, 0, 0, W, H }, // offset x + { 0, 1, 0, W, H }, // offset y + { 0, 0, 1, W, H }, // not level 0 + }; + for (int[] c : partial) { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingColorClear(st, HANDLE, 1f, 0f, 0f, 1f); + assertFalse(tracker().discardPendingClearIfFullyCovered(st, HANDLE, c[0], c[1], c[2], c[3], c[4], meta()), + "x=" + c[0] + " y=" + c[1] + " level=" + c[2] + " w=" + c[3] + " h=" + c[4]); + assertTrue(st.pendingColorTextures.contains(HANDLE), "the clear must survive a partial overwrite"); + } + } + + @Test + void volumeTextureKeepsTheClear() { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingColorClear(st, HANDLE, 1f, 0f, 0f, 1f); + final ResourceManager.TextureMeta volume = new ResourceManager.TextureMeta(0, 0, SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, W, H, 4, 1, 0); + assertFalse(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, volume), + "one slice of a volume is not full coverage"); + assertTrue(st.pendingColorTextures.contains(HANDLE)); + } + + @Test + void noPendingClearIsNotAnOverwriteClaim() { + final ContextState st = new ContextState(); + assertFalse(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, meta())); + assertFalse(st.clearedTexturesThisFrame.contains(HANDLE)); + } + + @Test + void missingMetaFallsBackToMaterializing() { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingColorClear(st, HANDLE, 1f, 0f, 0f, 1f); + assertFalse(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, null)); + assertTrue(st.pendingColorTextures.contains(HANDLE)); + } + + @Test + void discardBumpsMutationGenSoSamplerFlushReevaluates() { + final ContextState st = new ContextState(); + FBOClearTracker.recordPendingColorClear(st, HANDLE, 1f, 0f, 0f, 1f); + FBOClearTracker.snapshotFlushGenerations(st); + final int before = st.pendingMutationGen; + + assertTrue(tracker().discardPendingClearIfFullyCovered(st, HANDLE, 0, 0, 0, W, H, meta())); + assertEquals(before + 1, st.pendingMutationGen); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSyncDirtyGateTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSyncDirtyGateTest.java new file mode 100644 index 000000000..34ef7b726 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentBufferSyncDirtyGateTest.java @@ -0,0 +1,313 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PersistentBufferSyncDirtyGateTest { + + private static final class CountingSink implements PersistentBufferSync.UploadSink { + int enqueued; + long seq; + @Override public void enqueue(TransferThread.DeferredUpload upload) { enqueued++; } + @Override public long nextSeq() { return ++seq; } + } + + @Test + void gateStaysClosedUntilAWriteMarksARegionDirty() { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final CountingSink sink = new CountingSink(); + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, sink); + + final ByteBuffer staging = MemoryUtil.memCalloc(64); + try { + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 64, 0); + + assertFalse(rm.hasDirtyPersistentRegions(), "a mapping with no writes is not dirty"); + sync.enqueueDirtyPersistentRegions(); + assertEquals(0, sink.enqueued, "clean mappings must not be snapshotted or enqueued"); + + sync.onPersistentBufferWrite(1, 0, 16); + assertTrue(rm.hasDirtyPersistentRegions()); + sync.enqueueDirtyPersistentRegions(); + assertEquals(1, sink.enqueued); + + assertFalse(rm.hasDirtyPersistentRegions(), "the flush clears the gate"); + sync.enqueueDirtyPersistentRegions(); + assertEquals(1, sink.enqueued, "no second enqueue without a further write"); + } finally { + MemoryUtil.memFree(staging); + } + } + + @Test + void widenAndRemoveKeepTheCountExact() { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, new CountingSink()); + + final ByteBuffer staging = MemoryUtil.memCalloc(64); + try { + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 64, 0); + + sync.onPersistentBufferWrite(1, 0, 16); + sync.onPersistentBufferWrite(1, 16, 16); + assertTrue(rm.hasDirtyPersistentRegions()); + + rm.removePersistentMapping(1); + assertFalse(rm.hasDirtyPersistentRegions()); + } finally { + MemoryUtil.memFree(staging); + } + } + + @Test + void mappingsVersionMovesOnlyWhenTheMapChanges() { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + + final ByteBuffer staging = MemoryUtil.memCalloc(64); + try { + final int atStart = rm.getMappingsVersion(); + + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + final int afterPut = rm.getMappingsVersion(); + assertNotEquals(atStart, afterPut, "adding a mapping must move the version"); + + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 64, 0); + assertEquals(afterPut, rm.getMappingsVersion(), "recording a buffer is not a mapping change"); + + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, new CountingSink()); + sync.onPersistentBufferWrite(1, 0, 16); + sync.enqueueDirtyPersistentRegions(); + assertEquals(afterPut, rm.getMappingsVersion(), "dirtying and draining is not a mapping change"); + + rm.swapPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + final int afterSwap = rm.getMappingsVersion(); + assertNotEquals(afterPut, afterSwap, "swapping a mapping must move the version"); + + rm.removePersistentMapping(1); + assertNotEquals(afterSwap, rm.getMappingsVersion(), "removing a mapping must move the version"); + } finally { + MemoryUtil.memFree(staging); + } + } + + @Test + void repeatedDrainsKeepUploadingWhenTheMappingSetIsUnchanged() { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final CountingSink sink = new CountingSink(); + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, sink); + + final ByteBuffer staging = MemoryUtil.memCalloc(256); + try { + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 256, 0); + + for (int i = 0; i < 10; i++) { + sync.onPersistentBufferWrite(1, i * 16, 16); + sync.enqueueDirtyPersistentRegions(); + assertEquals(i + 1, sink.enqueued, + "every dirty region must upload, not just the one before the snapshot was cached"); + } + } finally { + rm.removePersistentMapping(1); + MemoryUtil.memFree(staging); + } + } + + @Test + void aReplacedMappingIsPickedUpByALaterDrain() { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final CountingSink sink = new CountingSink(); + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, sink); + + final ByteBuffer first = MemoryUtil.memCalloc(64); + final ByteBuffer second = MemoryUtil.memCalloc(64); + try { + rm.putPersistentMapping(1, new PersistentMapping(first, 0L, first.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 64, 0); + sync.onPersistentBufferWrite(1, 0, 16); + sync.enqueueDirtyPersistentRegions(); + assertEquals(1, sink.enqueued); + + rm.swapPersistentMapping(1, new PersistentMapping(second, 0L, second.capacity(), 0)); + sync.onPersistentBufferWrite(1, 0, 16); + sync.enqueueDirtyPersistentRegions(); + assertEquals(2, sink.enqueued, "the drain must see the replacement, not a stale snapshot"); + } finally { + rm.removePersistentMapping(1); + MemoryUtil.memFree(first); + MemoryUtil.memFree(second); + } + } + + @Test + void concurrentWritesAndDrainsLeaveTheGateExact() throws Exception { + final SdlTestRig rig = SdlTestRig.create(); + final Device device = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final CountingSink sink = new CountingSink(); + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, sink); + + final ByteBuffer staging = MemoryUtil.memCalloc(4096); + try { + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 4096, 0); + + final int writers = 6; + final int rounds = 4000; + final AtomicReference error = new AtomicReference<>(); + final CountDownLatch start = new CountDownLatch(1); + final Thread[] threads = new Thread[writers + 1]; + final AtomicBoolean stop = new AtomicBoolean(); + + for (int w = 0; w < writers; w++) { + final int id = w; + threads[w] = new Thread(() -> { + try { + start.await(); + for (int i = 0; i < rounds; i++) sync.onPersistentBufferWrite(1, (id * 32L + i) % 2048, 16); + } catch (Throwable t) { error.set(t); } + }, "writer-" + id); + } + threads[writers] = new Thread(() -> { + try { + start.await(); + while (!stop.get()) sync.enqueueDirtyPersistentRegions(); + } catch (Throwable t) { error.set(t); } + }, "drainer"); + + for (Thread t : threads) t.start(); + start.countDown(); + for (int w = 0; w < writers; w++) threads[w].join(30_000); + stop.set(true); + threads[writers].join(30_000); + + if (error.get() != null) throw new AssertionError("worker crashed", error.get()); + + sync.enqueueDirtyPersistentRegions(); + assertFalse(rm.hasDirtyPersistentRegions(), "gate must settle back to zero, not drift"); + } finally { + rm.removePersistentMapping(1); + MemoryUtil.memFree(staging); + } + } + + @Test + void deferEnqueueStampsLastEnqueuedSeq() { + final SdlTestRig rig = SdlTestRig.create(); + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + + final ByteBuffer staging = MemoryUtil.memCalloc(64); + try { + final PersistentMapping pm = new PersistentMapping(staging, 0L, staging.capacity(), 0); + rm.putPersistentMapping(1, pm); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, 64, 0); + + final long[] stampAtEnqueue = {-1L}; + final long[] uploadSeq = {-1L}; + final long[] nextSeq = {42L}; + final PersistentBufferSync sync = new PersistentBufferSync(fm, rm, new PersistentBufferSync.UploadSink() { + @Override public void enqueue(TransferThread.DeferredUpload upload) { + uploadSeq[0] = upload.seq(); + stampAtEnqueue[0] = pm.lastEnqueuedSeq; + } + @Override public long nextSeq() { return ++nextSeq[0]; } + }); + + sync.onPersistentBufferWrite(1, 0, 16); + sync.enqueueDirtyPersistentRegions(); + + assertEquals(43L, uploadSeq[0]); + assertEquals(43L, stampAtEnqueue[0], "stamp must be visible at the moment of enqueue"); + assertEquals(43L, pm.lastEnqueuedSeq); + } finally { + MemoryUtil.memFree(staging); + } + } + + @Test + void snapshotIterationIsStableUnderConcurrentMutation() throws Exception { + final ResourceManager rm = SdlTestRig.resourceManager(); + + final int seedCount = 100; + for (int i = 0; i < seedCount; i++) { + final ByteBuffer b = MemoryUtil.memAlloc(64); + rm.putPersistentMapping(i, new PersistentMapping(b, 0L, b.capacity(), 0)); + } + + final AtomicBoolean stop = new AtomicBoolean(false); + final AtomicBoolean violation = new AtomicBoolean(false); + final CountDownLatch mutatorStarted = new CountDownLatch(1); + + final Thread mutator = new Thread(() -> { + mutatorStarted.countDown(); + int next = seedCount; + while (!stop.get()) { + final ByteBuffer b = MemoryUtil.memAlloc(64); + rm.putPersistentMapping(next, new PersistentMapping(b, 0L, b.capacity(), 0)); + rm.removePersistentMapping(next - 50); + next++; + if (next > seedCount + 10000) next = seedCount; + } + }, "mutator"); + mutator.start(); + mutatorStarted.await(); + + final IntArrayList keys = new IntArrayList(); + final ArrayList vals = new ArrayList<>(); + try { + for (int round = 0; round < 200; round++) { + rm.snapshotPersistentMappingsInto(keys, vals); + final int n = keys.size(); + for (int i = 0; i < n; i++) { + if (vals.get(i) == null) violation.set(true); + } + } + } finally { + stop.set(true); + mutator.join(2000); + } + + assertFalse(violation.get(), "snapshot must contain only valid entries"); + + for (int i = 0; i < seedCount; i++) { + final PersistentMapping pm = rm.removePersistentMapping(i); + if (pm != null) MemoryUtil.memFree(pm.staging); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentDrainBoundaryTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentDrainBoundaryTest.java new file mode 100644 index 000000000..94e066234 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentDrainBoundaryTest.java @@ -0,0 +1,104 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class PersistentDrainBoundaryTest { + + private static final class RecordingSink implements PersistentBufferSync.UploadSink { + final LongArrayList offsets = new LongArrayList(); + final LongArrayList sizes = new LongArrayList(); + long seq; + + @Override public void enqueue(TransferThread.DeferredUpload upload) { + final TransferThread.StagingReadUpload u = (TransferThread.StagingReadUpload) upload; + offsets.add(u.srcOffset); + sizes.add(u.size); + } + + @Override public long nextSeq() { return ++seq; } + + long totalBytes() { + long sum = 0; + for (int i = 0; i < sizes.size(); i++) sum += sizes.getLong(i); + return sum; + } + } + + private static final class Fixture implements AutoCloseable { + final ResourceManager rm; + final PersistentBufferSync sync; + final RecordingSink sink = new RecordingSink(); + final ByteBuffer staging = MemoryUtil.memCalloc(4096); + + Fixture() { + final SdlTestRig rig = SdlTestRig.create(); + rm = rig.resourceManager; + sync = new PersistentBufferSync(rig.frameManager, rm, sink); + rm.putPersistentMapping(1, new PersistentMapping(staging, 0L, staging.capacity(), 0)); + SdlReflect.recordBuffer(rm, 1, 0xCAFEBABEL, staging.capacity(), 0); + } + + @Override public void close() { + rm.removePersistentMapping(1); + MemoryUtil.memFree(staging); + } + } + + @Test + void oneDrainCoversEveryRangeDirtiedSinceTheLastDrain() { + try (Fixture f = new Fixture()) { + for (int i = 0; i < 64; i++) f.sync.onPersistentBufferWrite(1, i * 188L, 188L); + f.sync.enqueueDirtyPersistentRegions(); + + assertEquals(1, f.sink.offsets.size(), "contiguous writes drain as a single upload"); + assertEquals(0L, f.sink.offsets.getLong(0)); + assertEquals(64L * 188L, f.sink.sizes.getLong(0), "the union spans every byte written since the last drain"); + assertFalse(f.rm.hasDirtyPersistentRegions()); + } + } + + @Test + void theAccumulatedUnionMatchesThePerDrawSum() { + final long batched; + try (Fixture f = new Fixture()) { + for (int i = 0; i < 64; i++) f.sync.onPersistentBufferWrite(1, i * 188L, 188L); + f.sync.enqueueDirtyPersistentRegions(); + batched = f.sink.totalBytes(); + } + try (Fixture f = new Fixture()) { + for (int i = 0; i < 64; i++) { + f.sync.onPersistentBufferWrite(1, i * 188L, 188L); + f.sync.enqueueDirtyPersistentRegions(); + } + assertEquals(64, f.sink.offsets.size(), "the per-draw drain enqueues once per write"); + assertEquals(f.sink.totalBytes(), batched, "batching changes the enqueue count, not the bytes"); + } + } + + @Test + void aLaterDrainPicksUpWritesMadeSinceTheBoundary() { + try (Fixture f = new Fixture()) { + f.sync.onPersistentBufferWrite(1, 0L, 16L); + f.sync.enqueueDirtyPersistentRegions(); + assertEquals(1, f.sink.offsets.size()); + + f.sync.onPersistentBufferWrite(1, 512L, 16L); + f.sync.onPersistentBufferWrite(1, 1024L, 16L); + f.sync.enqueueDirtyPersistentRegions(); + + assertEquals(2, f.sink.offsets.size()); + assertEquals(512L, f.sink.offsets.getLong(1), "the union starts at the first byte dirtied after the boundary"); + assertEquals(528L, f.sink.sizes.getLong(1), "and spans through the last one"); + assertFalse(f.rm.hasDirtyPersistentRegions(), "no dirty bytes survive a drain"); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMappingDirtyRangeTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMappingDirtyRangeTest.java new file mode 100644 index 000000000..910f855f3 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/PersistentMappingDirtyRangeTest.java @@ -0,0 +1,154 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PersistentMappingDirtyRangeTest { + + private static PersistentMapping mapping(int capacity) { + final ByteBuffer staging = MemoryUtil.memCalloc(capacity); + return new PersistentMapping(staging, 0L, capacity, 0); + } + + private static void free(PersistentMapping pm) { + MemoryUtil.memFree(pm.staging); + } + + @Test + void firstWriteTransitionsAndReportsItsRange() { + final PersistentMapping pm = mapping(256); + try { + assertFalse(pm.isDirty(), "a fresh mapping is clean"); + assertTrue(pm.markDirty(16, 32), "the clean -> dirty edge is reported once"); + assertTrue(pm.isDirty()); + + final long claimed = pm.claimDirty(); + assertFalse(PersistentMapping.isClean(claimed)); + assertEquals(16, PersistentMapping.rangeOffset(claimed)); + assertEquals(32, PersistentMapping.rangeSize(claimed)); + assertFalse(pm.isDirty(), "claiming leaves the mapping clean"); + } finally { + free(pm); + } + } + + @Test + void widensWithoutRepeatingTheTransition() { + final PersistentMapping pm = mapping(256); + try { + assertTrue(pm.markDirty(64, 16)); + assertFalse(pm.markDirty(16, 16), "already dirty, so no second transition"); + assertFalse(pm.markDirty(128, 32), "still no second transition"); + + final long claimed = pm.claimDirty(); + assertEquals(16, PersistentMapping.rangeOffset(claimed), "union takes the lowest offset"); + assertEquals(144, PersistentMapping.rangeSize(claimed), "union runs to the highest end"); + } finally { + free(pm); + } + } + + @Test + void rewritingTheSameRangeIsNotATransition() { + final PersistentMapping pm = mapping(256); + try { + assertTrue(pm.markDirty(0, 64)); + assertFalse(pm.markDirty(0, 64)); + assertFalse(pm.markDirty(8, 8), "a contained range does not widen the window"); + assertEquals(64, PersistentMapping.rangeSize(pm.claimDirty())); + } finally { + free(pm); + } + } + + @Test + void zeroSizedWriteIsNotDirty() { + final PersistentMapping pm = mapping(256); + try { + assertFalse(pm.markDirty(32, 0)); + assertFalse(pm.isDirty()); + assertTrue(PersistentMapping.isClean(pm.claimDirty())); + } finally { + free(pm); + } + } + + @Test + void claimIsExclusive() { + final PersistentMapping pm = mapping(256); + try { + pm.markDirty(0, 8); + assertFalse(PersistentMapping.isClean(pm.claimDirty()), "first claim wins"); + assertTrue(PersistentMapping.isClean(pm.claimDirty()), "second claim gets nothing"); + } finally { + free(pm); + } + } + + @Test + void concurrentWritersProduceExactlyOneTransitionPerClaim() throws Exception { + final PersistentMapping pm = mapping(4096); + final int writers = 8; + final int rounds = 5000; + final AtomicInteger transitions = new AtomicInteger(); + final AtomicInteger claims = new AtomicInteger(); + final AtomicReference error = new AtomicReference<>(); + final CountDownLatch start = new CountDownLatch(1); + final Thread[] threads = new Thread[writers + 1]; + + try { + for (int w = 0; w < writers; w++) { + final int id = w; + threads[w] = new Thread(() -> { + try { + start.await(); + for (int i = 0; i < rounds; i++) { + if (pm.markDirty((id * 64L + i) % 2048, 16)) transitions.incrementAndGet(); + } + } catch (Throwable t) { error.set(t); } + }, "writer-" + id); + } + threads[writers] = new Thread(() -> { + try { + start.await(); + for (int i = 0; i < rounds * writers; i++) { + if (!PersistentMapping.isClean(pm.claimDirty())) claims.incrementAndGet(); + } + } catch (Throwable t) { error.set(t); } + }, "claimer"); + + for (Thread t : threads) t.start(); + start.countDown(); + for (Thread t : threads) t.join(30_000); + + if (error.get() != null) throw new AssertionError("worker crashed", error.get()); + + if (!PersistentMapping.isClean(pm.claimDirty())) claims.incrementAndGet(); + assertEquals(transitions.get(), claims.get(), "every clean -> dirty transition must be claimed exactly once"); + } finally { + free(pm); + } + } + + @Test + void rangeSurvivesOffsetsNearTheIntCeiling() { + final PersistentMapping pm = mapping(64); + try { + assertTrue(pm.markDirty(0x7FFFFF00L, 0x40L)); + final long claimed = pm.claimDirty(); + assertEquals(0x7FFFFF00L, PersistentMapping.rangeOffset(claimed)); + assertEquals(0x40L, PersistentMapping.rangeSize(claimed)); + } finally { + free(pm); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadowsTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadowsTest.java new file mode 100644 index 000000000..bd83c01d0 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReadbackShadowsTest.java @@ -0,0 +1,65 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ReadbackShadowsTest { + + private static final long SENTINEL_HANDLE = 0xBEEFL; + + private static ReadbackShadows shadows() { + return new ReadbackShadows(null); + } + + private static ByteBuffer out(int bytes) { + return ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()); + } + + @Test + void serveRefusesAStaleSlot() { + final ReadbackShadows shadows = shadows(); + SdlReflect.putReadbackSlot(shadows, 7, 0, SENTINEL_HANDLE, 64, false); + + assertFalse(shadows.serve(7, 0, out(64), 64), + "a slot invalidated by a GPU-to-GPU write must not be served as if it were downloaded"); + } + + @Test + void serveRefusesAnUnknownSlot() { + final ReadbackShadows shadows = shadows(); + SdlReflect.putReadbackSlot(shadows, 7, 0, SENTINEL_HANDLE, 64, true); + + assertFalse(shadows.serve(7, 64, out(64), 64), "a different ring offset is a different slot"); + assertFalse(shadows.serve(8, 0, out(64), 64), "a different buffer is a different slot"); + } + + @Test + void invalidateTouchesOnlyItsOwnSlot() { + final ReadbackShadows shadows = shadows(); + SdlReflect.putReadbackSlot(shadows, 7, 0, SENTINEL_HANDLE, 64, true); + SdlReflect.putReadbackSlot(shadows, 7, 64, SENTINEL_HANDLE, 64, true); + + shadows.invalidate(7, 0); + + assertFalse(shadows.serve(7, 0, out(64), 64), "the invalidated slot is still being served"); + assertTrue(SdlReflect.readbackSlotValid(shadows, 7, 64), "invalidating one ring slot must not disturb the others"); + } + + @Test + void releaseDropsOnlyTheNamedBuffer() { + final ReadbackShadows shadows = shadows(); + SdlReflect.putReadbackSlot(shadows, 7, 0, 0L, 64, true); + SdlReflect.putReadbackSlot(shadows, 7, 64, 0L, 64, true); + SdlReflect.putReadbackSlot(shadows, 8, 0, 0L, 64, true); + + shadows.release(7); + + assertFalse(shadows.hasSlotsFor(7), "deleting a buffer must drop all of its ring slots"); + assertTrue(shadows.hasSlotsFor(8), "deleting one buffer must not drop another's slots"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReleasePersistentStagingTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReleasePersistentStagingTest.java new file mode 100644 index 000000000..d53d3d450 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ReleasePersistentStagingTest.java @@ -0,0 +1,101 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ReleasePersistentStagingTest { + + @Test + void nullPmAndNullStagingNoOp() { + final ResourceManager rm = SdlTestRig.resourceManager(); + rm.releasePersistentStaging(null); + rm.releasePersistentStaging(new PersistentMapping(null, 0L, 0L, 0)); + } + + @Test + void noTransferThreadFreesInline() { + final ResourceManager rm = SdlTestRig.resourceManager(); + rm.releasePersistentStaging(new PersistentMapping(MemoryUtil.memAlloc(24), 0L, 24L, 0)); + } + + @Test + void seqAlreadySubmittedFreesInline() { + final SdlTestRig rig = SdlTestRig.create(); + final Device dev = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final TransferThread tt = new TransferThread(dev, rm); + rm.setTransferThread(tt); + try { + final PersistentMapping pm = new PersistentMapping(MemoryUtil.memAlloc(24), 0L, 24L, 0); + pm.lastEnqueuedSeq = 0L; + rm.releasePersistentStaging(pm); + assertEquals(0, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + @Test + void inFlightSeqRoutesToFreeAfterSeq() { + final SdlTestRig rig = SdlTestRig.create(); + final Device dev = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final TransferThread tt = new TransferThread(dev, rm); + rm.setTransferThread(tt); + try { + final PersistentMapping pm = new PersistentMapping(MemoryUtil.memAlloc(24), 0L, 24L, 0); + pm.lastEnqueuedSeq = 50L; + rm.releasePersistentStaging(pm); + assertEquals(1, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + @Test + void deleteBufferReleasesPersistentStaging() { + final ResourceManager rm = SdlTestRig.resourceManager(); + SdlReflect.recordBuffer(rm, 7, 0xDEADBEEFL, 64, 0); + rm.putPersistentMapping(7, new PersistentMapping(MemoryUtil.memCalloc(64), 0L, 64L, 0)); + + rm.deleteBuffer(7); + + assertNull(rm.getPersistentMapping(7)); + } + + @Test + void deleteBufferDefersFreeWhenSeqInFlight() { + final SdlTestRig rig = SdlTestRig.create(); + final Device dev = rig.device; + final FrameManager fm = rig.frameManager; + final ResourceManager rm = rig.resourceManager; + final TransferThread tt = new TransferThread(dev, rm); + rm.setTransferThread(tt); + try { + final ByteBuffer staging = MemoryUtil.memCalloc(64); + final PersistentMapping pm = new PersistentMapping(staging, 0L, staging.capacity(), 0); + pm.lastEnqueuedSeq = 99L; + SdlReflect.recordBuffer(rm, 7, 0xDEADBEEFL, 64, 0); + rm.putPersistentMapping(7, pm); + + rm.deleteBuffer(7); + + assertNull(rm.getPersistentMapping(7)); + assertEquals(1, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + private static void shutdown(TransferThread tt) { + tt.shutdown(); + try { tt.getThread().join(2000); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerConcurrencyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerConcurrencyTest.java new file mode 100644 index 000000000..a94a1de47 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerConcurrencyTest.java @@ -0,0 +1,162 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ResourceManagerConcurrencyTest { + + private interface Body { + void run(int slot) throws Exception; + } + + private static void race(int threads, Body body) throws Exception { + final CountDownLatch start = new CountDownLatch(1); + final AtomicInteger ready = new AtomicInteger(); + final AtomicReference failure = new AtomicReference<>(); + final List pool = new ArrayList<>(threads); + for (int t = 0; t < threads; t++) { + final int slot = t; + final Thread th = new Thread(() -> { + ready.incrementAndGet(); + try { + start.await(); + body.run(slot); + } catch (Throwable e) { + failure.compareAndSet(null, e); + } + }, "rm-race-" + t); + pool.add(th); + th.start(); + } + while (ready.get() < threads) Thread.onSpinWait(); + start.countDown(); + for (Thread th : pool) th.join(TimeUnit.SECONDS.toMillis(30)); + for (Thread th : pool) assertFalse(th.isAlive(), "thread " + th.getName() + " still running"); + assertNull(failure.get(), () -> "race or exception: " + failure.get()); + } + + @Test + void genFboId_isUniqueAcrossThreads() throws Exception { + final ResourceManager rm = SdlTestRig.resourceManager(); + final int perThread = 1000; + final int threads = 2; + final int[][] ids = new int[threads][perThread]; + + race(threads, slot -> { + for (int i = 0; i < perThread; i++) ids[slot][i] = rm.genFboId(); + }); + + final Set all = new HashSet<>(threads * perThread); + for (int t = 0; t < threads; t++) for (int id : ids[t]) all.add(id); + assertEquals(threads * perThread, all.size(), "FBO IDs must be globally unique across threads"); + } + + @Test + void getOrCreateTexSamplerState_singleInstanceForRacingCallers() throws Exception { + final ResourceManager rm = SdlTestRig.resourceManager(); + final int n = 8; + final TextureSamplerState[] results = new TextureSamplerState[n]; + + race(n, slot -> results[slot] = rm.getOrCreateTexSamplerState(7)); + + for (int i = 1; i < n; i++) { + assertSame(results[0], results[i], "double-create at slot " + i); + } + } + + @Test + void textureDeleteAndFboCleanupAreAtomic() throws Exception { + final ResourceManager rm = SdlTestRig.resourceManager(); + final int textureId = 42; + final int fboId = rm.genFboId(); + final FboState fbo = rm.createFbo(fboId); + fbo.colorGlIds[0] = textureId; + fbo.colorTextures[0] = 0xDEADBEEFL; + fbo.colorFormats[0] = 1; + + final AtomicBoolean done = new AtomicBoolean(false); + final AtomicBoolean violation = new AtomicBoolean(false); + final CountDownLatch readerStarted = new CountDownLatch(1); + + final Thread reader = new Thread(() -> { + readerStarted.countDown(); + int iters = 0; + while (!done.get() && iters < 5_000_000) { + final FboState f = rm.getFbo(fboId); + if (f != null) { + final boolean idSet = f.colorGlIds[0] == textureId; + final boolean handleSet = f.colorTextures[0] != 0 || f.colorFormats[0] != 0; + if (idSet != handleSet) { + violation.set(true); + return; + } + } + iters++; + } + }, "reader"); + reader.start(); + readerStarted.await(); + + Thread.sleep(10); + rm.deleteTexture(textureId); + Thread.sleep(20); + done.set(true); + reader.join(2000); + + assertFalse(violation.get(), "Reader observed half-cleaned FBO state"); + + final FboState f = rm.getFbo(fboId); + assertEquals(0, f.colorGlIds[0]); + assertEquals(0L, f.colorTextures[0]); + assertEquals(0, f.colorFormats[0]); + } + + @Test + void concurrentCreateLookupDelete_noRaces() throws Exception { + final ResourceManager rm = SdlTestRig.resourceManager(); + final int threads = 8; + final int opsPerThread = 5_000; + final AtomicInteger created = new AtomicInteger(); + + race(threads, slot -> { + final Random rng = new Random(slot); + final List mine = new ArrayList<>(); + for (int i = 0; i < opsPerThread; i++) { + switch (rng.nextInt(3)) { + case 0 -> { + final int id = rm.genFboId(); + rm.createFbo(id); + mine.add(id); + created.incrementAndGet(); + } + case 1 -> { + if (!mine.isEmpty()) rm.getFbo(mine.get(rng.nextInt(mine.size()))); + } + default -> { + if (!mine.isEmpty()) rm.deleteFbo(mine.remove(mine.size() - 1)); + } + } + } + }); + + assertTrue(created.get() >= threads, "each thread should have created at least one FBO"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerFormatMappingTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerFormatMappingTest.java new file mode 100644 index 000000000..457a134fe --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerFormatMappingTest.java @@ -0,0 +1,93 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL21; +import org.lwjgl.opengl.GL30; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +class ResourceManagerFormatMappingTest { + + private static final int D24 = SDL_GPU_TEXTUREFORMAT_D24_UNORM; + private static final int D24S8 = SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT; + + private static int map(int glFormat) { + return ResourceManager.mapTextureFormat(glFormat, D24, D24S8); + } + + @Test + void testRGBA8MapsCorrectly() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(GL11.GL_RGBA8)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(GL11.GL_RGBA)); + } + + @Test + void testRGB8PromotesToRGBA8() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(GL11.GL_RGB8)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(GL11.GL_RGB)); + } + + @Test + void testSRGBAlpha() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, map(GL21.GL_SRGB8_ALPHA8)); + } + + @Test + void testFloatFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT, map(GL30.GL_RGBA16F)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT, map(GL30.GL_RGBA32F)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R16_FLOAT, map(GL30.GL_R16F)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R16G16_FLOAT, map(GL30.GL_RG16F)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R32_FLOAT, map(GL30.GL_R32F)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R32G32_FLOAT, map(GL30.GL_RG32F)); + } + + @Test + void testSingleChannelFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8_UNORM, map(GL30.GL_R8)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8_UNORM, map(GL30.GL_RG8)); + } + + @Test + void testDepthFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_D16_UNORM, map(GL14.GL_DEPTH_COMPONENT16)); + assertEquals(SDL_GPU_TEXTUREFORMAT_D24_UNORM, map(GL14.GL_DEPTH_COMPONENT24)); + assertEquals(SDL_GPU_TEXTUREFORMAT_D32_FLOAT, map(GL30.GL_DEPTH_COMPONENT32F)); + } + + @Test + void testRGBA16MapsToR16G16B16A16Unorm() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R16G16B16A16_UNORM, map(GL11.GL_RGBA16)); + } + + @Test + void testDepthComponent32MapsToD32Float() { + assertEquals(SDL_GPU_TEXTUREFORMAT_D32_FLOAT, map(GL14.GL_DEPTH_COMPONENT32)); + assertNotEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(GL14.GL_DEPTH_COMPONENT32), "must not fall through to the colour-format default on a depth attachment"); + } + + @Test + void testDepthStencilFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, map(GL30.GL_DEPTH24_STENCIL8)); + assertEquals(SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT, map(GL30.GL_DEPTH32F_STENCIL8)); + } + + @Test + void testIntegerFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UINT, map(GL30.GL_RGBA8UI)); + assertEquals(SDL_GPU_TEXTUREFORMAT_R32G32B32A32_UINT, map(GL30.GL_RGBA32UI)); + } + + @Test + void testPackedFormats() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R11G11B10_UFLOAT, map(GL30.GL_R11F_G11F_B10F)); + } + + @Test + void testUnknownFormatFallsBackToRGBA8() { + assertEquals(SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, map(0xDEAD)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerUsageCombinationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerUsageCombinationTest.java new file mode 100644 index 000000000..c0b74c80e --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManagerUsageCombinationTest.java @@ -0,0 +1,50 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.sdl.SDLGPU.*; + +class ResourceManagerUsageCombinationTest { + + @Test + void samplerDropsSimultaneousReadWrite() { + final int merged = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE; + final int out = ResourceManager.reconcileUsage(merged); + assertEquals(0, out & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE, "SDL never returns a simultaneous-RW texture to the sampler default"); + assertNotEquals(0, out & SDL_GPU_TEXTUREUSAGE_SAMPLER); + assertNotEquals(0, out & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET); + } + + @Test + void samplerDropsGraphicsStorageRead() { + final int merged = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ; + final int out = ResourceManager.reconcileUsage(merged); + assertEquals(0, out & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ); + assertNotEquals(0, out & SDL_GPU_TEXTUREUSAGE_SAMPLER); + } + + @Test + void samplerKeepsPlainComputeStorage() { + final int merged = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE; + assertEquals(merged, ResourceManager.reconcileUsage(merged), "SDL transitions plain compute storage symmetrically to and from the sampler default"); + } + + @Test + void withoutSamplerEveryStorageBitSurvives() { + final int merged = SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE; + assertEquals(merged, ResourceManager.reconcileUsage(merged)); + } + + @Test + void plainSampledColourTextureIsUnchanged() { + final int merged = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; + assertEquals(merged, ResourceManager.reconcileUsage(merged)); + } + + @Test + void depthTargetIsUnchanged() { + final int merged = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET; + assertEquals(merged, ResourceManager.reconcileUsage(merged)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SDLGPUFboTargetCacheTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SDLGPUFboTargetCacheTest.java new file mode 100644 index 000000000..d923042da --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SDLGPUFboTargetCacheTest.java @@ -0,0 +1,159 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SDLGPUFboTargetCacheTest { + + @Test + void freshFboState_hasNoColorAndZeroTarget() { + final FboState fbo = new FboState(); + assertTrue(fbo.targetsDirty, "fresh state must compute on first read"); + fbo.recomputeTargets(); + assertFalse(fbo.targetsDirty); + assertFalse(fbo.hasAnyColor); + assertEquals(0L, fbo.primaryTarget); + } + + @Test + void depthOnly_primaryTargetIsDepth() { + final FboState fbo = new FboState(); + fbo.depthTexture = 0xDDDDL; + fbo.recomputeTargets(); + assertFalse(fbo.hasAnyColor); + assertEquals(0xDDDDL, fbo.primaryTarget); + } + + @Test + void singleColor_primaryTargetIsColor() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.depthTexture = 0xDDDDL; + // default drawBuffers = {0} + fbo.recomputeTargets(); + assertTrue(fbo.hasAnyColor); + assertEquals(0xAAAAL, fbo.primaryTarget); + } + + @Test + void disabledDrawBuffer_doesNotCount() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.colorTextures[1] = 0xBBBBL; + fbo.drawBuffers = new int[]{-1, 1}; // GL_NONE then attachment 1 + fbo.depthTexture = 0xDDDDL; + fbo.recomputeTargets(); + assertTrue(fbo.hasAnyColor); + assertEquals(0xBBBBL, fbo.primaryTarget, "first enabled drawBuffer is index 1"); + } + + @Test + void allDrawBuffersDisabled_falsThroughToDepth() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.drawBuffers = new int[]{-1}; + fbo.depthTexture = 0xDDDDL; + fbo.recomputeTargets(); + assertFalse(fbo.hasAnyColor); + assertEquals(0xDDDDL, fbo.primaryTarget); + } + + @Test + void mrtFirstColorWins_evenWhenMultipleAttached() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.colorTextures[1] = 0xBBBBL; + fbo.colorTextures[2] = 0xCCCCL; + fbo.drawBuffers = new int[]{0, 1, 2}; + fbo.recomputeTargets(); + assertTrue(fbo.hasAnyColor); + assertEquals(0xAAAAL, fbo.primaryTarget); + } + + @Test + void emptyDrawBuffers_noColorEvenIfBound() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.drawBuffers = new int[0]; + fbo.depthTexture = 0xDDDDL; + fbo.recomputeTargets(); + assertFalse(fbo.hasAnyColor); + assertEquals(0xDDDDL, fbo.primaryTarget); + } + + @Test + void detachColor_zeroesSlotAndShrinksCount() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; fbo.colorGlIds[0] = 10; fbo.colorFormats[0] = 100; + fbo.colorTextures[1] = 0xBBBBL; fbo.colorGlIds[1] = 11; fbo.colorFormats[1] = 101; + fbo.colorTextures[2] = 0xCCCCL; fbo.colorGlIds[2] = 12; fbo.colorFormats[2] = 102; + fbo.colorAttachmentCount = 3; + fbo.cachedFormatsDirty = false; + fbo.recomputeTargets(); + assertFalse(fbo.targetsDirty); + + fbo.detachColor(2); + + assertEquals(0L, fbo.colorTextures[2]); + assertEquals(0, fbo.colorGlIds[2]); + assertEquals(0, fbo.colorFormats[2]); + assertEquals(2, fbo.colorAttachmentCount, "topmost detach shrinks count to highest remaining + 1"); + assertTrue(fbo.targetsDirty); + assertTrue(fbo.cachedFormatsDirty); + } + + @Test + void detachColor_middleSlotKeepsCount() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.colorTextures[2] = 0xCCCCL; + fbo.colorAttachmentCount = 3; + + fbo.detachColor(0); + + assertEquals(0L, fbo.colorTextures[0]); + assertEquals(0xCCCCL, fbo.colorTextures[2], "non-detached slot untouched"); + assertEquals(3, fbo.colorAttachmentCount, "count stays while slot 2 occupied"); + assertTrue(fbo.targetsDirty); + assertTrue(fbo.cachedFormatsDirty); + } + + @Test + void detachDepth_zeroesFields() { + final FboState fbo = new FboState(); + fbo.depthTexture = 0xDDDDL; + fbo.depthGlId = 42; + fbo.depthFormat = 999; + fbo.recomputeTargets(); + assertFalse(fbo.targetsDirty); + + fbo.detachDepth(); + + assertEquals(0L, fbo.depthTexture); + assertEquals(0, fbo.depthGlId); + assertEquals(0, fbo.depthFormat); + assertTrue(fbo.targetsDirty); + } + + @Test + void detachColor_outOfBounds_noOp() { + final FboState fbo = new FboState(); + fbo.colorTextures[0] = 0xAAAAL; + fbo.colorAttachmentCount = 1; + fbo.cachedFormatsDirty = false; + fbo.recomputeTargets(); + + fbo.detachColor(-1); + fbo.detachColor(ContextState.MAX_COLOR_ATTACHMENTS); + + assertEquals(0xAAAAL, fbo.colorTextures[0]); + assertEquals(1, fbo.colorAttachmentCount); + assertFalse(fbo.targetsDirty); + assertFalse(fbo.cachedFormatsDirty); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SdlReflect.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SdlReflect.java new file mode 100644 index 000000000..228e62e39 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/SdlReflect.java @@ -0,0 +1,76 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import java.util.Map; +import java.util.Queue; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; + +public final class SdlReflect { + private SdlReflect() {} + + public static void putTextureHandle(ResourceManager rm, int glId, long handle) { + final Object handles = Reflect.get(rm, "textureHandles"); + Reflect.invoke(handles, "put", new Class[] { int.class, long.class }, glId, handle); + } + + public static void putComputeStandIn(ResourceManager rm, int glFormat, int glTarget, boolean readWrite, long handle) { + final Object cache = Reflect.get(rm, "computeStandInTextures"); + Reflect.invoke(cache, "put", new Class[] { long.class, long.class }, + ResourceManager.computeStandInKey(glFormat, glTarget, readWrite), handle); + } + + static void putReadbackSlot(ReadbackShadows shadows, int glId, long offset, long handle, int capacity, boolean valid) { + final Class slotClass; + try { + slotClass = Class.forName("com.gtnewhorizons.angelica.sdlgpu.resource.ReadbackShadows$Slot"); + } catch (ClassNotFoundException e) { + throw new AssertionError(e); + } + final Object slot = Reflect.construct(slotClass); + Reflect.setDeclared(slotClass, slot, "transferBuffer", handle); + Reflect.setDeclared(slotClass, slot, "capacity", capacity); + Reflect.setDeclared(slotClass, slot, "valid", valid); + readbackSlots(shadows).put(readbackKey(glId, offset), slot); + } + + static boolean readbackSlotValid(ReadbackShadows shadows, int glId, long offset) { + return Reflect.get(readbackSlots(shadows).get(readbackKey(glId, offset)), "valid"); + } + + private static long readbackKey(int glId, long offset) { + return (((long) glId) << 32) | (offset & 0xFFFFFFFFL); + } + + private static Map readbackSlots(ReadbackShadows shadows) { + return Reflect.get(shadows, "slots"); + } + + static void recordBuffer(ResourceManager rm, int glId, long handle, long size, int usage) { + rm.recordBufferSizeOnly(glId, size); + putIntKeyed(rm, "bufferHandles", long.class, glId, handle); + putIntKeyed(rm, "bufferUsages", int.class, glId, usage); + } + + static void markUndefined(ResourceManager rm, int glId) { + Reflect.invoke(Reflect.get(rm, "undefinedContentBuffers"), "add", new Class[] { int.class }, glId); + } + + static int pendingFreeCount(TransferThread tt) { + return Reflect.>get(tt, "pendingFrees").size(); + } + + static void forceSubmittedSeq(TransferThread tt, long seq) { + Reflect.setDeclared(TransferThread.class, tt, "submittedSeq", seq); + final Object lock = Reflect.get(tt, "submittedLock"); + synchronized (lock) { lock.notifyAll(); } + } + + static PersistentMapping mapping(ResourceManager rm, int glId) { + return rm.getPersistentMapping(glId); + } + + private static void putIntKeyed(Object owner, String field, Class valueType, int key, Object value) { + Reflect.invoke(Reflect.get(owner, field), "put", new Class[] { int.class, valueType }, key, value); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadDeferFreeTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadDeferFreeTest.java new file mode 100644 index 000000000..6a77afdd7 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadDeferFreeTest.java @@ -0,0 +1,62 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TransferThreadDeferFreeTest { + + private static TransferThread newThread() { + final SdlTestRig rig = SdlTestRig.create(); + return new TransferThread(rig.device, rig.resourceManager); + } + + @Test + void seqAlreadySubmittedFreesInline() { + final TransferThread tt = newThread(); + try { + tt.freeAfterSeq(MemoryUtil.memAlloc(24), 0L); + assertEquals(0, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + @Test + void futureSeqDefers() { + final TransferThread tt = newThread(); + try { + tt.freeAfterSeq(MemoryUtil.memAlloc(24), 100L); + assertEquals(1, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + @Test + void shutdownDrainsRegardlessOfSeq() { + final TransferThread tt = newThread(); + final ByteBuffer buf = MemoryUtil.memAlloc(24); + tt.freeAfterSeq(buf, Long.MAX_VALUE); + assertEquals(1, SdlReflect.pendingFreeCount(tt)); + + shutdown(tt); + assertEquals(0, SdlReflect.pendingFreeCount(tt)); + } + + @Test + void nullBufferIsNoOp() { + final TransferThread tt = newThread(); + try { + tt.freeAfterSeq(null, 0L); + tt.freeAfterSeq(null, 999L); + assertEquals(0, SdlReflect.pendingFreeCount(tt)); + } finally { shutdown(tt); } + } + + private static void shutdown(TransferThread tt) { + tt.shutdown(); + try { tt.getThread().join(2000); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadWakePolicyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadWakePolicyTest.java new file mode 100644 index 000000000..c874719f0 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/TransferThreadWakePolicyTest.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TransferThreadWakePolicyTest { + + @Test + void wakesOnceEveryCoalesceWindow() { + int woken = 0; + for (long seq = 1; seq <= 1600; seq++) { + if (TransferThread.shouldWakeOnEnqueue(seq)) woken++; + } + assertEquals(100, woken, "1600 enqueues must produce 100 unparks, not 1600"); + } + + @Test + void windowIsEvenlySpaced() { + long previous = -1; + for (long seq = 1; seq <= 512; seq++) { + if (!TransferThread.shouldWakeOnEnqueue(seq)) continue; + if (previous >= 0) assertEquals(16, seq - previous, "gaps between unparks must be uniform"); + previous = seq; + } + } + + @Test + void neighboursOfAWakeDoNotWake() { + assertTrue(TransferThread.shouldWakeOnEnqueue(16)); + assertFalse(TransferThread.shouldWakeOnEnqueue(15)); + assertFalse(TransferThread.shouldWakeOnEnqueue(17)); + } + + @Test + void policyHoldsAtLargeSequenceNumbers() { + final long base = 1L << 40; + int woken = 0; + for (long seq = base; seq < base + 1600; seq++) { + if (TransferThread.shouldWakeOnEnqueue(seq)) woken++; + } + assertEquals(100, woken); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaGpuRoundTripTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaGpuRoundTripTest.java new file mode 100644 index 000000000..c273aa830 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaGpuRoundTripTest.java @@ -0,0 +1,286 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.lwjgl.PointerBuffer; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDL_GPUBufferCreateInfo; +import org.lwjgl.sdl.SDL_GPUBufferRegion; +import org.lwjgl.sdl.SDL_GPUTransferBufferCreateInfo; +import org.lwjgl.sdl.SDL_GPUTransferBufferLocation; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.sdl.SDLGPU.*; +import static org.lwjgl.system.MemoryStack.stackPush; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class UploadArenaGpuRoundTripTest { + + private static Device device; + private static FrameManager frameManager; + private static ResourceManager resourceManager; + private static long sdlDevice; + private static int nextGlId = 1; + + @BeforeAll + static void setUp() throws Exception { + final SdlTestRig rig = SdlTestRig.acquireRealDevice(); + device = rig.device; + frameManager = rig.frameManager; + resourceManager = rig.resourceManager; + sdlDevice = rig.sdlHandle; + } + + @AfterAll + static void tearDown() { + if (frameManager != null && frameManager.isFrameActive()) { + frameManager.endFrame(); + } + SdlTestRig.releaseRealDevice(); + } + + private static void beginFrame() { + frameManager.beginFrame(); + frameManager.frame().swapchainUnavailable = true; // headless: never touch the swapchain + } + + private static void endFrame() { + resourceManager.flushUploadArena(); + frameManager.endFrame(); + } + + private static ByteBuffer pattern(int size, int seed) { + final ByteBuffer buf = MemoryUtil.memAlloc(size); + for (int i = 0; i < size; i++) { + buf.put(i, (byte) (seed * 31 + i)); + } + return buf; + } + + private static void assertPattern(ByteBuffer actual, int size, int seed, String what) { + int nonzero = 0; + for (int i = 0; i < size; i++) { + if (actual.get(i) != 0) nonzero++; + } + assertTrue(nonzero > 0, what + ": buffer is all zeros (" + size + " bytes) - upload never landed"); + for (int i = 0; i < size; i++) { + assertEquals((byte) (seed * 31 + i), actual.get(i), what + ": mismatch at byte " + i); + } + } + + private static ByteBuffer download(long gpuBuffer, int size) { + try (var stack = stackPush()) { + final SDL_GPUTransferBufferCreateInfo ci = SDL_GPUTransferBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD) + .size(size); + final long xfer = SDL_CreateGPUTransferBuffer(sdlDevice, ci); + assertTrue(xfer != 0, "download transfer buffer: " + SDLError.SDL_GetError()); + + final long cb = SDL_AcquireGPUCommandBuffer(sdlDevice); + final long cp = SDL_BeginGPUCopyPass(cb); + final SDL_GPUBufferRegion src = SDL_GPUBufferRegion.calloc(stack).buffer(gpuBuffer).offset(0).size(size); + final SDL_GPUTransferBufferLocation dst = SDL_GPUTransferBufferLocation.calloc(stack).transfer_buffer(xfer).offset(0); + SDL_DownloadFromGPUBuffer(cp, src, dst); + SDL_EndGPUCopyPass(cp); + final long fence = SDL_SubmitGPUCommandBufferAndAcquireFence(cb); + assertTrue(fence != 0, "submit+fence: " + SDLError.SDL_GetError()); + final PointerBuffer fences = stack.pointers(fence); + SDL_WaitForGPUFences(sdlDevice, true, fences); + SDL_ReleaseGPUFence(sdlDevice, fence); + + final ByteBuffer mapped = SDL_MapGPUTransferBuffer(sdlDevice, xfer, false, size); + final ByteBuffer copy = MemoryUtil.memAlloc(size); + MemoryUtil.memCopy(MemoryUtil.memAddress(mapped), MemoryUtil.memAddress(copy), size); + SDL_UnmapGPUTransferBuffer(sdlDevice, xfer); + SDL_ReleaseGPUTransferBuffer(sdlDevice, xfer); + return copy; + } + } + + private static long createVertexBuffer(int size) { + return resourceManager.createBuffer(nextGlId++, SDL_GPU_BUFFERUSAGE_VERTEX, size); + } + + private static long createRawBuffer(int size) { + try (var stack = stackPush()) { + final SDL_GPUBufferCreateInfo ci = SDL_GPUBufferCreateInfo.calloc(stack) + .usage(SDL_GPU_BUFFERUSAGE_VERTEX) + .size(size); + return SDL_CreateGPUBuffer(sdlDevice, ci); + } + } + + @Test + @Order(1) + void singleFrameRoundTrip() { + final int size = 54864; // DE armor OBJ list size + beginFrame(); + final long dst = createVertexBuffer(size); + assertTrue(dst != 0); + final ByteBuffer data = pattern(size, 7); + assertTrue(resourceManager.arenaUpload(data, dst, 0, false)); + MemoryUtil.memFree(data); + endFrame(); + + SDL_WaitForGPUIdle(sdlDevice); + final ByteBuffer got = download(dst, size); + assertPattern(got, size, 7, "single-frame upload"); + MemoryUtil.memFree(got); + } + + @Test + @Order(2) + void uploadSurvivesManyFramesOfArenaChurnAndFragmentation() { + final int size = 117072; + final int junkSize = 64 * 1024; + + beginFrame(); + final long armor = createVertexBuffer(size); + assertTrue(armor != 0); + final ByteBuffer armorData = pattern(size, 3); + assertTrue(resourceManager.arenaUpload(armorData, armor, 0, false)); + MemoryUtil.memFree(armorData); + final long junkDst = createVertexBuffer(junkSize); + endFrame(); + + final ByteBuffer junk = pattern(junkSize, 9); + final long[] churn = new long[8]; + for (int frame = 0; frame < 60; frame++) { + beginFrame(); + for (int i = 0; i < churn.length; i++) { + if (churn[i] != 0) SDL_ReleaseGPUBuffer(sdlDevice, churn[i]); + churn[i] = createRawBuffer(3 * 1024 * 1024); // >2MiB: shared large-page allocations + } + for (int i = 0; i < 6; i++) { + junk.position(0).limit(junkSize); + assertTrue(resourceManager.arenaUpload(junk, junkDst, 0, false)); + } + endFrame(); + } + MemoryUtil.memFree(junk); + for (long handle : churn) { + if (handle != 0) SDL_ReleaseGPUBuffer(sdlDevice, handle); + } + + SDL_WaitForGPUIdle(sdlDevice); + final ByteBuffer got = download(armor, size); + assertPattern(got, size, 3, "upload after 60 frames of churn"); + MemoryUtil.memFree(got); + } + + @Test + @Order(4) + void replayOfDeArmorLoadTrace() { + final int bigSize = 14854464; + final int medSize = 3713616; + final int[] armorSizes = { 78624, 78624, 54864, 54864, 54864, 54864, 117072, 117072 }; + + // frame 66 + beginFrame(); + long big = createVertexBuffer(bigSize); + ByteBuffer bigData = pattern(bigSize, 41); + assertTrue(resourceManager.arenaUpload(bigData, big, 0, false)); + MemoryUtil.memFree(bigData); + final long med = createVertexBuffer(medSize); + final ByteBuffer medData = pattern(medSize, 42); + assertTrue(resourceManager.arenaUpload(medData, med, 0, false)); + MemoryUtil.memFree(medData); + endFrame(); + + final int bigGlId = nextGlId - 2; + beginFrame(); + resourceManager.deleteBuffer(bigGlId); + big = resourceManager.createBuffer(bigGlId, SDL_GPU_BUFFERUSAGE_VERTEX, bigSize); + bigData = pattern(bigSize, 43); + assertTrue(resourceManager.arenaUpload(bigData, big, 0, false)); + MemoryUtil.memFree(bigData); + endFrame(); + + final long[] armor = new long[armorSizes.length]; + beginFrame(); + for (int i = 0; i < armorSizes.length; i++) { + armor[i] = createVertexBuffer(armorSizes[i]); + final ByteBuffer data = pattern(armorSizes[i], 50 + i); + assertTrue(resourceManager.arenaUpload(data, armor[i], 0, false)); + MemoryUtil.memFree(data); + } + endFrame(); + + for (int frame = 0; frame < 30; frame++) { + beginFrame(); + resourceManager.deleteBuffer(bigGlId); + big = resourceManager.createBuffer(bigGlId, SDL_GPU_BUFFERUSAGE_VERTEX, bigSize); + bigData = pattern(bigSize, 60 + frame); + assertTrue(resourceManager.arenaUpload(bigData, big, 0, false)); + MemoryUtil.memFree(bigData); + endFrame(); + } + + SDL_WaitForGPUIdle(sdlDevice); + for (int i = 0; i < armorSizes.length; i++) { + final ByteBuffer got = download(armor[i], armorSizes[i]); + assertPattern(got, armorSizes[i], 50 + i, "armor buffer " + i + " (size " + armorSizes[i] + ")"); + MemoryUtil.memFree(got); + } + } + + @Test + @Order(5) + void midFrameReadbackFlushSeesPriorUploadsAndKeepsLaterOnes() { + final int size = 54864; + beginFrame(); + final long a = createVertexBuffer(size); + final ByteBuffer dataA = pattern(size, 11); + assertTrue(resourceManager.arenaUpload(dataA, a, 0, false)); + MemoryUtil.memFree(dataA); + + resourceManager.flushUploadArena(); + final ByteBuffer readback = download(a, size); + assertPattern(readback, size, 11, "mid-frame readback of A"); + + final long b = createVertexBuffer(size); + assertTrue(resourceManager.arenaUpload(readback, b, 0, false)); + MemoryUtil.memFree(readback); + endFrame(); + + SDL_WaitForGPUIdle(sdlDevice); + final ByteBuffer got = download(b, size); + assertPattern(got, size, 11, "B built from mid-frame readback"); + MemoryUtil.memFree(got); + } + + @Test + @Order(3) + void midFrameOverflowGrowKeepsAllUploads() { + final int chunk = 5 * 1024 * 1024; + final int chunks = 5; + final long[] dsts = new long[chunks]; + beginFrame(); + for (int i = 0; i < chunks; i++) { + dsts[i] = createVertexBuffer(chunk); + final ByteBuffer data = pattern(chunk, 20 + i); + assertTrue(resourceManager.arenaUpload(data, dsts[i], 0, false)); + MemoryUtil.memFree(data); + } + endFrame(); + + SDL_WaitForGPUIdle(sdlDevice); + for (int i = 0; i < chunks; i++) { + final ByteBuffer got = download(dsts[i], chunk); + assertPattern(got, chunk, 20 + i, "grow-path upload " + i); + MemoryUtil.memFree(got); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaTest.java new file mode 100644 index 000000000..da874f52a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadArenaTest.java @@ -0,0 +1,79 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UploadArenaTest { + + @Test + void reserveBumpsOffsetAndCountsCopies() { + final UploadArena a = new UploadArena(); + assertEquals(0, a.reserve(100)); + assertEquals(112, a.reserve(50)); + assertEquals(162, a.usedBytes()); + assertEquals(2, a.copyCount()); + } + + @Test + void reserveFailsWhenFullWithoutCounting() { + final UploadArena a = new UploadArena(); + assertEquals(0, a.reserve(a.capacity())); + assertEquals(-1, a.reserve(1)); + assertEquals(-1, a.reserve(-1)); + assertEquals(1, a.copyCount()); + } + + @Test + void fitsChecksAgainstCapacityNotRemaining() { + final UploadArena a = new UploadArena(); + a.reserve(a.capacity() - 10); + assertTrue(a.fits(100)); + assertFalse(a.fits(a.capacity() + 1)); + assertFalse(a.fits(-1)); + } + + @Test + void resetClearsOffsetAndCountButKeepsCapacity() { + final UploadArena a = new UploadArena(); + a.reserve(500); + a.reset(); + assertEquals(0, a.usedBytes()); + assertEquals(0, a.copyCount()); + assertEquals(UploadArena.INITIAL_CAPACITY, a.capacity()); + assertEquals(0, a.reserve(10)); + } + + @Test + void growIsDeferredUntilApplyGrow() { + final UploadArena a = new UploadArena(); + a.requestGrow(UploadArena.INITIAL_CAPACITY + 1); + assertEquals(UploadArena.INITIAL_CAPACITY, a.capacity()); + assertTrue(a.applyGrow()); + assertEquals(UploadArena.INITIAL_CAPACITY * 2, a.capacity()); + assertFalse(a.applyGrow()); + } + + @Test + void requestGrowDoublesUntilMinSizeFits() { + final UploadArena a = new UploadArena(); + a.requestGrow(UploadArena.INITIAL_CAPACITY * 3); + assertTrue(a.applyGrow()); + assertEquals(UploadArena.INITIAL_CAPACITY * 4, a.capacity()); + } + + @Test + void overflowThenGrowRoundTrip() { + final UploadArena a = new UploadArena(); + assertEquals(0, a.reserve(a.capacity())); + final int want = a.usedBytes() + 4096; + assertEquals(-1, a.reserve(4096)); + a.requestGrow(want); + a.reset(); + assertTrue(a.applyGrow()); + assertEquals(0, a.reserve(a.capacity())); + assertEquals(1, a.copyCount()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBAutoFlushThresholdTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBAutoFlushThresholdTest.java new file mode 100644 index 000000000..b774af46a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBAutoFlushThresholdTest.java @@ -0,0 +1,87 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + + +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import static com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.MAX_PENDING_UPLOAD_BYTES; +import static com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.MAX_PENDING_UPLOAD_COMMANDS; +import static org.junit.jupiter.api.Assertions.*; + +class UploadCBAutoFlushThresholdTest { + + private static FrameManager newFM() { + return SdlTestRig.frameManager(); + } + + @Test + void bytesUnderThreshold_doesNotRequestFlush() { + final FrameManager fm = newFM(); + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES / 2, 1); + assertFalse(fm.shouldAutoSubmitPendingUpload()); + } + + @Test + void bytesAtThreshold_requestsFlush() { + final FrameManager fm = newFM(); + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES, 1); + assertTrue(fm.shouldAutoSubmitPendingUpload()); + } + + @Test + void bytesOverThreshold_requestsFlush() { + final FrameManager fm = newFM(); + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES + 1, 1); + assertTrue(fm.shouldAutoSubmitPendingUpload()); + } + + @Test + void manyTinyUploadsAccumulateBytes() { + final FrameManager fm = newFM(); + for (int i = 0; i < 255; i++) fm.recordUploadCommands(65536, 1); + assertTrue(fm.frame().pendingUploadBytes < MAX_PENDING_UPLOAD_BYTES); + fm.recordUploadCommands(65536, 1); + assertTrue(fm.shouldAutoSubmitPendingUpload()); + } + + @Test + void manyOneByteUploadsTripCommandThreshold() { + final FrameManager fm = newFM(); + for (int i = 0; i < MAX_PENDING_UPLOAD_COMMANDS - 1; i++) fm.recordUploadCommands(1, 1); + assertFalse(fm.shouldAutoSubmitPendingUpload(), "below command threshold and far below byte threshold"); + fm.recordUploadCommands(1, 1); + assertTrue(fm.shouldAutoSubmitPendingUpload(), "exactly MAX_PENDING_UPLOAD_COMMANDS recorded -- request flush"); + } + + @Test + void recordUploadCommands_perThreadCountersDoNotInterfere() throws Exception { + final FrameManager fm = newFM(); + final AtomicLong threadABytes = new AtomicLong(); + final AtomicReference threadAShouldFlush = new AtomicReference<>(); + final CountDownLatch aDone = new CountDownLatch(1); + final Thread tA = new Thread(() -> { + try { + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES + 1, 17); + threadABytes.set(fm.frame().pendingUploadBytes); + threadAShouldFlush.set(fm.shouldAutoSubmitPendingUpload()); + } finally { + aDone.countDown(); + } + }, "upload-thread-A"); + tA.start(); + aDone.await(); + + assertEquals(MAX_PENDING_UPLOAD_BYTES + 1, threadABytes.get()); + assertTrue(threadAShouldFlush.get()); + assertEquals(0L, fm.frame().pendingUploadBytes); + assertEquals(0, fm.frame().pendingUploadCommands); + assertFalse(fm.shouldAutoSubmitPendingUpload()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBBatchFillCycleSafetyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBBatchFillCycleSafetyTest.java new file mode 100644 index 000000000..2b54e9c56 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/resource/UploadCBBatchFillCycleSafetyTest.java @@ -0,0 +1,136 @@ +package com.gtnewhorizons.angelica.sdlgpu.resource; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; + +import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.MAX_PENDING_UPLOAD_BYTES; +import static com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.MAX_PENDING_UPLOAD_COMMANDS; +import static org.junit.jupiter.api.Assertions.*; + +class UploadCBBatchFillCycleSafetyTest { + + private static FrameManager newFM() { + return SdlTestRig.frameManager(); + } + + @Test + void thresholdPredicate_dependsOnlyOnCounters() { + final FrameManager fm = newFM(); + final FrameManager.FrameState f = fm.frame(); + fm.recordUploadCommands(MAX_PENDING_UPLOAD_BYTES + 1, 1); + f.copyPass = 0; + assertTrue(fm.shouldAutoSubmitPendingUpload()); + f.copyPass = 0xCAFEBABEL; + assertTrue(fm.shouldAutoSubmitPendingUpload()); + } + + @Test + void thresholdPredicate_commandsThresholdTrips() { + final FrameManager fm = newFM(); + for (int i = 0; i < MAX_PENDING_UPLOAD_COMMANDS; i++) fm.recordUploadCommands(1, 1); + assertTrue(fm.shouldAutoSubmitPendingUpload(), "command-count threshold trips at MAX_PENDING_UPLOAD_COMMANDS"); + } + + @Test + void flushRequestedFlag_isPerThread() throws Exception { + final FrameManager fm = newFM(); + final FrameManager.FrameState mine = fm.frame(); + assertFalse(mine.flushRequested, "test thread's flag starts false"); + + final AtomicReference workerInitial = new AtomicReference<>(); + final AtomicReference workerAfterSet = new AtomicReference<>(); + final AtomicBoolean workerWasIndependentObject = new AtomicBoolean(); + final CountDownLatch done = new CountDownLatch(1); + + final Thread worker = new Thread(() -> { + try { + final FrameManager.FrameState theirs = fm.frame(); + workerInitial.set(theirs.flushRequested); + workerWasIndependentObject.set(theirs != mine); + theirs.flushRequested = true; + workerAfterSet.set(theirs.flushRequested); + } finally { + done.countDown(); + } + }, "flush-flag-worker"); + worker.start(); + done.await(); + + assertEquals(Boolean.FALSE, workerInitial.get()); + assertTrue(workerWasIndependentObject.get(), "worker has its own FrameManager.FrameState"); + assertEquals(Boolean.TRUE, workerAfterSet.get()); + assertFalse(mine.flushRequested, "test thread's flag stays false"); + } + + @Test + void requestFlushOnAllRegisteredFrames_flagsAllIncludingCaller() throws Exception { + final FrameManager fm = newFM(); + final FrameManager.FrameState mine = fm.frame(); + + final AtomicReference wA = new AtomicReference<>(); + final AtomicReference wB = new AtomicReference<>(); + final CountDownLatch registered = new CountDownLatch(2); + final CountDownLatch keepAlive = new CountDownLatch(1); + + final Thread tA = new Thread(() -> { + wA.set(fm.frame()); + registered.countDown(); + try { keepAlive.await(); } catch (InterruptedException ignored) {} + }, "worker-A"); + final Thread tB = new Thread(() -> { + wB.set(fm.frame()); + registered.countDown(); + try { keepAlive.await(); } catch (InterruptedException ignored) {} + }, "worker-B"); + tA.start(); + tB.start(); + registered.await(); + + assertFalse(mine.flushRequested); + assertFalse(wA.get().flushRequested); + assertFalse(wB.get().flushRequested); + + fm.requestFlushOnAllRegisteredFrames(); + + assertTrue(mine.flushRequested, "caller's flag MUST be raised"); + assertTrue(wA.get().flushRequested); + assertTrue(wB.get().flushRequested); + + keepAlive.countDown(); + tA.join(); + tB.join(); + } + + @Test + void releaseThreadState_unregistersFromRegistry() throws Exception { + final FrameManager fm = newFM(); + fm.frame(); + + final AtomicReference beforeRelease = new AtomicReference<>(); + final CountDownLatch released = new CountDownLatch(1); + + final Thread w = new Thread(() -> { + try { + beforeRelease.set(fm.frame()); + fm.releaseThreadState(); + } finally { + released.countDown(); + } + }, "release-worker"); + w.start(); + released.await(); + w.join(); + + final FrameManager.FrameState dead = beforeRelease.get(); + assertNotNull(dead); + dead.flushRequested = false; // baseline + fm.requestFlushOnAllRegisteredFrames(); + assertFalse(dead.flushRequested, "released worker's FrameManager.FrameState must not be flagged by triggers (out of registry)"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBindGenerationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBindGenerationTest.java new file mode 100644 index 000000000..d43a1c0be --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerBindGenerationTest.java @@ -0,0 +1,76 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.lang.reflect.Field; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class SamplerBindGenerationTest { + + @SuppressWarnings("unchecked") + private static ContextState state() throws Exception { + final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState"); + f.setAccessible(true); + return ((ThreadLocal) f.get(null)).get(); + } + + @Test + void switchingActiveUnitDoesNotBumpTheGeneration() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.activeTexture(GL13.GL_TEXTURE0); + final int before = st.samplerBindGen; + + backend.activeTexture(GL13.GL_TEXTURE3); + backend.activeTexture(GL13.GL_TEXTURE7); + backend.activeTexture(GL13.GL_TEXTURE0); + + assertEquals(before, st.samplerBindGen, "a bare unit switch changes no binding"); + assertEquals(0, st.activeTextureUnit, "the active unit still tracks"); + } + + @Test + void aRealBindChangeBumpsTheGeneration() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.activeTexture(GL13.GL_TEXTURE0); + backend.bindTexture(GL11.GL_TEXTURE_2D, 0); + final int before = st.samplerBindGen; + + backend.bindTexture(GL11.GL_TEXTURE_2D, 42); + assertNotEquals(before, st.samplerBindGen, "a changed binding must invalidate the sampler set"); + } + + @Test + void rebindingTheSameTextureDoesNotBumpTheGeneration() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.activeTexture(GL13.GL_TEXTURE0); + backend.bindTexture(GL11.GL_TEXTURE_2D, 99); + final int before = st.samplerBindGen; + + backend.bindTexture(GL11.GL_TEXTURE_2D, 99); + assertEquals(before, st.samplerBindGen); + } + + @Test + void bindingsAreHeldPerUnitSoTheActiveUnitIsNotSamplerState() throws Exception { + final SDLGPURenderBackend backend = new SDLGPURenderBackend(); + final ContextState st = state(); + + backend.activeTexture(GL13.GL_TEXTURE2); + backend.bindTexture(GL11.GL_TEXTURE_2D, 55); + backend.activeTexture(GL13.GL_TEXTURE6); + + assertEquals(55, st.boundTextures[2], "unit 2 keeps its binding after the active unit moves away"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCacheTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCacheTest.java new file mode 100644 index 000000000..cabec0844 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/SamplerCacheTest.java @@ -0,0 +1,82 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class SamplerCacheTest { + + private static SamplerCache.Key key(int minF, int magF) { + return new SamplerCache.Key(minF, magF, 0x2901, 0x2901, 0x2901, 0f, 1000f, 0f, 1f, 0, 0x0203); + } + + @Test + void sameKeyReturnsSameHandleAndFactoryCalledOnce() { + final SamplerCache cache = new SamplerCache(); + final AtomicLong nextHandle = new AtomicLong(0x1000); + final AtomicInteger calls = new AtomicInteger(); + + final SamplerCache.Factory f = k -> { + calls.incrementAndGet(); + return nextHandle.getAndIncrement(); + }; + + final SamplerCache.Key k = key(0x2702, 0x2600); + final long h1 = cache.getOrCreate(k, f); + final long h2 = cache.getOrCreate(k, f); + final long h3 = cache.getOrCreate(k, f); + + assertEquals(h1, h2, "second lookup with same key must return cached handle"); + assertEquals(h1, h3, "third lookup with same key must return cached handle"); + assertEquals(1, calls.get(), "factory must be invoked exactly once per unique key"); + assertEquals(1, cache.size()); + } + + @Test + void distinctKeysReturnDistinctHandles() { + final SamplerCache cache = new SamplerCache(); + final AtomicLong nextHandle = new AtomicLong(0x2000); + + final SamplerCache.Factory f = k -> nextHandle.getAndIncrement(); + + final long mipped = cache.getOrCreate(key(0x2702, 0x2600), f); + final long flat = cache.getOrCreate(key(0x2600, 0x2600), f); + + assertNotEquals(mipped, flat, "different sampler states must produce different handles"); + assertEquals(2, cache.size()); + + assertEquals(mipped, cache.getOrCreate(key(0x2702, 0x2600), f)); + assertEquals(flat, cache.getOrCreate(key(0x2600, 0x2600), f)); + } + + @Test + void factoryReturningZeroIsNotCached() { + final SamplerCache cache = new SamplerCache(); + final AtomicInteger calls = new AtomicInteger(); + + final SamplerCache.Factory zeroFactory = k -> { calls.incrementAndGet(); return 0L; }; + final SamplerCache.Key k = key(0x2702, 0x2600); + + assertEquals(0L, cache.getOrCreate(k, zeroFactory)); + assertEquals(0L, cache.getOrCreate(k, zeroFactory)); + assertEquals(2, calls.get(), "0 result must not be cached -- factory must be invoked again"); + assertEquals(0, cache.size()); + } + + @Test + void recordKeyEqualityAndHashCode() { + final SamplerCache.Key a = key(0x2702, 0x2600); + final SamplerCache.Key b = key(0x2702, 0x2600); + final SamplerCache.Key c = key(0x2600, 0x2600); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + assertNotEquals(a, c); + assertNotNull(a.toString()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinderTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinderTest.java new file mode 100644 index 000000000..8533e8d06 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/sampler/StorageBufferBinderTest.java @@ -0,0 +1,47 @@ +package com.gtnewhorizons.angelica.sdlgpu.sampler; + +import java.lang.reflect.InvocationTargetException; +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class StorageBufferBinderTest { + + @Test + void bindStage_emptySlotsIsNoOp() { + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + prog.linked = true; + prog.fragmentGraphicsBindingMap = ShaderManager.GraphicsBindingMap.EMPTY; + + final ContextState st = new ContextState(); + st.boundProgram = 1; + + final StorageBufferBinder binder = new StorageBufferBinder(null, null); + assertDoesNotThrow(() -> invokeBindStage(binder, st, prog, true)); + assertEquals(0, st.lastFragStorageBufProgram); + } + + @Test + void bindStage_rejectsOverCapDeclaration() { + final int[] tooMany = new int[ContextState.MAX_STORAGE_BUFFERS_PER_STAGE + 1]; + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + prog.linked = true; + prog.fragmentGraphicsBindingMap = new ShaderManager.GraphicsBindingMap(new int[0], new int[0], tooMany); + + final ContextState st = new ContextState(); + st.boundProgram = 1; + + final StorageBufferBinder binder = new StorageBufferBinder(null, null); + assertThrows(InvocationTargetException.class, () -> invokeBindStage(binder, st, prog, true)); + } + + private static void invokeBindStage(StorageBufferBinder binder, ContextState st, ShaderManager.ProgramObject prog, boolean fragment) throws Exception { + final var m = StorageBufferBinder.class.getDeclaredMethod("bindStage", long.class, ContextState.class, ShaderManager.ProgramObject.class, boolean.class); + m.setAccessible(true); + m.invoke(binder, 0xDEADBEEFL, st, prog, fragment); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationPatchTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationPatchTest.java new file mode 100644 index 000000000..454df39f8 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationPatchTest.java @@ -0,0 +1,87 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.junit.jupiter.api.Test; +import org.lwjgl.util.spvc.Spvc; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AttribLocationPatchTest { + + private static final String[] NAMES = { + "vPosition", "aMaterial", "aTranslateSubChunk", "aTranslateChunk", "aScale", "iris_color" + }; + + private static final int[] DESIRED = {0, 5, 4, 3, 2, 1}; + private static final int[] VEC_SIZES = {3, 1, 3, 3, 3, 4}; + private static final int[] BASE_TYPES = { + Spvc.SPVC_BASETYPE_FP32, Spvc.SPVC_BASETYPE_INT32, Spvc.SPVC_BASETYPE_FP32, + Spvc.SPVC_BASETYPE_INT32, Spvc.SPVC_BASETYPE_FP32, Spvc.SPVC_BASETYPE_FP32 + }; + + private static ShaderManager.StageReflection reflectionWithInputs(ByteBuffer spirv) { + final ShaderManager.VsInput[] inputs = new ShaderManager.VsInput[NAMES.length]; + for (int i = 0; i < NAMES.length; i++) { + spirv.asIntBuffer().put(i, i); + inputs[i] = new ShaderManager.VsInput(NAMES[i], i, i, VEC_SIZES[i], BASE_TYPES[i]); + } + final ShaderManager.StageReflection e = ShaderManager.StageReflection.EMPTY; + return new ShaderManager.StageReflection(e.counts(), e.samplerNames(), e.extraUniformNames(), + e.storageImageNames(), e.uboSize(), e.uboMembers(), List.of(inputs), e.vsOutputs(), e.fsInputs(), + e.maxOutputLocation(), e.numReadonlyStorageBuffers(), e.numReadwriteStorageBuffers(), + e.numReadonlyStorageTextures(), e.numReadwriteStorageTextures(), e.blocks()); + } + + @Test + void fullPermutationRemapsEveryInputWithoutCollision() { + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + prog.vertexSpirv = ByteBuffer.allocateDirect(NAMES.length * Integer.BYTES).order(ByteOrder.nativeOrder()); + final ShaderManager.StageReflection vs = reflectionWithInputs(prog.vertexSpirv); + for (int i = 0; i < NAMES.length; i++) { + prog.attribLocationBindings.put(NAMES[i], DESIRED[i]); + } + + ShaderManager.applyAttribLocationsAndInputMask(prog, vs); + + for (int i = 0; i < NAMES.length; i++) { + final int idx = i; + assertEquals(DESIRED[i], prog.vertexSpirv.asIntBuffer().get(i), () -> "SPIR-V Location decoration for " + NAMES[idx]); + assertEquals(DESIRED[i], prog.resolvedAttribLocations.getInt(NAMES[i]), () -> "resolved location for " + NAMES[idx]); + } + assertEquals(0x3f, prog.vertexInputMask, "six inputs at 0..5"); + } + + @Test + void metadataFollowsTheRemappedLocation() { + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + prog.vertexSpirv = ByteBuffer.allocateDirect(NAMES.length * Integer.BYTES).order(ByteOrder.nativeOrder()); + final ShaderManager.StageReflection vs = reflectionWithInputs(prog.vertexSpirv); + for (int i = 0; i < NAMES.length; i++) { + prog.attribLocationBindings.put(NAMES[i], DESIRED[i]); + } + + ShaderManager.applyAttribLocationsAndInputMask(prog, vs); + + assertEquals(4, prog.vertexInputVecSize[1]); + assertEquals(Spvc.SPVC_BASETYPE_FP32, prog.vertexInputBaseType[1]); + assertEquals(1, prog.vertexInputVecSize[5]); + assertEquals(Spvc.SPVC_BASETYPE_INT32, prog.vertexInputBaseType[5]); + } + + @Test + void unboundInputsKeepTheirOriginalLocation() { + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + prog.vertexSpirv = ByteBuffer.allocateDirect(NAMES.length * Integer.BYTES).order(ByteOrder.nativeOrder()); + final ShaderManager.StageReflection vs = reflectionWithInputs(prog.vertexSpirv); + prog.attribLocationBindings.put("vPosition", 0); + + ShaderManager.applyAttribLocationsAndInputMask(prog, vs); + + for (int i = 0; i < NAMES.length; i++) { + assertEquals(i, prog.resolvedAttribLocations.getInt(NAMES[i]), NAMES[i]); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationReflectionTest.java new file mode 100644 index 000000000..53dd68ef0 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/AttribLocationReflectionTest.java @@ -0,0 +1,112 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager.ProgramObject; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager.StageReflection; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager.VsInput; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.util.spvc.Spvc; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class AttribLocationReflectionTest { + + private static StageReflection reflectionWith(VsInput... inputs) { + return new StageReflection( + ShaderManager.ResourceCounts.EMPTY, List.of(), List.of(), List.of(), 0, List.of(), + List.of(inputs), List.of(), List.of(), -1, 0, 0, 0, 0, ShaderManager.BlockReflection.emptyBlocks()); + } + + private static ByteBuffer spirvWithWord(int offset, int value) { + final ByteBuffer buf = ByteBuffer.allocateDirect((offset + 1) * 4).order(ByteOrder.nativeOrder()); + buf.asIntBuffer().put(offset, value); + return buf; + } + + @Test + void autoMappedAttributeIsResolved() { + final ProgramObject prog = new ProgramObject(); + prog.vertexSpirv = spirvWithWord(2, 0); + ShaderManager.applyAttribLocationsAndInputMask(prog, reflectionWith(new VsInput("vertexId", 2, 0, 1, Spvc.SPVC_BASETYPE_FP32))); + + assertEquals(0, prog.resolvedAttribLocations.getInt("vertexId")); + assertEquals(1, prog.vertexInputMask); + assertEquals(-1, prog.resolvedAttribLocations.getInt("doesNotExist")); + } + + @Test + void explicitBindingPatchesSpirvAndResolvedMap() { + final ProgramObject prog = new ProgramObject(); + prog.attribLocationBindings.put("vertexId", 5); + prog.vertexSpirv = spirvWithWord(2, 0); + ShaderManager.applyAttribLocationsAndInputMask(prog, reflectionWith(new VsInput("vertexId", 2, 0, 1, Spvc.SPVC_BASETYPE_FP32))); + + assertEquals(5, prog.vertexSpirv.asIntBuffer().get(2)); + assertEquals(5, prog.resolvedAttribLocations.getInt("vertexId")); + assertEquals(1 << 5, prog.vertexInputMask); + } + + @Test + void relinkRefreshesResolvedLocations() { + final ProgramObject prog = new ProgramObject(); + prog.vertexSpirv = spirvWithWord(2, 0); + final StageReflection vs = reflectionWith(new VsInput("vertexId", 2, 0, 1, Spvc.SPVC_BASETYPE_FP32)); + ShaderManager.applyAttribLocationsAndInputMask(prog, vs); + assertEquals(0, prog.resolvedAttribLocations.getInt("vertexId")); + + prog.attribLocationBindings.put("vertexId", 3); + prog.vertexSpirv = spirvWithWord(2, 0); + ShaderManager.applyAttribLocationsAndInputMask(prog, vs); + assertEquals(3, prog.resolvedAttribLocations.getInt("vertexId")); + assertEquals(1 << 3, prog.vertexInputMask); + } + + @Test + void activeAttribNamesComeFromReflectionOnceLinked() { + final ProgramObject prog = new ProgramObject(); + prog.vertexSpirv = spirvWithWord(6, 1); + final ByteBuffer buf = prog.vertexSpirv; + buf.asIntBuffer().put(3, 0); + ShaderManager.applyAttribLocationsAndInputMask(prog, reflectionWith( + new VsInput("a_Pos", 3, 0, 3, Spvc.SPVC_BASETYPE_FP32), + new VsInput("vertexId", 6, 1, 1, Spvc.SPVC_BASETYPE_FP32))); + prog.linked = true; + + assertEquals(List.of("a_Pos", "vertexId"), prog.getActiveAttribNames()); + } + + @Test + void activeAttribNamesCacheInvalidatedOnRelink() { + final ProgramObject prog = new ProgramObject(); + prog.vertexSpirv = spirvWithWord(2, 0); + ShaderManager.applyAttribLocationsAndInputMask( + prog, reflectionWith(new VsInput("first", 2, 0, 1, Spvc.SPVC_BASETYPE_FP32))); + prog.linked = true; + assertEquals(List.of("first"), prog.getActiveAttribNames()); + + prog.vertexSpirv = spirvWithWord(2, 0); + ShaderManager.applyAttribLocationsAndInputMask( + prog, reflectionWith(new VsInput("second", 2, 0, 1, Spvc.SPVC_BASETYPE_FP32))); + assertEquals(List.of("second"), prog.getActiveAttribNames()); + } + + @Test + void attribGlTypeFromReflection() { + final ProgramObject prog = new ProgramObject(); + prog.vertexSpirv = spirvWithWord(6, 1); + prog.vertexSpirv.asIntBuffer().put(3, 0); + ShaderManager.applyAttribLocationsAndInputMask(prog, reflectionWith( + new VsInput("vertexId", 3, 0, 1, Spvc.SPVC_BASETYPE_FP32), + new VsInput("cell", 6, 1, 3, Spvc.SPVC_BASETYPE_INT32))); + + assertEquals(GL11.GL_FLOAT, prog.getAttribGlType("vertexId")); + assertEquals(GL20.GL_INT_VEC3, prog.getAttribGlType("cell")); + assertEquals(GL20.GL_FLOAT_VEC4, prog.getAttribGlType("unknown")); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/CanonicalBlockLayoutTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/CanonicalBlockLayoutTest.java new file mode 100644 index 000000000..428ff6e72 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/CanonicalBlockLayoutTest.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +class CanonicalBlockLayoutTest { + + private static final String BLOCK_GLSL = """ + layout(std140) uniform IrisPerFrame { + vec3 cameraPosition; + float frameTimeCounter; + mat4 gbufferModelView; + vec4 fogColor; + float rainStrength; + }; + """; + + private static String shaderUsing(String expr) { + return "#version 330 core\n" + BLOCK_GLSL + "out vec4 fragColor;\nvoid main() { fragColor = " + expr + "; }\n"; + } + + @Test + void unusedMembersKeepTheirOffsetsAcrossPrograms() { + final Map usesFirst = offsetsOf(shaderUsing("vec4(cameraPosition, 1.0)")); + final Map usesLast = offsetsOf(shaderUsing("vec4(rainStrength)")); + + assertEquals(0, usesFirst.get("cameraPosition")); + assertEquals(12, usesFirst.get("frameTimeCounter")); + assertEquals(16, usesFirst.get("gbufferModelView")); + assertEquals(80, usesFirst.get("fogColor")); + assertEquals(96, usesFirst.get("rainStrength")); + + assertEquals(usesFirst, usesLast, "a shader referencing only the last member must still see every member at the same offset; without this one shared per-frame buffer cannot serve all programs"); + } + + @Test + void looseUniformOffsetsDependOnEachShadersDeclarationSet() { + final String withoutLeadingDecl = """ + #version 330 core + uniform vec3 cameraPosition; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, 1.0); } + """; + final String withLeadingDecl = """ + #version 330 core + uniform mat4 gbufferModelView; + uniform vec3 cameraPosition; + out vec4 fragColor; + void main() { fragColor = gbufferModelView * vec4(cameraPosition, 1.0); } + """; + + final Integer a = offsetsOf(withoutLeadingDecl).get("cameraPosition"); + final Integer b = offsetsOf(withLeadingDecl).get("cameraPosition"); + + assertNotNull(a); + assertNotNull(b); + assertNotEquals(a, b, "if loose-uniform offsets were stable across declaration sets, no canonical block would be needed"); + } + + private static Map offsetsOf(String source) { + final ByteBuffer spirv = compile(source); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final Map out = new LinkedHashMap<>(); + for (ShaderManager.UboMember m : refl.uboMembers()) out.put(m.name(), m.offset()); + return out; + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static ByteBuffer compile(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_fragment_shader, "test.frag", SpirvCompiler.Options.vulkanRelaxed()); + if (r.spirv() == null) { + fail("shaderc failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClearImage3DReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClearImage3DReflectionTest.java new file mode 100644 index 000000000..50748e3f8 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ClearImage3DReflectionTest.java @@ -0,0 +1,76 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ClearImage3DReflectionTest { + + private static final String SHADER = "clear_image3d.csh"; + + private static String source() { + return TestPaths.readString("src/main/resources/assets/angelica/shaders/sdlgpu/" + SHADER); + } + + @Test + void compileShaderLeavesComputeSpirvPristine() throws Exception { + final ShaderManager sm = new ShaderManager(null); + final int shader = sm.createShader(GL43.GL_COMPUTE_SHADER); + sm.shaderSource(shader, source()); + sm.compileShader(shader); + + final var shaderObjects = ShaderManager.class.getDeclaredField("shaderObjects"); + shaderObjects.setAccessible(true); + final Object obj = ((java.util.Map) shaderObjects.get(sm)).values().iterator().next(); + final var objClass = obj.getClass(); + final var compiledField = objClass.getDeclaredField("compiled"); + compiledField.setAccessible(true); + assertTrue((boolean) compiledField.get(obj), "clear compute must compile"); + final var reflField = objClass.getDeclaredField("reflection"); + reflField.setAccessible(true); + assertTrue(reflField.get(obj) == ShaderManager.StageReflection.EMPTY, + "compute shaders must not receive the graphics-convention reflection; link reflects the compute-remapped copy"); + + final var spirvField = objClass.getDeclaredField("spirv"); + spirvField.setAccessible(true); + final ByteBuffer pristine = (ByteBuffer) spirvField.get(obj); + final ByteBuffer copy = MemoryUtil.memAlloc(pristine.remaining()); + copy.put(pristine.duplicate()).flip(); + try { + ShaderManager.remapSpirvForComputeSDLGPU(copy); + final List members = ShaderManager.reflectStage(copy, false) + .uboMembers().stream().map(ShaderManager.UboMember::name).toList(); + assertTrue(members.contains("u_extent"), + "link-time reflection of the pristine compute SPIR-V must expose the clear uniforms; got " + members); + } finally { + MemoryUtil.memFree(copy); + } + } + + @Test + void looseUniformsReflectAsBindingZeroUboMembers() { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source(), GL43.GL_COMPUTE_SHADER, SHADER, true); + final String src = pre != null ? pre.rewrittenSource() : source(); + final SpirvCompiler.Result r = SpirvCompiler.compile(src, Shaderc.shaderc_compute_shader, SHADER, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) fail(SHADER + " failed to compile: " + r.error() + "\nsource:\n" + src); + final ByteBuffer spirv = r.spirv(); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final List members = refl.uboMembers().stream().map(ShaderManager.UboMember::name).toList(); + assertTrue(members.contains("u_extent"), "clear uniforms must reflect as UBO members; got uboSize=" + refl.uboSize() + " members=" + members + " extraNames=" + refl.extraUniformNames()); + } finally { + MemoryUtil.memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeSpirvRemapTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeSpirvRemapTest.java new file mode 100644 index 000000000..3292c750f --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeSpirvRemapTest.java @@ -0,0 +1,269 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ComputeSpirvRemapTest { + + private static final String COMPUTE_MIXED = """ + #version 460 core + layout(local_size_x = 1) in; + + layout(std430, binding = 0) readonly buffer Visible { uint ids[]; } visible; + layout(std430, binding = 1) buffer Cmds { uint data[]; } cmds; + layout(std430, binding = 2) readonly buffer Meta { uint m[]; } meta; + layout(std430, binding = 3) buffer Counter { uint count; } counter; + + layout(rgba8, binding = 0) readonly uniform image2D srcImage; + layout(rgba8, binding = 1) writeonly uniform image2D dstImage; + + layout(std140, binding = 0) uniform Frustum { vec4 planes[6]; } frustum; + + void main() { + // touch every binding so glslang doesn't optimize them away + uint id = visible.ids[0]; + uint mm = meta.m[id]; + cmds.data[id] = mm; + atomicAdd(counter.count, 1u); + vec4 c = imageLoad(srcImage, ivec2(0)); + imageStore(dstImage, ivec2(0), c * frustum.planes[0]); + } + """; + + @Test + void mixedRoRwLayout_setsAndBindings() { + final ByteBuffer spirv = compile(COMPUTE_MIXED, Shaderc.shaderc_compute_shader); + try { + final ShaderManager.ComputeBindingMap map = ShaderManager.remapSpirvForComputeSDLGPU(spirv); + + // Two RO buffers, two RW + assertEquals(2, map.roSsboGlSlots().length, "two RO SSBOs"); + assertEquals(2, map.rwSsboGlSlots().length, "two RW SSBOs"); + // One RO image, one RW image + assertEquals(1, map.roStorageTextureGlSlots().length, "one RO storage image"); + assertEquals(1, map.rwStorageTextureGlSlots().length, "one RW storage image"); + // One UBO + assertEquals(1, map.uboGlSlots().length, "one UBO"); + + final ResourceLayout layout = captureResourceLayout(spirv); + // 0 samplers + 1 RO image + 2 RO buffers + assertEquals(3, layout.set0Bindings.size(), "set 0 should have 3 entries"); + assertEquals(Set.of(0, 1, 2), new TreeSet<>(layout.set0Bindings)); + // 1 RW image + 2 RW buffers + assertEquals(3, layout.set1Bindings.size(), "set 1 should have 3 entries"); + assertEquals(Set.of(0, 1, 2), new TreeSet<>(layout.set1Bindings)); + // 1 UBO at binding 0 + assertEquals(List.of(0), new ArrayList<>(layout.set2Bindings)); + assertEquals(0, layout.otherSetCount, "no resources outside sets 0/1/2"); + + assertEquals(2, layout.roSsbos.size(), "2 RO SSBOs in set 0"); for (int s : layout.roSsbos) assertEquals(0, s); + assertEquals(2, layout.rwSsbos.size(), "2 RW SSBOs in set 1"); for (int s : layout.rwSsbos) assertEquals(1, s); + assertEquals(1, layout.roImages.size(), "1 RO image in set 0"); for (int s : layout.roImages) assertEquals(0, s); + assertEquals(1, layout.rwImages.size(), "1 RW image in set 1"); for (int s : layout.rwImages) assertEquals(1, s); + assertEquals(1, layout.ubos.size(), "1 UBO in set 2"); for (int s : layout.ubos) assertEquals(2, s); + + assertContains(map.roSsboGlSlots(), 0); // visible + assertContains(map.roSsboGlSlots(), 2); // meta + assertContains(map.rwSsboGlSlots(), 1); // cmds + assertContains(map.rwSsboGlSlots(), 3); // counter + assertContains(map.roStorageTextureGlSlots(), 0); + assertContains(map.rwStorageTextureGlSlots(), 1); + assertContains(map.uboGlSlots(), 0); + + assertEquals(1, map.uboIsDefaultBlock().length); + assertFalse(map.uboIsDefaultBlock()[0]); + assertEquals(96, map.uboSizes()[0]); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static final class ResourceLayout { + final List set0Bindings = new ArrayList<>(); + final List set1Bindings = new ArrayList<>(); + final List set2Bindings = new ArrayList<>(); + int otherSetCount; + final List roSsbos = new ArrayList<>(); + final List rwSsbos = new ArrayList<>(); + final List roImages = new ArrayList<>(); + final List rwImages = new ArrayList<>(); + final List ubos = new ArrayList<>(); + } + + private static ResourceLayout captureResourceLayout(ByteBuffer spirv) { + final ResourceLayout out = new ResourceLayout(); + try (MemoryStack stack = MemoryStack.stackPush()) { + final PointerBuffer pCtx = stack.pointers(0); + if (Spvc.spvc_context_create(pCtx) != Spvc.SPVC_SUCCESS) fail("spvc_context_create"); + final long ctx = pCtx.get(0); + try { + final IntBuffer words = spirv.asIntBuffer(); + final PointerBuffer pIR = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, words, words.remaining(), pIR) != Spvc.SPVC_SUCCESS) fail("parse_spirv"); + final PointerBuffer pComp = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pIR.get(0), + Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pComp) != Spvc.SPVC_SUCCESS) fail("create_compiler"); + final long comp = pComp.get(0); + final PointerBuffer pRes = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(comp, pRes) != Spvc.SPVC_SUCCESS) fail("create_shader_resources"); + final long res = pRes.get(0); + + walkType(res, comp, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, (id, set, bind) -> { + recordSet(out, set, bind); + final boolean ro = isReadOnlyBlock(comp, id); + (ro ? out.roSsbos : out.rwSsbos).add(set); + }); + walkType(res, comp, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE, (id, set, bind) -> { + recordSet(out, set, bind); + final boolean ro = Spvc.spvc_compiler_has_decoration(comp, id, Spv.SpvDecorationNonWritable); + (ro ? out.roImages : out.rwImages).add(set); + }); + walkType(res, comp, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, (id, set, bind) -> { + recordSet(out, set, bind); + out.ubos.add(set); + }); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + return out; + } + + private static void recordSet(ResourceLayout out, int set, int bind) { + switch (set) { + case 0 -> out.set0Bindings.add(bind); + case 1 -> out.set1Bindings.add(bind); + case 2 -> out.set2Bindings.add(bind); + default -> out.otherSetCount++; + } + } + + private static boolean isReadOnlyBlock(long compiler, int varId) { + try (MemoryStack stack = MemoryStack.stackPush()) { + final PointerBuffer pDecorations = stack.pointers(0); + final PointerBuffer pNum = stack.pointers(0); + if (Spvc.spvc_compiler_get_buffer_block_decorations(compiler, varId, pDecorations, pNum) != Spvc.SPVC_SUCCESS) return false; + final long n = pNum.get(0); + if (n <= 0) return false; + final IntBuffer decs = MemoryUtil.memIntBuffer(pDecorations.get(0), (int) n); + for (int i = 0; i < n; i++) if (decs.get(i) == Spv.SpvDecorationNonWritable) return true; + return false; + } + } + + @FunctionalInterface + private interface ResourceVisitor { void visit(int id, int set, int binding); } + + private static void walkType(long resources, long compiler, int resourceType, ResourceVisitor v) { + try (MemoryStack stack = MemoryStack.stackPush()) { + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) return; + final int n = (int) pCount.get(0); + if (n == 0) return; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), n); + for (int i = 0; i < n; i++) { + final SpvcReflectedResource r = list.get(i); + final int set = Spvc.spvc_compiler_get_decoration(compiler, r.id(), Spv.SpvDecorationDescriptorSet); + final int bind = Spvc.spvc_compiler_get_decoration(compiler, r.id(), Spv.SpvDecorationBinding); + v.visit(r.id(), set, bind); + } + } + } + + private static final String COMPUTE_LOOSE_UNIFORMS = """ + #version 460 core + layout(local_size_x = 1) in; + + uniform float frameTime; + uniform vec4 tint; + + layout(rgba8, binding = 0) writeonly uniform image2D dst; + + void main() { + imageStore(dst, ivec2(0), tint * frameTime); + } + """; + + @Test + void looseUniforms_flaggedAsDefaultBlock() { + final ByteBuffer spirv = compile(COMPUTE_LOOSE_UNIFORMS, Shaderc.shaderc_compute_shader); + try { + final ShaderManager.ComputeBindingMap map = ShaderManager.remapSpirvForComputeSDLGPU(spirv); + assertEquals(1, map.uboGlSlots().length, "one synthetic UBO"); + assertTrue(map.uboIsDefaultBlock()[0], "loose-uniform block must be flagged as default"); + assertTrue(map.uboSizes()[0] >= 20, "declared size covers float + vec4"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static final String COMPUTE_NO_RESOURCES = """ + #version 460 core + layout(local_size_x = 1) in; + void main() {} + """; + + @Test + void noResources_emptyBindingMap() { + final ByteBuffer spirv = compile(COMPUTE_NO_RESOURCES, Shaderc.shaderc_compute_shader); + try { + final ShaderManager.ComputeBindingMap map = ShaderManager.remapSpirvForComputeSDLGPU(spirv); + assertEquals(0, map.roSsboGlSlots().length); + assertEquals(0, map.rwSsboGlSlots().length); + assertEquals(0, map.roStorageTextureGlSlots().length); + assertEquals(0, map.rwStorageTextureGlSlots().length); + assertEquals(0, map.uboGlSlots().length); + assertEquals(0, map.samplerGlSlots().length); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void mixedRoRw_reflectionSplitCounts() { + final ByteBuffer spirv = compile(COMPUTE_MIXED, Shaderc.shaderc_compute_shader); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + assertEquals(2, refl.numReadonlyStorageBuffers()); + assertEquals(2, refl.numReadwriteStorageBuffers()); + assertEquals(1, refl.numReadonlyStorageTextures()); + assertEquals(1, refl.numReadwriteStorageTextures()); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static void assertContains(int[] arr, int value) { + for (int v : arr) if (v == value) return; + fail("expected " + value + " in " + Arrays.toString(arr)); + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "compute_test", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("compute compile failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeStorageImageReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeStorageImageReflectionTest.java new file mode 100644 index 000000000..5f622d94a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ComputeStorageImageReflectionTest.java @@ -0,0 +1,60 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.TestPaths; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +class ComputeStorageImageReflectionTest { + + private static ShaderManager.ComputeBindingMap reflect(String name, String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_compute_shader, name, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) fail(name + " failed to compile: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + return ShaderManager.remapSpirvForComputeSDLGPU(spirv); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void qualifiedFormatsAndDimensionsAreReflected() { + final ShaderManager.ComputeBindingMap map = reflect("mixed.csh", """ + #version 460 core + layout(local_size_x = 1) in; + layout(binding = 0, rgba8) readonly uniform image2D u_ro; + layout(binding = 1, r32ui) writeonly uniform uimage3D u_rw; + void main() { + vec4 v = imageLoad(u_ro, ivec2(0)); + imageStore(u_rw, ivec3(0), uvec4(uint(v.r))); + } + """); + + assertEquals(1, map.roStorageTextureFormats().length); + assertEquals(InternalTextureFormat.RGBA8.getGlFormat(), map.roStorageTextureFormats()[0]); + assertEquals(GL11.GL_TEXTURE_2D, map.roStorageTextureTargets()[0]); + + assertEquals(1, map.rwStorageTextureFormats().length); + assertEquals(InternalTextureFormat.R32UI.getGlFormat(), map.rwStorageTextureFormats()[0]); + assertEquals(GL12.GL_TEXTURE_3D, map.rwStorageTextureTargets()[0]); + } + + @Test + void formatlessWriteonlyImageFallsBackToItsSampledType() { + final ShaderManager.ComputeBindingMap map = reflect("clear_image3d.csh", TestPaths.readString("src/main/resources/assets/angelica/shaders/sdlgpu/clear_image3d.csh")); + + assertEquals(1, map.rwStorageTextureFormats().length, "one writeonly uimage3D"); + assertEquals(InternalTextureFormat.R32UI.getGlFormat(), map.rwStorageTextureFormats()[0], "no layout format qualifier, so the unsigned sampled type picks the stand-in format"); + assertEquals(GL12.GL_TEXTURE_3D, map.rwStorageTextureTargets()[0]); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentOutputReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentOutputReflectionTest.java new file mode 100644 index 000000000..a7e56f257 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentOutputReflectionTest.java @@ -0,0 +1,86 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; + +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.lwjgl.system.MemoryUtil.memFree; + +class FragmentOutputReflectionTest { + + private static int maxOutputLocationOf(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_fragment_shader, "out.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "compile failed: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + return ShaderManager.reflectStage(spirv, false).maxOutputLocation(); + } finally { + memFree(spirv); + } + } + + @Test + void irisStyleMultiTargetOutputs() { + assertEquals(3, maxOutputLocationOf(""" + #version 460 core + layout ( location = 3 ) out vec4 iris_FragData3 ; + layout ( location = 2 ) out vec4 iris_FragData2 ; + layout ( location = 1 ) out vec4 iris_FragData1 ; + layout ( location = 0 ) out vec4 iris_FragData0 ; + void main() { + iris_FragData0 = vec4(1.0); + iris_FragData1 = vec4(2.0); + iris_FragData2 = vec4(3.0); + iris_FragData3 = vec4(4.0); + } + """)); + } + + @Test + void twoTargetOutputs() { + assertEquals(1, maxOutputLocationOf(""" + #version 460 core + layout ( location = 1 ) out vec4 a ; + layout ( location = 0 ) out vec4 b ; + void main() { a = vec4(1.0); b = vec4(0.0); } + """)); + } + + @Test + void implicitLocationZeroIsFound() { + assertEquals(0, maxOutputLocationOf(""" + #version 460 core + out vec4 fragColor; + void main() { fragColor = vec4(1.0); } + """)); + } + + @Test + void noOutputsYieldsMinusOne() { + assertEquals(-1, maxOutputLocationOf(""" + #version 460 core + void main() { } + """)); + } + + @Test + void vertexStageLeavesItUnset() { + final SpirvCompiler.Result r = SpirvCompiler.compile(""" + #version 460 core + layout ( location = 0 ) out vec4 vColor ; + void main() { vColor = vec4(1.0); gl_Position = vec4(0.0); } + """, Shaderc.shaderc_vertex_shader, "out.vert", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "compile failed: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + assertEquals(-1, ShaderManager.reflectStage(spirv, true).maxOutputLocation()); + } finally { + memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentStorageTextureReadGpuTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentStorageTextureReadGpuTest.java new file mode 100644 index 000000000..3ee04d361 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/FragmentStorageTextureReadGpuTest.java @@ -0,0 +1,259 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.sdl.SDL_GPUColorTargetDescription; +import org.lwjgl.sdl.SDL_GPUColorTargetInfo; +import org.lwjgl.sdl.SDL_GPUGraphicsPipelineCreateInfo; +import org.lwjgl.sdl.SDL_GPUGraphicsPipelineTargetInfo; +import org.lwjgl.sdl.SDL_GPUMultisampleState; +import org.lwjgl.sdl.SDL_GPURasterizerState; +import org.lwjgl.sdl.SDL_GPUTextureSamplerBinding; +import org.lwjgl.sdl.SDL_GPUVertexInputState; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.lwjgl.sdl.SDLGPU.*; + +class FragmentStorageTextureReadGpuTest { + + private static SdlTestRig rig; + private static ShaderManager sm; + + private static final int VOL = 8; + private static final int TARGET = 64; + + @BeforeAll + static void setUp() throws Exception { + rig = SdlTestRig.acquireRealDevice(); + sm = new ShaderManager(rig.device); + } + + @AfterAll + static void tearDown() { + SdlTestRig.releaseRealDevice(); + } + + private static final String VERTEX = String.join("\n", + "#version 460 core", + "void main() {", + " vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);", + " gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);", + "}", + ""); + + private static String fragment(int samplerCount) { + final StringBuilder sb = new StringBuilder(); + sb.append("#version 460 core\n"); + for (int i = 0; i < samplerCount; i++) sb.append("uniform sampler2D tex").append(i).append(";\n"); + sb.append("layout(r16ui) readonly uniform uimage3D voxel_img;\n"); + sb.append("layout(location = 0) out vec4 fragColor;\n"); + sb.append("void main() {\n"); + sb.append(" ivec2 p = ivec2(gl_FragCoord.xy);\n"); + sb.append(" ivec3 cell = ivec3(p.x % 8, p.y % 8, (p.x / 8 + p.y / 8) % 8);\n"); + sb.append(" uint v = imageLoad(voxel_img, cell).x;\n"); + sb.append(" vec4 acc = vec4(0.0);\n"); + for (int i = 0; i < samplerCount; i++) sb.append(" acc += texture(tex").append(i).append(", vec2(0.5)) * 0.0;\n"); + sb.append(" fragColor = vec4(float(v) / 255.0, float(v & 15u) / 15.0, float(v >> 4u) / 15.0, 1.0) + acc;\n"); + sb.append("}\n"); + return sb.toString(); + } + + private static int patternValue(int x, int y, int z) { + return (x == y) ? 255 - z * 16 : z * 32 + x * 2 + y; + } + + private int createVoxelTexture() { + final int glId = 9001; + final long handle = rig.resourceManager.createTexture(glId, GL12.GL_TEXTURE_3D, GL30.GL_R16UI, VOL, VOL, VOL, 1); + assertTrue(handle != 0, "voxel texture creation failed"); + final ByteBuffer data = MemoryUtil.memAlloc(VOL * VOL * VOL * 2); + for (int z = 0; z < VOL; z++) + for (int y = 0; y < VOL; y++) + for (int x = 0; x < VOL; x++) + data.putShort((short) patternValue(x, y, z)); + data.flip(); + try { + final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice()); + assertTrue(cb != 0, "no command buffer"); + final long cp = SDL_BeginGPUCopyPass(cb); + assertTrue(cp != 0, "no copy pass"); + rig.resourceManager.uploadToTexture3D(cp, data, handle, 0, 0, 0, VOL, VOL, VOL, 0); + SDL_EndGPUCopyPass(cp); + assertTrue(SDL_SubmitGPUCommandBuffer(cb), "upload submit failed"); + SDL_WaitForGPUIdle(rig.device.getDevice()); + } finally { + MemoryUtil.memFree(data); + } + return glId; + } + + private int linkProgram(int samplerCount) { + final int vs = sm.createShader(GL20.GL_VERTEX_SHADER); + sm.shaderSource(vs, VERTEX); + sm.compileShader(vs); + final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER); + sm.shaderSource(fs, fragment(samplerCount)); + sm.compileShader(fs); + final int prog = sm.createProgram(); + sm.attachShader(prog, vs); + sm.attachShader(prog, fs); + sm.linkProgram(prog); + final ShaderManager.ProgramObject po = sm.getProgram(prog); + assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog)); + assertEquals(samplerCount, po.fragmentResources.numSamplers(), "production sampler count"); + assertEquals(1, po.fragmentResources.numStorageTextures(), "production storage texture count"); + return prog; + } + + private void runCase(int samplerCount) throws IOException { + final int voxelGlId = createVoxelTexture(); + final long voxelHandle = rig.resourceManager.getTextureHandle(voxelGlId); + + final int targetGlId = 9100 + samplerCount; + final long targetHandle = rig.resourceManager.createTexture(targetGlId, GL11.GL_TEXTURE_2D, GL11.GL_RGBA8, TARGET, TARGET, 1, 1); + assertTrue(targetHandle != 0, "target creation failed"); + final int targetFormat = rig.resourceManager.getTextureMeta(targetGlId).sdlFormat(); + + final long[] dummyTex = new long[samplerCount]; + for (int i = 0; i < samplerCount; i++) { + final int id = 9200 + samplerCount * 10 + i; + dummyTex[i] = rig.resourceManager.createTexture(id, GL11.GL_TEXTURE_2D, GL11.GL_RGBA8, 1, 1, 1, 1); + assertTrue(dummyTex[i] != 0, "dummy sampler texture creation failed"); + } + + final ShaderManager.ProgramObject po = sm.getProgram(linkProgram(samplerCount)); + System.out.println("[GpuReadTest] S=" + samplerCount + + " VS=" + po.vertexResources + " FS=" + po.fragmentResources); + + final ShaderManager.ResourceCounts vr = po.vertexResources; + po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures()); + final ShaderManager.ResourceCounts fr = po.fragmentResources; + po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures()); + assertTrue(po.sdlVertexShader != 0, "SDL vertex shader creation failed"); + assertTrue(po.sdlFragmentShader != 0, "SDL fragment shader creation failed"); + + final long pipeline; + try (MemoryStack stack = MemoryStack.stackPush()) { + final SDL_GPUColorTargetDescription.Buffer colorDesc = SDL_GPUColorTargetDescription.calloc(1, stack); + colorDesc.get(0).format(targetFormat); + final SDL_GPUGraphicsPipelineTargetInfo targetInfo = SDL_GPUGraphicsPipelineTargetInfo.calloc(stack) + .num_color_targets(1) + .color_target_descriptions(colorDesc); + final SDL_GPUGraphicsPipelineCreateInfo ci = SDL_GPUGraphicsPipelineCreateInfo.calloc(stack) + .vertex_shader(po.sdlVertexShader) + .fragment_shader(po.sdlFragmentShader) + .primitive_type(SDL_GPU_PRIMITIVETYPE_TRIANGLELIST) + .rasterizer_state(SDL_GPURasterizerState.calloc(stack) + .cull_mode(SDL_GPU_CULLMODE_NONE) + .fill_mode(SDL_GPU_FILLMODE_FILL)) + .multisample_state(SDL_GPUMultisampleState.calloc(stack).sample_count(SDL_GPU_SAMPLECOUNT_1)) + .target_info(targetInfo) + .vertex_input_state(SDL_GPUVertexInputState.calloc(stack)); + pipeline = SDL_CreateGPUGraphicsPipeline(rig.device.getDevice(), ci); + } + assertTrue(pipeline != 0, "pipeline creation failed"); + + try (MemoryStack stack = MemoryStack.stackPush()) { + final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice()); + assertTrue(cb != 0, "no command buffer"); + final SDL_GPUColorTargetInfo.Buffer target = SDL_GPUColorTargetInfo.calloc(1, stack); + target.get(0).texture(targetHandle).load_op(SDL_GPU_LOADOP_CLEAR).store_op(SDL_GPU_STOREOP_STORE); + final ByteBuffer zeroUbo = stack.calloc(256); + for (int slot = 0; slot < po.vertexResources.numUBOs(); slot++) { + SDL_PushGPUVertexUniformData(cb, slot, zeroUbo); + } + for (int slot = 0; slot < po.fragmentResources.numUBOs(); slot++) { + SDL_PushGPUFragmentUniformData(cb, slot, zeroUbo); + } + final long pass = SDL_BeginGPURenderPass(cb, target, null); + assertTrue(pass != 0, "no render pass"); + SDL_BindGPUGraphicsPipeline(pass, pipeline); + if (samplerCount > 0) { + final SDL_GPUTextureSamplerBinding.Buffer samplers = SDL_GPUTextureSamplerBinding.calloc(samplerCount, stack); + final long defaultSampler = rig.resourceManager.getOrCreateDefaultSampler(); + for (int i = 0; i < samplerCount; i++) { + samplers.get(i).texture(dummyTex[i]).sampler(defaultSampler); + } + SDL_BindGPUFragmentSamplers(pass, 0, samplers); + } + SDL_BindGPUFragmentStorageTextures(pass, 0, stack.pointers(voxelHandle)); + SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0); + SDL_EndGPURenderPass(pass); + assertTrue(SDL_SubmitGPUCommandBuffer(cb), "draw submit failed"); + SDL_WaitForGPUIdle(rig.device.getDevice()); + } + + final ByteBuffer pixels = MemoryUtil.memAlloc(TARGET * TARGET * 4); + try { + final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice()); + assertTrue(cb != 0, "no readback command buffer"); + rig.resourceManager.downloadFromTexture(cb, targetHandle, 0, 0, TARGET, TARGET, 0, pixels); + final Path png = dumpPng(pixels, samplerCount); + // SDL's Y-flip means the readback may be row-inverted vs gl_FragCoord; either orientation + // is a fixed convention, not this bug - accept whichever matches. + final int direct = countMismatches(pixels, false, null); + final StringBuilder firstBad = new StringBuilder(); + final int flipped = countMismatches(pixels, true, firstBad); + final int mismatches = Math.min(direct, flipped); + assertEquals(0, mismatches, "fragment imageLoad visualizer diverged on " + mismatches + "/" + (TARGET * TARGET) + " pixels (S=" + samplerCount + ", direct=" + direct + " flipped=" + flipped + "); " + firstBad + "; inspect " + png); + } finally { + MemoryUtil.memFree(pixels); + } + } + + private static int countMismatches(ByteBuffer pixels, boolean flipY, StringBuilder firstBad) { + int mismatches = 0; + for (int py = 0; py < TARGET; py++) { + final int fragY = flipY ? TARGET - 1 - py : py; + for (int px = 0; px < TARGET; px++) { + final int cellX = px % VOL, cellY = fragY % VOL, cellZ = (px / VOL + fragY / VOL) % VOL; + final int expected = patternValue(cellX, cellY, cellZ); + final int got = pixels.get((py * TARGET + px) * 4) & 0xFF; + if (Math.abs(got - expected) > 1) { + if (mismatches == 0 && firstBad != null) { + firstBad.append("first mismatch at pixel (").append(px).append(',').append(py) + .append(") cell (").append(cellX).append(',').append(cellY).append(',').append(cellZ) + .append("): expected ").append(expected).append(" got ").append(got); + } + mismatches++; + } + } + } + return mismatches; + } + + private static Path dumpPng(ByteBuffer rgba, int samplerCount) throws IOException { + final Path out = Path.of("build", "test-artifacts"); + Files.createDirectories(out); + final java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(TARGET, TARGET, java.awt.image.BufferedImage.TYPE_INT_RGB); + for (int y = 0; y < TARGET; y++) { + for (int x = 0; x < TARGET; x++) { + final int i = (y * TARGET + x) * 4; + img.setRGB(x, y, ((rgba.get(i) & 0xFF) << 16) | ((rgba.get(i + 1) & 0xFF) << 8) | (rgba.get(i + 2) & 0xFF)); + } + } + final Path file = out.resolve("storage_read_s" + samplerCount + ".png").toAbsolutePath(); + javax.imageio.ImageIO.write(img, "png", file.toFile()); + System.out.println("[GpuReadTest] wrote " + file); + return file; + } + + @Test void fragmentImageLoadReadsCorrectTexels_noSamplers() throws IOException { runCase(0); } + @Test void fragmentImageLoadReadsCorrectTexels_twoSamplers() throws IOException { runCase(2); } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/GraphicsBindingMapSsboTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/GraphicsBindingMapSsboTest.java new file mode 100644 index 000000000..0b7a2f7f0 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/GraphicsBindingMapSsboTest.java @@ -0,0 +1,108 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +class GraphicsBindingMapSsboTest { + + private static final String FRAG_WITH_SSBO = """ + #version 460 core + layout(std430, binding = 5) readonly buffer Block { uint data[]; } blk; + layout(set = 0, binding = 0) uniform sampler2D s0; + layout(location = 0) in vec2 uv; + layout(location = 0) out vec4 o; + void main() { + uint x = blk.data[0]; + o = texture(s0, uv) + vec4(float(x)); + } + """; + + @Test + void extractsOriginalSsboBinding() { + final ByteBuffer spirv = compile(FRAG_WITH_SSBO, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.GraphicsBindingMap map = ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + assertEquals(1, map.roSsboGlSlots().length); + assertEquals(5, map.roSsboGlSlots()[0], "pre-remap binding decoration preserved"); + + final int[] setBindingForSsbo = findFirstResource(spirv, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER); + assertEquals(2, setBindingForSsbo[0], "fragment resource set"); + assertEquals(1, setBindingForSsbo[1], "binding 1 (after the one sampler at 0)"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void emptyMapForShaderWithoutSsbo() { + final String src = """ + #version 460 core + layout(set = 0, binding = 0) uniform sampler2D s0; + layout(location = 0) in vec2 uv; + layout(location = 0) out vec4 o; + void main() { o = texture(s0, uv); } + """; + final ByteBuffer spirv = compile(src, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.GraphicsBindingMap map = ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + assertEquals(0, map.roSsboGlSlots().length); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static int[] findFirstResource(ByteBuffer spirv, int resourceType) { + final int[] out = new int[] { -1, -1 }; + try (MemoryStack stack = MemoryStack.stackPush()) { + final PointerBuffer pCtx = stack.pointers(0); + if (Spvc.spvc_context_create(pCtx) != Spvc.SPVC_SUCCESS) fail("spvc_context_create"); + final long ctx = pCtx.get(0); + try { + final IntBuffer words = spirv.asIntBuffer(); + final PointerBuffer pIR = stack.pointers(0); + if (Spvc.spvc_context_parse_spirv(ctx, words, words.remaining(), pIR) != Spvc.SPVC_SUCCESS) fail("parse_spirv"); + final PointerBuffer pComp = stack.pointers(0); + if (Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pIR.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pComp) != Spvc.SPVC_SUCCESS) fail("create_compiler"); + final long comp = pComp.get(0); + final PointerBuffer pRes = stack.pointers(0); + if (Spvc.spvc_compiler_create_shader_resources(comp, pRes) != Spvc.SPVC_SUCCESS) fail("create_shader_resources"); + final long res = pRes.get(0); + + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(res, resourceType, pList, pCount) != Spvc.SPVC_SUCCESS) return out; + final int n = (int) pCount.get(0); + if (n == 0) return out; + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), n); + final SpvcReflectedResource r = list.get(0); + out[0] = Spvc.spvc_compiler_get_decoration(comp, r.id(), Spv.SpvDecorationDescriptorSet); + out[1] = Spvc.spvc_compiler_get_decoration(comp, r.id(), Spv.SpvDecorationBinding); + } finally { + Spvc.spvc_context_destroy(ctx); + } + } + return out; + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "frag_test", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("frag compile failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java new file mode 100644 index 000000000..d827f4a92 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java @@ -0,0 +1,271 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryUtil.memFree; + +class PerFrameBlockInjectorTest { + + private static final PerFrameUniformBlock BLOCK = new PerFrameUniformBlock(List.of( + new Member("cameraPosition", UniformType.VEC3), + new Member("frameTimeCounter", UniformType.FLOAT), + new Member("rainStrength", UniformType.FLOAT))); + + @Test + void dropsLooseDeclarationsAndInjectsTheBlock() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform vec3 cameraPosition; + uniform float rainStrength; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, rainStrength); } + """, BLOCK, null); + + assertTrue(out.contains("buffer AngelicaPerFrame")); + assertFalse(out.contains("uniform vec3 cameraPosition")); + assertFalse(out.contains("uniform float rainStrength")); + assertTrue(out.contains("vec4(cameraPosition, rainStrength)"), "use sites must be untouched"); + } + + @Test + void declaresEveryMemberEvenWhenUnused() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform float rainStrength; + out vec4 fragColor; + void main() { fragColor = vec4(rainStrength); } + """, BLOCK, null); + + for (Member m : BLOCK.members()) { + assertTrue(out.contains(PerFrameBlockInjector.std140Type(m.type()) + " " + m.name() + ";"), "missing member " + m.name()); + } + } + + @Test + void blockGoesAfterTheVersionDirective() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform float rainStrength; + void main() {} + """, BLOCK, null); + assertTrue(out.indexOf("#version") < out.indexOf("buffer AngelicaPerFrame")); + } + + @Test + void leavesMixedDeclarationAlone() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform float rainStrength, packOwnedValue; + void main() {} + """, BLOCK, null); + assertTrue(out.contains("uniform float rainStrength, packOwnedValue;")); + } + + @Test + void emptyMemberListIsANoOp() { + final String src = "#version 330 core\nvoid main() {}\n"; + assertEquals(src, PerFrameBlockInjector.inject(src, new PerFrameUniformBlock(List.of()), null)); + } + + @Test + void memberShadowedByAPackDeclarationIsRenamedNotRedeclared() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + const float rainStrength = 3.14159265359; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, rainStrength); } + """, BLOCK, null); + + assertFalse(out.contains(" float rainStrength;"), "would redefine the shader's own declaration"); + assertTrue(out.contains("angelica_pfb_unused_rainStrength"), "shadowed member must be renamed, not dropped"); + assertTrue(out.contains("const float rainStrength = 3.14159265359;"), "the pack's declaration must survive"); + + final SpirvCompiler.Result r = SpirvCompiler.compile(out, Shaderc.shaderc_fragment_shader, "shadowed.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "shadowed source failed to compile: " + r.error()); + memFree(r.spirv()); + } + + @Test + void functionLocalRedeclarationDoesNotShadowTheMember() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform vec3 cameraPosition; + vec3 ambient = pow(cameraPosition, vec3(0.75)); + out vec4 fragColor; + void main() { + vec4 cameraPosition = vec4(0); + fragColor = vec4(ambient, 1.0) + cameraPosition; + } + """, BLOCK, null); + + assertFalse(out.contains("uniform vec3 cameraPosition;")); + assertTrue(out.contains(" vec3 cameraPosition;"), "member must keep its real name"); + assertFalse(out.contains("angelica_pfb_unused_cameraPosition")); + assertTrue(out.contains("vec4 cameraPosition = vec4(0);"), "the local declaration must survive"); + + final SpirvCompiler.Result r = SpirvCompiler.compile(out, Shaderc.shaderc_fragment_shader, "localshadow.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "locally-shadowed source failed to compile: " + r.error()); + memFree(r.spirv()); + } + + @Test + void shadowingDoesNotChangeAnyOffset() { + final String plain = PerFrameBlockInjector.inject(""" + #version 330 core + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, rainStrength); } + """, BLOCK, null); + final String shadowed = PerFrameBlockInjector.inject(""" + #version 330 core + const float rainStrength = 1.0; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, rainStrength); } + """, BLOCK, null); + + assertEquals(offsetsOf(plain).values().stream().toList(), offsetsOf(shadowed).values().stream().toList(), "a renamed member must occupy the same slot as the name it replaced"); + } + + @Test + void uniformDeclaredWithADifferentTypeIsLeftAlone() { + final PerFrameUniformBlock block = new PerFrameUniformBlock(List.of( + new Member("cameraPosition", UniformType.VEC3), + new Member("isRightHanded", UniformType.INT))); + + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform bool isRightHanded; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, (true ^^ isRightHanded) ? 1.0 : 0.0); } + """, block, null); + + assertTrue(out.contains("uniform bool isRightHanded;"), "a type mismatch must stay on the push path"); + assertTrue(out.contains("angelica_pfb_unused_isRightHanded"), "its block slot must still be held"); + assertFalse(out.contains(" int isRightHanded;")); + + final SpirvCompiler.Result r = SpirvCompiler.compile(out, Shaderc.shaderc_fragment_shader, "booltype.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "bool-typed uniform failed to compile: " + r.error()); + memFree(r.spirv()); + } + + @Test + void uniformDeclaredWithTheMatchingTypeIsStillReplaced() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform float rainStrength; + out vec4 fragColor; + void main() { fragColor = vec4(rainStrength); } + """, BLOCK, null); + assertFalse(out.contains("uniform float rainStrength;")); + assertTrue(out.contains(" float rainStrength;")); + } + + @Test + void shaderReferencingNoMemberIsUntouched() { + final String src = """ + #version 330 core + uniform vec4 packOwnedColor; + out vec4 fragColor; + void main() { fragColor = packOwnedColor; } + """; + assertEquals(src, PerFrameBlockInjector.inject(src, BLOCK, null)); + } + + @Test + void oneReferenceStillDeclaresEveryMember() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + out vec4 fragColor; + void main() { fragColor = vec4(rainStrength); } + """, BLOCK, null); + for (Member m : BLOCK.members()) { + assertTrue(out.contains(PerFrameBlockInjector.std140Type(m.type()) + " " + m.name() + ";"), "missing member " + m.name()); + } + } + + private static final PerFrameUniformBlock PER_PASS = new PerFrameUniformBlock(List.of( + new Member("gbufferModelView", UniformType.MAT4), + new Member("fogColor", UniformType.VEC3))); + + @Test + void bothBlocksInjectInOneParse() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform vec3 cameraPosition; + uniform mat4 gbufferModelView; + out vec4 fragColor; + void main() { fragColor = gbufferModelView * vec4(cameraPosition, 1.0); } + """, BLOCK, PER_PASS); + + assertTrue(out.contains("binding = " + ShaderManager.PER_FRAME_BLOCK_BINDING + ") readonly buffer AngelicaPerFrame")); + assertTrue(out.contains("binding = " + ShaderManager.PER_PASS_BLOCK_BINDING + ") readonly buffer AngelicaPerPass")); + assertFalse(out.contains("uniform vec3 cameraPosition")); + assertFalse(out.contains("uniform mat4 gbufferModelView")); + assertTrue(out.contains(" vec3 fogColor;"), "unused per-pass member still declared in its block"); + } + + @Test + void unreferencedBlockIsNotInjected() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, 1.0); } + """, BLOCK, PER_PASS); + + assertTrue(out.contains("buffer AngelicaPerFrame")); + assertFalse(out.contains("buffer AngelicaPerPass"), "no per-pass member referenced"); + } + + private static LinkedHashMap offsetsOf(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_fragment_shader, "off.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "compile failed: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + final LinkedHashMap out = new LinkedHashMap<>(); + for (ShaderManager.UboMember m : ShaderManager.reflectStage(spirv, false).blocks()[ShaderManager.BLOCK_PER_FRAME].members()) { + out.put(m.name(), m.offset()); + } + return out; + } finally { + memFree(spirv); + } + } + + @Test + void injectedSourceCompilesAndReflects() { + final String out = PerFrameBlockInjector.inject(""" + #version 330 core + uniform vec3 cameraPosition; + uniform float rainStrength; + out vec4 fragColor; + void main() { fragColor = vec4(cameraPosition, rainStrength); } + """, BLOCK, null); + + final SpirvCompiler.Result r = SpirvCompiler.compile(out, Shaderc.shaderc_fragment_shader, "injected.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "injected source failed to compile: " + r.error()); + + final ByteBuffer spirv = r.spirv(); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final List members = refl.blocks()[ShaderManager.BLOCK_PER_FRAME].members(); + assertEquals(List.of("cameraPosition", "frameTimeCounter", "rainStrength"), members.stream().map(ShaderManager.UboMember::name).toList()); + assertEquals(0, members.get(0).offset()); + assertEquals(12, members.get(1).offset()); + assertEquals(16, members.get(2).offset()); + } finally { + memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockLocationRoutingTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockLocationRoutingTest.java new file mode 100644 index 000000000..0fab66db3 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockLocationRoutingTest.java @@ -0,0 +1,105 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryUtil.memFree; + +class PerFrameBlockLocationRoutingTest { + + private static final PerFrameUniformBlock PER_FRAME = new PerFrameUniformBlock(List.of( + new Member("cameraPosition", UniformType.VEC3), + new Member("frameTimeCounter", UniformType.FLOAT))); + + private static final PerFrameUniformBlock PER_PASS = new PerFrameUniformBlock(List.of( + new Member("gbufferModelView", UniformType.MAT4))); + + private static final String SOURCE = """ + #version 330 core + uniform vec3 cameraPosition; + uniform float frameTimeCounter; + uniform mat4 gbufferModelView; + uniform float packOwned; + out vec4 fragColor; + void main() { + fragColor = gbufferModelView * vec4(cameraPosition, frameTimeCounter * packOwned); + } + """; + + private static ShaderManager.ProgramObject linkedProgram() { + final String injected = PerFrameBlockInjector.inject(SOURCE, PER_FRAME, PER_PASS); + final SpirvCompiler.Result r = SpirvCompiler.compile(injected, Shaderc.shaderc_fragment_shader, "routing.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "compile failed: " + r.error()); + + final ByteBuffer spirv = r.spirv(); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final ShaderManager.ProgramObject prog = new ShaderManager.ProgramObject(); + ShaderManager.applyUboMembers(prog, refl, false); + ShaderManager.applyBlockMembers(prog, refl); + prog.buildUniformSlotArrays(); + return prog; + } finally { + memFree(spirv); + } + } + + @Test + void blockMembersGetLocationsCarryingTheReflectedOffset() { + final ShaderManager.ProgramObject prog = linkedProgram(); + + for (String name : List.of("cameraPosition", "frameTimeCounter")) { + final int loc = prog.nameToLocation.getInt(name); + assertTrue(loc >= 0, name + " must have a location despite its loose declaration being stripped"); + assertNotNull(prog.blockInfoBySlot[ShaderManager.BLOCK_PER_FRAME][loc], name + " must route to the per-frame block"); + } + final int mvLoc = prog.nameToLocation.getInt("gbufferModelView"); + assertTrue(mvLoc >= 0); + assertNotNull(prog.blockInfoBySlot[ShaderManager.BLOCK_PER_PASS][mvLoc], "gbufferModelView must route to the per-pass block"); + assertNull(prog.blockInfoBySlot[ShaderManager.BLOCK_PER_FRAME][mvLoc], "gbufferModelView must not also route to the per-frame block"); + + assertEquals(0, prog.blockInfoBySlot[ShaderManager.BLOCK_PER_FRAME][prog.nameToLocation.getInt("cameraPosition")].offset()); + assertEquals(12, prog.blockInfoBySlot[ShaderManager.BLOCK_PER_FRAME][prog.nameToLocation.getInt("frameTimeCounter")].offset()); + assertEquals(0, prog.blockInfoBySlot[ShaderManager.BLOCK_PER_PASS][mvLoc].offset()); + } + + @Test + void blockMembersNeverAlsoRouteToThePerProgramUbo() { + final ShaderManager.ProgramObject prog = linkedProgram(); + for (String name : List.of("cameraPosition", "frameTimeCounter", "gbufferModelView")) { + final int loc = prog.nameToLocation.getInt(name); + assertNull(prog.vsInfoBySlot[loc], name + " must not also be a VS UBO member"); + assertNull(prog.fsInfoBySlot[loc], name + " must not also be an FS UBO member"); + } + } + + @Test + void nonMemberUniformStaysOnTheUboPath() { + final ShaderManager.ProgramObject prog = linkedProgram(); + final int loc = prog.nameToLocation.getInt("packOwned"); + assertTrue(loc >= 0); + assertNull(prog.blockInfoBySlot[ShaderManager.BLOCK_PER_FRAME][loc], "packOwned is not a block member"); + assertNull(prog.blockInfoBySlot[ShaderManager.BLOCK_PER_PASS][loc], "packOwned is not a block member"); + assertNotNull(prog.fsInfoBySlot[loc], "packOwned must remain a normal FS UBO member"); + } + + @Test + void blockSizesAndBindingsAreRecorded() { + final ShaderManager.ProgramObject prog = linkedProgram(); + assertEquals(16, prog.blockSize[ShaderManager.BLOCK_PER_FRAME], "vec3@0 + float@12"); + assertEquals(64, prog.blockSize[ShaderManager.BLOCK_PER_PASS], "one mat4"); + assertEquals(ShaderManager.PER_FRAME_BLOCK_BINDING, prog.blockBinding[ShaderManager.BLOCK_PER_FRAME]); + assertEquals(ShaderManager.PER_PASS_BLOCK_BINDING, prog.blockBinding[ShaderManager.BLOCK_PER_PASS]); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReadOnlyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReadOnlyTest.java new file mode 100644 index 000000000..28fd496ca --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReadOnlyTest.java @@ -0,0 +1,49 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryUtil.memFree; + +class PerFrameBlockReadOnlyTest { + + private static final PerFrameUniformBlock BLOCK = new PerFrameUniformBlock(List.of( + new Member("cameraPosition", UniformType.VEC3), + new Member("rainStrength", UniformType.FLOAT))); + + private static final PerFrameUniformBlock PER_PASS = new PerFrameUniformBlock(List.of(new Member("gbufferModelView", UniformType.MAT4))); + + private static final String DUAL_SOURCE = """ + #version 330 core + out vec4 fragColor; + void main() { fragColor = gbufferModelView * vec4(cameraPosition, rainStrength); } + """; + + @Test + void injectedBlocksAreDecoratedNonWritable() { + final String injected = PerFrameBlockInjector.inject(DUAL_SOURCE, BLOCK, PER_PASS); + final SpirvCompiler.Result r = SpirvCompiler.compile(injected, Shaderc.shaderc_fragment_shader, "readonly.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "compile failed: " + r.error()); + + final ByteBuffer spirv = r.spirv(); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + for (int b = 0; b < ShaderManager.BLOCK_COUNT; b++) { + final ShaderManager.BlockReflection block = refl.blocks()[b]; + assertTrue(block.size() > 0, "block " + b + " must be present for this assertion to mean anything"); + assertTrue(block.readOnly(), "block " + b + " must carry NonWritable or Vulkan rejects every pipeline that uses it"); + } + } finally { + memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReflectionTest.java new file mode 100644 index 000000000..78e09366a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockReflectionTest.java @@ -0,0 +1,106 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.lwjgl.system.MemoryUtil.memFree; +class PerFrameBlockReflectionTest { + + private static final String BLOCK_GLSL = """ + layout(std140) buffer AngelicaPerFrame { + vec3 cameraPosition; + float frameTimeCounter; + mat4 gbufferModelView; + vec4 fogColor; + float rainStrength; + }; + """; + + private static String shaderUsing(String expr) { + return "#version 330 core\n" + BLOCK_GLSL + "out vec4 fragColor;\nvoid main() { fragColor = " + expr + "; }\n"; + } + + @Test + void reflectsStorageBlockMembersAtStd140Offsets() { + final Map offsets = perFrameOffsetsOf(shaderUsing("vec4(cameraPosition, 1.0)")); + + assertEquals(0, offsets.get("cameraPosition")); + assertEquals(12, offsets.get("frameTimeCounter")); + assertEquals(16, offsets.get("gbufferModelView")); + assertEquals(80, offsets.get("fogColor")); + assertEquals(96, offsets.get("rainStrength")); + } + + + @Test + void offsetsAreIdenticalAcrossProgramsReferencingDifferentMembers() { + assertEquals(perFrameOffsetsOf(shaderUsing("vec4(cameraPosition, 1.0)")), perFrameOffsetsOf(shaderUsing("vec4(rainStrength)")), "a shader touching only the last member must still see every member at the same offset"); + } + + @Test + void ignoresUnrelatedStorageBlocks() { + final String src = """ + #version 430 core + layout(std430) buffer PackOwnedBuffer { vec4 packData[4]; }; + out vec4 fragColor; + void main() { fragColor = packData[0]; } + """; + final ShaderManager.StageReflection refl = reflect(src); + for (int b = 0; b < ShaderManager.BLOCK_COUNT; b++) { + assertTrue(refl.blocks()[b].members().isEmpty()); + assertEquals(-1, refl.blocks()[b].binding()); + assertEquals(0, refl.blocks()[b].size()); + } + } + + @Test + void reportsBlockSizeAndBinding() { + final ShaderManager.BlockReflection block = reflect(shaderUsing("vec4(rainStrength)")).blocks()[ShaderManager.BLOCK_PER_FRAME]; + assertEquals(100, block.size()); + assertTrue(block.binding() >= 0); + } + + @Test + void reflectsThePerPassBlockIndependently() { + final String src = """ + #version 330 core + layout(std140) buffer AngelicaPerPass { + mat4 gbufferModelView; + vec3 fogColor; + }; + out vec4 fragColor; + void main() { fragColor = gbufferModelView * vec4(fogColor, 1.0); } + """; + final ShaderManager.StageReflection refl = reflect(src); + final ShaderManager.BlockReflection perPass = refl.blocks()[ShaderManager.BLOCK_PER_PASS]; + assertEquals(0, refl.blocks()[ShaderManager.BLOCK_PER_FRAME].size(), "per-frame block absent"); + assertEquals(2, perPass.members().size()); + assertEquals(0, perPass.members().get(0).offset()); + assertEquals(64, perPass.members().get(1).offset()); + } + + private static Map perFrameOffsetsOf(String source) { + final Map out = new LinkedHashMap<>(); + for (ShaderManager.UboMember m : reflect(source).blocks()[ShaderManager.BLOCK_PER_FRAME].members()) out.put(m.name(), m.offset()); + return out; + } + + private static ShaderManager.StageReflection reflect(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_fragment_shader, "test.frag", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(r.spirv(), () -> "shaderc failed: " + r.error()); + final ByteBuffer spirv = r.spirv(); + try { + return ShaderManager.reflectStage(spirv, false); + } finally { + memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java new file mode 100644 index 000000000..6e380efaf --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java @@ -0,0 +1,138 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL43; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PrewarmSingleParseEquivalenceTest { + + private static String legacy(String source, int glShaderType) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, "test", true); + String src = pre != null ? pre.rewrittenSource() : source; + if (glShaderType == GL20.GL_VERTEX_SHADER) { + src = ClipZRemap.injectGLToVulkanClipZ(src); + } + src = SamplerStripper.stripUnused(src); + return src; + } + + private static void assertEquivalent(String label, String source, int glShaderType) { + GlslVulkanPreprocess.clearCache(); + final String legacyOut = legacy(source, glShaderType); + GlslVulkanPreprocess.clearCache(); + final String parseOnceOut = ShaderManager.applyPrewarmTransforms(source, glShaderType); + assertEquals(legacyOut, parseOnceOut, "single-parse vs chained pipeline diverged for " + label); + } + + @Test + void minimalFragment_noTransformsNeeded() { + final String src = "#version 460 core\n" + + "layout(location = 0) out vec4 fragColor;\n" + + "void main() { fragColor = vec4(1.0); }\n"; + assertEquivalent("minimal-fragment", src, GL20.GL_FRAGMENT_SHADER); + } + + @Test + void minimalVertex_depthRemapInjected() { + final String src = "#version 460 core\n" + + "layout(location = 0) in vec3 a_Position;\n" + + "void main() { gl_Position = vec4(a_Position, 1.0); }\n"; + assertEquivalent("minimal-vertex", src, GL20.GL_VERTEX_SHADER); + } + + @Test + void fragmentWithUnusedSampler_strippedAndIdsRewritten() { + final String src = "#version 460 core\n" + + "uniform sampler2D u_Unused;\n" + + "uniform sampler2D u_Used;\n" + + "layout(location = 0) out vec4 fragColor;\n" + + "void main() {\n" + + " fragColor = texture(u_Used, vec2(0.5));\n" + + "}\n"; + assertEquivalent("frag-unused-sampler", src, GL20.GL_FRAGMENT_SHADER); + } + + @Test + void vertexWithUnlocatedInputs_layoutLocationsInserted() { + final String src = "#version 460 core\n" + + "layout(location = 0) in vec3 a_Position;\n" + + "in vec2 a_TexCoord;\n" + + "in vec3 a_Normal;\n" + + "out vec2 v_TexCoord;\n" + + "void main() {\n" + + " v_TexCoord = a_TexCoord;\n" + + " gl_Position = vec4(a_Position + a_Normal, 1.0);\n" + + "}\n"; + assertEquivalent("vertex-unlocated-inputs", src, GL20.GL_VERTEX_SHADER); + } + + @Test + void vertexWithBuiltinIdRewrites() { + final String src = "#version 460 core\n" + + "void main() {\n" + + " int v = gl_VertexID;\n" + + " int i = gl_InstanceID;\n" + + " gl_Position = vec4(float(v + i), 0.0, 0.0, 1.0);\n" + + "}\n"; + assertEquivalent("vertex-builtin-ids", src, GL20.GL_VERTEX_SHADER); + } + + @Test + void fragmentWithBoolUniformsAndSamplerRename() { + final String src = "#version 460 core\n" + + "uniform bool u_Enabled;\n" + + "uniform float u_Gain = 1.5;\n" + + "layout(location = 0) out vec4 fragColor;\n" + + "void main() {\n" + + " fragColor = vec4(u_Enabled ? u_Gain : 0.0);\n" + + "}\n"; + assertEquivalent("frag-bool-uniform-init", src, GL20.GL_FRAGMENT_SHADER); + } + + @Test + void samplerOnlyReferencedInsidePreprocessorBlock_preservedConsistently() { + final String src = "#version 460 core\n" + + "#define FOO 1\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "void main() {\n" + + "#if FOO\n" + + " float a = textureLod(u_S, vec2(0), 0.0).r;\n" + + "#endif\n" + + "}\n"; + assertEquivalent("sampler-in-preprocessor-block", src, GL20.GL_FRAGMENT_SHADER); + } + + @Test + void compute_noVertexOnlyPasses() { + final String src = "#version 460 core\n" + + "layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;\n" + + "uniform sampler2D u_Unused;\n" + + "void main() {}\n"; + assertEquivalent("compute-empty", src, GL43.GL_COMPUTE_SHADER); + } + + @Test + void geometry_noVertexOnlyPasses() { + final String src = "#version 460 core\n" + + "layout(triangles) in;\n" + + "layout(triangle_strip, max_vertices = 3) out;\n" + + "void main() {\n" + + " for (int i = 0; i < 3; i++) {\n" + + " gl_Position = gl_in[i].gl_Position;\n" + + " EmitVertex();\n" + + " }\n" + + " EndPrimitive();\n" + + "}\n"; + assertEquivalent("geometry-passthrough", src, GL32.GL_GEOMETRY_SHADER); + } + + @Test + void unparseable_fallsBackToInputUnchanged() { + final String src = "this is not valid GLSL @@@@\n"; + assertEquivalent("unparseable", src, GL20.GL_FRAGMENT_SHADER); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSourceFidelityTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSourceFidelityTest.java new file mode 100644 index 000000000..59128ae5a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSourceFidelityTest.java @@ -0,0 +1,48 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; + +import static org.junit.jupiter.api.Assertions.*; + +class PrewarmSourceFidelityTest { + + private static final String RAW = """ + #version 460 core + in vec3 a_PosId; + void main() { + gl_Position = vec4(a_PosId, 1.0); + } + """; + + private static final String CLIP_Z = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;"; + + @BeforeEach + void reset() { + ShaderManager.clearPrewarmCache(); + } + + @Test + void prewarmHitStoresTheTransformedSourceNotTheRawInput() { + ShaderManager.prewarmSpirv(RAW, GL20.GL_VERTEX_SHADER); + + final ShaderManager sm = new ShaderManager(null); + final int shader = sm.createShader(GL20.GL_VERTEX_SHADER); + sm.shaderSource(shader, RAW); + + final String stored = sm.getShaderSource(shader); + assertNotEquals(RAW, stored, "a prewarm hit must not leave the raw pre-transform source on the shader"); + assertTrue(stored.contains(CLIP_Z), "stored source must carry the GL->Vulkan depth remap that the cached SPIR-V was built with\n\n" + stored); + } + + @Test + void prewarmMissAlsoStoresTheTransformedSource() { + final ShaderManager sm = new ShaderManager(null); + final int shader = sm.createShader(GL20.GL_VERTEX_SHADER); + sm.shaderSource(shader, RAW); + + final String stored = sm.getShaderSource(shader); + assertTrue(stored.contains(CLIP_Z), "the non-prewarm path must agree with the prewarm path\n\n" + stored); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ReadOnlyStorageTextureDescriptorTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ReadOnlyStorageTextureDescriptorTest.java new file mode 100644 index 000000000..e5a7250e7 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ReadOnlyStorageTextureDescriptorTest.java @@ -0,0 +1,155 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL20; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spv; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.lwjgl.system.MemoryStack.stackPush; + +class ReadOnlyStorageTextureDescriptorTest { + + private static final String FRAGMENT_READONLY_IMAGE = String.join("\n", + "#version 460 core", + "uniform sampler2D gtexture;", + "layout(r16ui) readonly uniform uimage3D voxel_img;", + "layout(location = 0) out vec4 fragColor;", + "void main() {", + " uint v = imageLoad(voxel_img, ivec3(1, 2, 3)).x;", + " fragColor = texture(gtexture, vec2(0.5)) + vec4(float(v));", + "}", + ""); + + private static String preprocess(String source, int glShaderType) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, "readonly-storage-test", true); + return pre == null ? source : pre.rewrittenSource(); + } + + private static ByteBuffer compileRewritten() { + final String source = preprocess(FRAGMENT_READONLY_IMAGE, GL20.GL_FRAGMENT_SHADER); + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_fragment_shader, "readonly-storage-test", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) fail("compile failed: " + r.error() + "\nsource:\n" + source); + return r.spirv(); + } + + private static Map bindingsOf(ByteBuffer spirv, int resourceType) { + final Map out = new LinkedHashMap<>(); + try (MemoryStack stack = stackPush()) { + final PointerBuffer pCtx = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create(pCtx)); + final IntBuffer words = spirv.asIntBuffer(); + final PointerBuffer pIR = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_parse_spirv(pCtx.get(0), words, words.remaining(), pIR)); + final PointerBuffer pCompiler = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create_compiler(pCtx.get(0), Spvc.SPVC_BACKEND_GLSL, pIR.get(0), Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler)); + final PointerBuffer pResources = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_compiler_create_shader_resources(pCompiler.get(0), pResources)); + + final PointerBuffer pList = stack.pointers(0); + final PointerBuffer pCount = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_resources_get_resource_list_for_type(pResources.get(0), resourceType, pList, pCount)); + final int count = (int) pCount.get(0); + if (count > 0) { + final SpvcReflectedResource.Buffer list = SpvcReflectedResource.create(pList.get(0), count); + for (int i = 0; i < count; i++) { + out.put(list.get(i).nameString(), Spvc.spvc_compiler_get_decoration(pCompiler.get(0), list.get(i).id(), Spv.SpvDecorationBinding)); + } + } + Spvc.spvc_context_destroy(pCtx.get(0)); + } + return out; + } + + private static List namesOf(ByteBuffer spirv, int resourceType) { + return new ArrayList<>(bindingsOf(spirv, resourceType).keySet()); + } + + @Test + void readOnlyImageBecomesSeparateTextureReadByTexelFetch() { + final String out = preprocess(FRAGMENT_READONLY_IMAGE, GL20.GL_FRAGMENT_SHADER); + + assertTrue(out.contains("uniform utexture3D voxel_img"), "read-only image must become a separate texture:\n" + out); + assertFalse(out.contains("uimage3D"), "no storage image may survive:\n" + out); + assertTrue(out.contains("texelFetch(voxel_img, ivec3(1, 2, 3), 0)"), "imageLoad must become a lod-0 texelFetch:\n" + out); + assertTrue(out.contains(GlslVulkanPreprocess.SAMPLERLESS_EXTENSION), "texelFetch on a bare texture needs the samplerless extension:\n" + out); + assertTrue(out.indexOf("#version") < out.indexOf(GlslVulkanPreprocess.SAMPLERLESS_EXTENSION), "the extension directive must follow #version:\n" + out); + } + + @Test + void extensionIsAnchoredToTheRealVersionDirectiveNotACommentMentioningIt() { + final String source = "// ported, bumped #version to 150\n" + FRAGMENT_READONLY_IMAGE; + final String out = preprocess(source, GL20.GL_FRAGMENT_SHADER); + + final int realVersion = out.indexOf("#version 460"); + assertTrue(realVersion >= 0, "the real directive must survive:\n" + out); + assertTrue(out.indexOf(GlslVulkanPreprocess.SAMPLERLESS_EXTENSION) > realVersion, "anchoring on the first textual '#version' would emit the extension before the real directive, which glslang rejects:\n" + out); + } + + @Test + void extensionIsEmittedWhenTheVersionLineHasNoTrailingNewline() { + final String source = "#version 460 core\nlayout(r16ui) readonly uniform uimage3D voxel_img;\nlayout(location = 0) out vec4 fragColor;\nvoid main() { fragColor = vec4(float(imageLoad(voxel_img, ivec3(0)).x)); }"; + final String out = preprocess(source, GL20.GL_FRAGMENT_SHADER); + + assertTrue(out.contains(GlslVulkanPreprocess.SAMPLERLESS_EXTENSION), "the extension must not be dropped:\n" + out); + assertTrue(out.contains("utexture3D voxel_img"), "the rewrite must still happen:\n" + out); + } + + @Test + void separateTextureSurvivesCompilationAsSeparateImage() { + final ByteBuffer spirv = compileRewritten(); + try { + assertEquals(List.of("voxel_img"), namesOf(spirv, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE), "voxel_img must reflect as a separate image (SAMPLED_IMAGE descriptor)"); + assertEquals(List.of(), namesOf(spirv, Spvc.SPVC_RESOURCE_TYPE_STORAGE_IMAGE), "nothing may reflect as a storage image"); + assertEquals(List.of("gtexture"), namesOf(spirv, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE), "only gtexture is a real combined sampler"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void separateTextureIsCountedAsStorageTextureNotSampler() { + final ByteBuffer spirv = compileRewritten(); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + + assertEquals(1, refl.counts().numSamplers(), "only gtexture consumes a sampler slot"); + assertEquals(1, refl.counts().numStorageTextures(), "voxel_img must be handed to SDL as a storage texture"); + assertEquals(List.of("gtexture"), refl.samplerNames()); + assertEquals(List.of("voxel_img"), refl.storageImageNames(), "StorageTextureBinder binds by this list, so voxel_img must appear in it"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void separateTextureBindsAfterTheSamplers() { + final ByteBuffer spirv = compileRewritten(); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + + assertEquals(0, bindingsOf(spirv, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE).get("gtexture"), "the sampler keeps binding 0"); + assertEquals(1, bindingsOf(spirv, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE).get("voxel_img"), "SDL lays set 2 out as samplers then storage textures, so one sampler puts voxel_img at binding 1"); + } finally { + MemoryUtil.memFree(spirv); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformDedupTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformDedupTest.java new file mode 100644 index 000000000..3156433ea --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformDedupTest.java @@ -0,0 +1,142 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineApplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SDLGPUUniformDedupTest { + + private PipelineApplier applier; + private ContextState st; + private ShaderManager.ProgramObject prog; + private UniformStaging us; + + @BeforeEach + void setUp() { + applier = new PipelineApplier(null, null, null, null, null, null, null, null, null); + st = new ContextState(); + prog = new ShaderManager.ProgramObject(); + prog.linked = true; + prog.vertexUboSize = 64; + prog.fragmentUboSize = 16; + prog.nextUniformLocation = 3; + for (int i = 0; i < 3; i++) { + prog.vertexMemberInfo.put(i, new ShaderManager.UniformMemberInfo( + i * 16, 16, 0, true, 4, 1, 0, 1)); + } + prog.fragmentMemberInfo.put(2, new ShaderManager.UniformMemberInfo(0, 16, 0, false, 4, 1, 0, 1)); + prog.buildUniformSlotArrays(); + st.boundProgramObj = prog; + st.boundProgram = 1; + us = st.uniformStaging(prog); + } + + @AfterEach + void tearDown() { + st.releaseUniformStaging(prog); + } + + @Test + void firstSet_dirtiesAndWritesUbo() { + final float[] a = applier.reuseOrAlloc(st, 0, 4); + a[0] = 1f; a[1] = 2f; a[2] = 3f; a[3] = 4f; + applier.putUniform(st, 0, a); + assertTrue(us.vsUniformDirty); + assertEquals(1f, us.vsUniformFb.get(0)); + assertEquals(4f, us.vsUniformFb.get(3)); + } + + @Test + void setSameValueTwice_secondCallDoesNotDirty() { + final float[] a = applier.reuseOrAlloc(st, 0, 4); + a[0] = 1f; a[1] = 2f; a[2] = 3f; a[3] = 4f; + applier.putUniform(st, 0, a); + us.vsUniformDirty = false; + + // Caller reuses the same backing array via reuseOrAlloc; writes the same values back. + final float[] b = applier.reuseOrAlloc(st, 0, 4); + assertSame(a, b, "reuseOrAlloc should return the cached array"); + b[0] = 1f; b[1] = 2f; b[2] = 3f; b[3] = 4f; + applier.putUniform(st, 0, b); + assertFalse(us.vsUniformDirty, "same-value reset must not re-dirty"); + } + + @Test + void setDifferentValue_dirties() { + final float[] a = applier.reuseOrAlloc(st, 0, 4); + a[0] = 1f; a[1] = 2f; a[2] = 3f; a[3] = 4f; + applier.putUniform(st, 0, a); + us.vsUniformDirty = false; + + final float[] b = applier.reuseOrAlloc(st, 0, 4); + b[0] = 1f; b[1] = 2f; b[2] = 3f; b[3] = 99f; + applier.putUniform(st, 0, b); + assertTrue(us.vsUniformDirty); + assertEquals(99f, us.vsUniformFb.get(3)); + } + + @Test + void differentSlots_independent() { + final float[] a = applier.reuseOrAlloc(st, 0, 4); + a[0] = 1f; a[1] = 2f; a[2] = 3f; a[3] = 4f; + applier.putUniform(st, 0, a); + final float[] b = applier.reuseOrAlloc(st, 1, 4); + b[0] = 5f; b[1] = 6f; b[2] = 7f; b[3] = 8f; + applier.putUniform(st, 1, b); + // slot 1 lives at byte offset 16 = float index 4 + assertEquals(1f, us.vsUniformFb.get(0)); + assertEquals(5f, us.vsUniformFb.get(4)); + assertEquals(8f, us.vsUniformFb.get(7)); + } + + @Test + void fragmentSlot_independentDirtyFlag() { + final float[] a = applier.reuseOrAlloc(st, 2, 4); + a[0] = 9f; a[1] = 10f; a[2] = 11f; a[3] = 12f; + applier.putUniform(st, 2, a); + assertTrue(us.vsUniformDirty, "slot 2 has VS member at offset 32"); + assertTrue(us.fsUniformDirty, "slot 2 also has FS member at offset 0"); + assertEquals(9f, us.vsUniformFb.get(8)); + assertEquals(9f, us.fsUniformFb.get(0)); + } + + @Test + void outOfRangeLocation_noCrash_noDirty() { + applier.putUniform(st, 999, new float[]{1f, 2f, 3f, 4f}); + applier.putUniform(st, -1, new float[]{1f, 2f, 3f, 4f}); + assertFalse(us.vsUniformDirty); + assertFalse(us.fsUniformDirty); + } + + @Test + void noProgramBound_reuseOrAllocReturnsFresh_putIsNoOp() { + st.boundProgramObj = null; + final float[] a = applier.reuseOrAlloc(st, 0, 4); + assertEquals(4, a.length); + final float[] b = applier.reuseOrAlloc(st, 0, 4); + assertNotSame(a, b, "no caching without bound program"); + applier.putUniform(st, 0, a); + } + + @Test + void lengthChange_writesThrough() { + final float[] a = applier.reuseOrAlloc(st, 0, 4); + a[0] = 1f; a[1] = 2f; a[2] = 3f; a[3] = 4f; + applier.putUniform(st, 0, a); + us.vsUniformDirty = false; + final float[] c = applier.reuseOrAlloc(st, 0, 2); + assertNotSame(a, c); + c[0] = 1f; c[1] = 2f; + applier.putUniform(st, 0, c); + assertTrue(us.vsUniformDirty); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformPackingTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformPackingTest.java new file mode 100644 index 000000000..3a83e0638 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SDLGPUUniformPackingTest.java @@ -0,0 +1,133 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SDLGPUUniformPackingTest { + + private static FloatBuffer wrap(float... values) { + final FloatBuffer fb = MemoryUtil.memCallocFloat(values.length); + fb.put(values).flip(); + return fb; + } + + private static void assertEq(float expected, float actual, String at) { + assertEquals(expected, actual, 1e-6f, "mismatch at " + at); + } + + private static void assertEq(float expected, float actual) { + assertEquals(expected, actual, 1e-6f); + } + + @Test + void mat3_columnMajor_copiedVerbatim() { + final FloatBuffer src = wrap(1, 2, 3, 4, 5, 6, 7, 8, 9); + try { + final float[] dst = new float[9]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 3, false, dst, 0); + for (int i = 0; i < 9; i++) assertEq(i + 1, dst[i], "[" + i + "]"); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat3_rowMajor_transposeFlipsToColumnMajor() { + // Input rows (1,2,3) (4,5,6) (7,8,9); output cols (1,4,7) (2,5,8) (3,6,9). + final FloatBuffer src = wrap(1, 2, 3, 4, 5, 6, 7, 8, 9); + try { + final float[] dst = new float[9]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 3, true, dst, 0); + assertEq(1f, dst[0], "c0.x"); assertEq(4f, dst[1], "c0.y"); assertEq(7f, dst[2], "c0.z"); + assertEq(2f, dst[3], "c1.x"); assertEq(5f, dst[4], "c1.y"); assertEq(8f, dst[5], "c1.z"); + assertEq(3f, dst[6], "c2.x"); assertEq(6f, dst[7], "c2.y"); assertEq(9f, dst[8], "c2.z"); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat3_oversizedBuffer_celeritasPattern_truncatesAtNineFloats() { + final FloatBuffer src = wrap(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0); + try { + final float[] dst = new float[9]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 3, false, dst, 0); + for (int i = 0; i < 9; i++) assertEq(i + 1, dst[i], "[" + i + "]"); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat3Array_twoElements_eachCopiedColumnMajor() { + final FloatBuffer src = wrap( + 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 20, 30, 40, 50, 60, 70, 80, 90 + ); + try { + final float[] dst = new float[18]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 2, 3, false, dst, 0); + for (int i = 0; i < 9; i++) assertEq(i + 1, dst[i], "m0[" + i + "]"); + for (int i = 0; i < 9; i++) assertEq((i + 1) * 10, dst[9 + i], "m1[" + i + "]"); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat2_columnMajor_copiedVerbatim() { + final FloatBuffer src = wrap(1, 2, 3, 4); + try { + final float[] dst = new float[4]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 2, false, dst, 0); + assertEq(1f, dst[0], "c0.x"); assertEq(2f, dst[1], "c0.y"); + assertEq(3f, dst[2], "c1.x"); assertEq(4f, dst[3], "c1.y"); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat2_rowMajor_transposeFlipsToColumnMajor() { + final FloatBuffer src = wrap(1, 2, 3, 4); + try { + final float[] dst = new float[4]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 2, true, dst, 0); + assertEq(1f, dst[0]); assertEq(3f, dst[1]); + assertEq(2f, dst[2]); assertEq(4f, dst[3]); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat4_rowMajor_transposeFlipsToColumnMajor() { + final FloatBuffer src = wrap(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + try { + final float[] dst = new float[16]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 4, true, dst, 0); + assertEq(1f, dst[0]); assertEq(5f, dst[1]); assertEq(9f, dst[2]); assertEq(13f, dst[3]); + assertEq(2f, dst[4]); assertEq(6f, dst[5]); assertEq(10f, dst[6]); assertEq(14f, dst[7]); + assertEq(3f, dst[8]); assertEq(7f, dst[9]); assertEq(11f, dst[10]); assertEq(15f, dst[11]); + assertEq(4f, dst[12]); assertEq(8f, dst[13]); assertEq(12f, dst[14]); assertEq(16f, dst[15]); + } finally { + MemoryUtil.memFree(src); + } + } + + @Test + void mat4_columnMajor_copiedVerbatim() { + final FloatBuffer src = wrap(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + try { + final float[] dst = new float[16]; + MatrixMarshal.marshalMatrixToColumnMajor(src, 0, 1, 4, false, dst, 0); + for (int i = 0; i < 16; i++) assertEq(i + 1, dst[i], "[" + i + "]"); + } finally { + MemoryUtil.memFree(src); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java new file mode 100644 index 000000000..436409b31 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java @@ -0,0 +1,118 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SdlSamplerStripperPreprocessorTest { + + @Test + void samplerReferencedOnlyInsideIfBlock_isPreserved() { + final String src = "#version 460 core\n" + + "#define FOO 1\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "void main() {\n" + + "#if FOO\n" + + " float a = textureLod(u_S, vec2(0), 0.0).r;\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertTrue(out.contains("uniform sampler2D u_S"), "ref inside #if must keep the decl; output:\n" + out); + } + + @Test + void samplerReferencedUnconditionally_isPreserved() { + final String src = "#version 460 core\n" + + "#define FOO 1\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "void main() {\n" + + " float t = textureLod(u_S, vec2(0), 0.0).r;\n" + + "#if FOO\n" + + " float a = t * 2.0;\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertTrue(out.contains("uniform sampler2D u_S"), + "unconditional ref must keep the decl; output:\n" + out); + } + + @Test + void samplerReferencedInBothIfAndElseBranches_isPreserved() { + final String src = "#version 460 core\n" + + "#define FOO 0\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "void main() {\n" + + "#if FOO\n" + + " float a = textureLod(u_S, vec2(0), 0.0).r;\n" + + "#else\n" + + " float b = textureLod(u_S, vec2(0), 0.0).r;\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertTrue(out.contains("uniform sampler2D u_S"), "refs in both branches must keep the decl; output:\n" + out); + } + + @Test + void terrainOpaqueLayout_keepsBlockTex() { + final String src = "#version 330 core\n" + + "#define USE_RGSS\n" + + "in vec2 v_TexCoord;\n" + + "out vec4 fragColor;\n" + + "uniform sampler2D u_BlockTex;\n" + + "#ifdef USE_RGSS\n" + + "vec4 sampleRGSS(sampler2D tex, vec2 uv) { return textureLod(tex, uv, 0.0); }\n" + + "#endif\n" + + "void main() {\n" + + "#ifdef USE_RGSS\n" + + " vec2 texSize = vec2(textureSize(u_BlockTex, 0));\n" + + " fragColor = sampleRGSS(u_BlockTex, v_TexCoord);\n" + + "#else\n" + + " fragColor = texture(u_BlockTex, v_TexCoord);\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertTrue(out.contains("uniform sampler2D u_BlockTex"), "terrain sampler must survive; output:\n" + out); + } + + @Test + void samplerNeverReferenced_isStripped() { + final String src = "#version 460 core\n" + + "#define FOO 1\n" + + "layout(binding = 0) uniform sampler2D iris_centerDepthSmooth;\n" + + "void main() {\n" + + "#if FOO\n" + + " float a = 1.0;\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertFalse(out.contains("uniform sampler2D iris_centerDepthSmooth"), "an unreferenced sampler must still be stripped; output:\n" + out); + } + + @Test + void samplerOnlyInCommentInsidePreprocessorBlock_isStripped() { + final String src = "#version 460 core\n" + + "#define FOO 1\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "void main() {\n" + + "#if FOO\n" + + " // u_S was used here once\n" + + " float a = 1.0;\n" + + "#endif\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertFalse(out.contains("uniform sampler2D u_S"), "a comment mention must not keep the decl; output:\n" + out); + } + + @Test + void samplerOnlyInMacroBody_isPreserved() { + final String src = "#version 460 core\n" + + "layout(binding = 0) uniform sampler2D u_S;\n" + + "#define SAMPLE_IT() textureLod(u_S, vec2(0), 0.0).r\n" + + "void main() {\n" + + " float a = SAMPLE_IT();\n" + + "}\n"; + final String out = SamplerStripper.stripUnused(src); + assertTrue(out.contains("uniform sampler2D u_S"), "a macro-body ref must keep the decl; output:\n" + out); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderCompilationTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderCompilationTest.java new file mode 100644 index 000000000..9ce20e9fb --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderCompilationTest.java @@ -0,0 +1,130 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests GLSL -> SPIR-V compilation via shaderc. + */ +class ShaderCompilationTest { + + private static final String SIMPLE_VERTEX_SHADER = """ + #version 460 core + layout(location = 0) in vec3 a_Position; + layout(location = 1) in vec4 a_Color; + out vec4 v_Color; + void main() { + gl_Position = vec4(a_Position, 1.0); + v_Color = a_Color; + } + """; + + private static final String SIMPLE_FRAGMENT_SHADER = """ + #version 460 core + in vec4 v_Color; + out vec4 fragColor; + void main() { + fragColor = v_Color; + } + """; + + private static final String TEXTURED_FRAGMENT_SHADER = """ + #version 460 core + in vec2 v_TexCoord; + out vec4 fragColor; + uniform sampler2D u_Texture; + void main() { + fragColor = texture(u_Texture, v_TexCoord); + } + """; + + private static final String UNIFORM_VERTEX_SHADER = """ + #version 460 core + layout(location = 0) in vec3 a_Position; + uniform mat4 u_ModelViewProjection; + uniform vec4 u_Color; + out vec4 v_Color; + void main() { + gl_Position = u_ModelViewProjection * vec4(a_Position, 1.0); + v_Color = u_Color; + } + """; + + @Test + void testSimpleVertexShaderCompiles() { + ByteBuffer spirv = compileShader(SIMPLE_VERTEX_SHADER, Shaderc.shaderc_vertex_shader); + assertNotNull(spirv, "Vertex shader should compile to SPIR-V"); + assertTrue(spirv.remaining() > 0, "SPIR-V output should not be empty"); + assertEquals(0x07230203, spirv.getInt(0), "Output should start with SPIR-V magic number"); + } + + @Test + void testSimpleFragmentShaderCompiles() { + ByteBuffer spirv = compileShader(SIMPLE_FRAGMENT_SHADER, Shaderc.shaderc_fragment_shader); + assertNotNull(spirv, "Fragment shader should compile to SPIR-V"); + assertTrue(spirv.remaining() > 0, "SPIR-V output should not be empty"); + assertEquals(0x07230203, spirv.getInt(0), "Output should start with SPIR-V magic number"); + } + + @Test + void testTexturedFragmentShaderCompiles() { + ByteBuffer spirv = compileShader(TEXTURED_FRAGMENT_SHADER, Shaderc.shaderc_fragment_shader); + assertNotNull(spirv, "Textured fragment shader should compile to SPIR-V"); + assertEquals(0x07230203, spirv.getInt(0)); + } + + @Test + void testUniformVertexShaderCompiles() { + ByteBuffer spirv = compileShader(UNIFORM_VERTEX_SHADER, Shaderc.shaderc_vertex_shader); + assertNotNull(spirv, "Uniform vertex shader should compile to SPIR-V"); + assertEquals(0x07230203, spirv.getInt(0)); + } + + @Test + void testInvalidShaderFailsGracefully() { + long compiler = Shaderc.shaderc_compiler_initialize(); + long options = Shaderc.shaderc_compile_options_initialize(); + + try { + Shaderc.shaderc_compile_options_set_forced_version_profile(options, 460, Shaderc.shaderc_profile_core); + + long result = Shaderc.shaderc_compile_into_spv( + compiler, "this is not valid GLSL", Shaderc.shaderc_vertex_shader, "bad_shader", "main", options); + + try { + final int status = Shaderc.shaderc_result_get_compilation_status(result); + assertNotEquals(Shaderc.shaderc_compilation_status_success, status, "Invalid GLSL should not compile successfully"); + + final String error = Shaderc.shaderc_result_get_error_message(result); + assertNotNull(error, "Error message should be present"); + assertFalse(error.isEmpty(), "Error message should not be empty"); + } finally { + Shaderc.shaderc_result_release(result); + } + } finally { + Shaderc.shaderc_compile_options_release(options); + Shaderc.shaderc_compiler_release(compiler); + } + } + + @Test + void testAutoBindUniformsProducesBindings() { + // Verify that shaderc's auto_bind_uniforms mode assigns bindings + final ByteBuffer spirv = compileShader(UNIFORM_VERTEX_SHADER, Shaderc.shaderc_vertex_shader); + assertNotNull(spirv, "Should compile with auto-bind-uniforms"); + assertTrue(spirv.remaining() > 100, "SPIR-V should be substantial enough to contain bindings"); + } + + private ByteBuffer compileShader(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "test_shader", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("Shader compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpirvTestShaders.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpirvTestShaders.java new file mode 100644 index 000000000..dd4467a76 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpirvTestShaders.java @@ -0,0 +1,68 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +public final class SpirvTestShaders { + + private SpirvTestShaders() {} + + public static final String VERTEX_GLSL = """ + #version 460 core + layout(set = 0, binding = 0) uniform sampler2D u_Texture; + layout(set = 1, binding = 0) uniform UBO { mat4 u_Mvp; } ubo; + layout(location = 0) in vec3 a_Position; + layout(location = 1) in vec2 a_TexCoord; + layout(location = 0) out vec2 v_TexCoord; + void main() { + gl_Position = ubo.u_Mvp * vec4(a_Position, 1.0); + v_TexCoord = a_TexCoord + texture(u_Texture, a_TexCoord).xy * 0.0; + } + """; + + public static final String FRAGMENT_GLSL = """ + #version 460 core + layout(set = 2, binding = 0) uniform sampler2D u_TexA; + layout(set = 2, binding = 1) uniform sampler2D u_TexB; + layout(set = 3, binding = 0) uniform UBO { vec4 u_Tint; } ubo; + layout(location = 0) in vec2 v_TexCoord; + layout(location = 0) out vec4 fragColor; + void main() { + fragColor = (texture(u_TexA, v_TexCoord) + texture(u_TexB, v_TexCoord)) * ubo.u_Tint; + } + """; + + public static final String HIZ_INIT_GLSL = """ + #version 460 core + layout(local_size_x = 8, local_size_y = 8) in; + layout(binding = 0) uniform sampler2D u_DepthSrc; + layout(r32f, binding = 0) uniform writeonly image2D u_HizMip0; + layout(std140, binding = 0) uniform Init { ivec2 srcSize; ivec2 dstSize; float zNear; float zFar; int projMode; } init; + void main() { + ivec2 c = ivec2(gl_GlobalInvocationID.xy); + if (c.x >= init.dstSize.x || c.y >= init.dstSize.y) return; + float d = texelFetch(u_DepthSrc, c, 0).r; + imageStore(u_HizMip0, c, vec4(d * float(init.projMode))); + } + """; + + public static final String LDS_MULTI_MIP_GLSL = """ + #version 460 core + layout(local_size_x = 64) in; + layout(r32f, binding = 0) uniform image2D u_Src; + layout(r32f, binding = 1) uniform writeonly image2D u_Dst1; + layout(r32f, binding = 2) uniform writeonly image2D u_Dst2; + layout(std140, binding = 0) uniform Down { ivec2 baseSize; int numMips; } down; + shared float lds[64]; + void main() { + uint t = gl_LocalInvocationID.x; + ivec2 c = ivec2(gl_GlobalInvocationID.x, 0); + float m = max(imageLoad(u_Src, c * 2).r, imageLoad(u_Src, c * 2 + ivec2(1, 0)).r); + imageStore(u_Dst1, c, vec4(m)); + lds[t] = m; + memoryBarrierShared(); + barrier(); + if (t % 2u == 0u && down.numMips > 1) { + float m2 = max(lds[t], lds[t + 1u]); + imageStore(u_Dst2, ivec2(int(t) / 2, 0), vec4(m2)); + } + } + """; +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcArrayStrideTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcArrayStrideTest.java new file mode 100644 index 000000000..d391d09dc --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcArrayStrideTest.java @@ -0,0 +1,177 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +class SpvcArrayStrideTest { + + private static final String FRAGMENT_WITH_FLOAT_ARRAY = """ + #version 330 core + uniform float arr[16]; + uniform int idx; + out vec4 fragColor; + void main() { + fragColor = vec4(arr[idx], arr[(idx + 1) % 16], 0.0, 1.0); + } + """; + + private static final String FRAGMENT_WITH_VEC4_ARRAY = """ + #version 330 core + uniform vec4 colors[8]; + uniform int idx; + out vec4 fragColor; + void main() { + fragColor = colors[idx]; + } + """; + + @Test + void floatArrayHasStride16() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_FLOAT_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final ShaderManager.UboMember arr = findMember(refl, "arr"); + assertNotNull(arr, "arr member missing from reflection: " + refl.uboMembers()); + assertEquals(16, arr.arrayStride(), "float[N] array stride should be 16 bytes under std140"); + assertEquals(256, arr.size(), "float[16] declared size should be 256 bytes under std140"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void vec4ArrayHasStride16() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_VEC4_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final ShaderManager.UboMember arr = findMember(refl, "colors"); + assertNotNull(arr, "colors member missing from reflection: " + refl.uboMembers()); + assertEquals(16, arr.arrayStride(), "vec4[N] array stride should be 16 bytes under std140"); + assertEquals(128, arr.size(), "vec4[8] declared size should be 128 bytes under std140"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void scalarMemberHasZeroStride() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_FLOAT_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.StageReflection refl = ShaderManager.reflectStage(spirv, false); + final ShaderManager.UboMember idx = findMember(refl, "idx"); + assertNotNull(idx, "idx member missing from reflection: " + refl.uboMembers()); + assertEquals(0, idx.arrayStride(), "non-array members must have arrayStride=0"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void typeDescriptor_floatScalar() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_FLOAT_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.UboMember idx = findMember(ShaderManager.reflectStage(spirv, false), "idx"); + assertNotNull(idx); + assertEquals(1, idx.vectorSize(), "scalar vectorSize"); + assertEquals(1, idx.columns(), "scalar columns"); + assertEquals(1, idx.arrayLen(), "non-array arrayLen=1"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void typeDescriptor_floatArray() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_FLOAT_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.UboMember arr = findMember(ShaderManager.reflectStage(spirv, false), "arr"); + assertNotNull(arr); + assertEquals(1, arr.vectorSize(), "scalar array vectorSize"); + assertEquals(1, arr.columns(), "scalar array columns"); + assertEquals(16, arr.arrayLen(), "float[16] arrayLen"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void typeDescriptor_vec4Array() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_VEC4_ARRAY, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.UboMember colors = findMember(ShaderManager.reflectStage(spirv, false), "colors"); + assertNotNull(colors); + assertEquals(4, colors.vectorSize(), "vec4 vectorSize"); + assertEquals(1, colors.columns(), "vec4 columns"); + assertEquals(8, colors.arrayLen(), "vec4[8] arrayLen"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static final String FRAGMENT_WITH_VEC3 = """ + #version 330 core + uniform vec3 dir; + out vec4 fragColor; + void main() { fragColor = vec4(dir, 1.0); } + """; + + @Test + void typeDescriptor_vec3() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_VEC3, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.UboMember dir = findMember(ShaderManager.reflectStage(spirv, false), "dir"); + assertNotNull(dir); + assertEquals(3, dir.vectorSize(), "vec3 vectorSize"); + assertEquals(1, dir.columns(), "vec3 columns"); + assertEquals(1, dir.arrayLen(), "non-array"); + assertEquals(0, dir.arrayStride(), "non-array stride=0"); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static final String FRAGMENT_WITH_MAT3 = """ + #version 330 core + uniform mat3 normalMatrix; + out vec4 fragColor; + void main() { fragColor = vec4(normalMatrix * vec3(0,1,0), 1.0); } + """; + + @Test + void typeDescriptor_mat3() { + final ByteBuffer spirv = compile(FRAGMENT_WITH_MAT3, Shaderc.shaderc_fragment_shader); + try { + final ShaderManager.UboMember m = findMember(ShaderManager.reflectStage(spirv, false), "normalMatrix"); + assertNotNull(m); + assertEquals(3, m.vectorSize(), "mat3 rows"); + assertEquals(3, m.columns(), "mat3 columns"); + assertEquals(1, m.arrayLen(), "non-array"); + + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static ShaderManager.UboMember findMember(ShaderManager.StageReflection refl, String name) { + for (ShaderManager.UboMember m : refl.uboMembers()) { + if (name.equals(m.name())) return m; + } + return null; + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "test", SpirvCompiler.Options.vulkanRelaxed()); + if (r.spirv() == null) { + fail("Compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcReflectionTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcReflectionTest.java new file mode 100644 index 000000000..9705312cc --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SpvcReflectionTest.java @@ -0,0 +1,181 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.lwjgl.system.MemoryStack; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.PointerBuffer; +import org.lwjgl.util.shaderc.Shaderc; +import org.lwjgl.util.spvc.Spvc; +import org.lwjgl.util.spvc.SpvcReflectedResource; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.lwjgl.system.MemoryStack.*; + +/** + * Tests SPIRV-Cross reflection on compiled SPIR-V: Verifies we can extract uniform buffer names, sampler names, and vertex attribute locations. + */ +class SpvcReflectionTest { + + private static final String VERTEX_WITH_UNIFORMS = """ + #version 460 core + layout(location = 0) in vec3 a_Position; + layout(location = 1) in vec2 a_TexCoord; + uniform mat4 u_ModelViewProjection; + uniform vec4 u_Color; + out vec2 v_TexCoord; + out vec4 v_Color; + void main() { + gl_Position = u_ModelViewProjection * vec4(a_Position, 1.0); + v_TexCoord = a_TexCoord; + v_Color = u_Color; + } + """; + + private static final String FRAGMENT_WITH_SAMPLER = """ + #version 460 core + in vec2 v_TexCoord; + in vec4 v_Color; + out vec4 fragColor; + uniform sampler2D u_Texture; + uniform float u_Alpha; + void main() { + vec4 texColor = texture(u_Texture, v_TexCoord); + fragColor = texColor * v_Color * vec4(1.0, 1.0, 1.0, u_Alpha); + } + """; + + @Test + void testReflectUniformBuffersFromVertexShader() { + ByteBuffer spirv = compileWithAutoBindUniforms(VERTEX_WITH_UNIFORMS, Shaderc.shaderc_vertex_shader); + assertNotNull(spirv); + + List uniformBuffers = reflectResourceNames(spirv, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER); + assertFalse(uniformBuffers.isEmpty(), "Should find uniform buffers after auto-bind compilation"); + } + + @Test + void testReflectSampledImagesFromFragmentShader() { + ByteBuffer spirv = compileWithAutoBindUniforms(FRAGMENT_WITH_SAMPLER, Shaderc.shaderc_fragment_shader); + assertNotNull(spirv); + + List sampledImages = reflectResourceNames(spirv, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE); + // With auto-combined-image-sampler, separate sampler+image become combined + // Check both combined and separate paths + List separateImages = reflectResourceNames(spirv, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE); + List separateSamplers = reflectResourceNames(spirv, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS); + + boolean foundTexture = sampledImages.stream().anyMatch(n -> n.contains("u_Texture")) + || separateImages.stream().anyMatch(n -> n.contains("u_Texture")) + || separateSamplers.stream().anyMatch(n -> n.contains("u_Texture")); + + assertTrue(foundTexture, "Should find u_Texture in sampled images, separate images, or separate samplers. " + + "Combined: " + sampledImages + ", Images: " + separateImages + ", Samplers: " + separateSamplers); + } + + @Test + void testReflectProducesNonEmptyNames() { + ByteBuffer spirv = compileWithAutoBindUniforms(VERTEX_WITH_UNIFORMS, Shaderc.shaderc_vertex_shader); + assertNotNull(spirv); + + try (var stack = stackPush()) { + long ctx = createSpvcContext(stack); + long compiler = createGLSLCompiler(ctx, spirv, stack); + long resources = createResources(compiler, stack); + + // Get uniform buffers + PointerBuffer pList = stack.pointers(0); + PointerBuffer pCount = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, + Spvc.spvc_resources_get_resource_list_for_type(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, pList, pCount)); + + long count = pCount.get(0); + if (count > 0) { + SpvcReflectedResource.Buffer resList = SpvcReflectedResource.create(pList.get(0), (int) count); + for (int i = 0; i < count; i++) { + String name = resList.get(i).nameString(); + assertNotNull(name, "Resource name should not be null"); + assertFalse(name.isEmpty(), "Resource name should not be empty"); + } + } + + Spvc.spvc_context_destroy(ctx); + } + } + + @Test + void testSpvcContextCreationAndDestruction() { + try (var stack = stackPush()) { + PointerBuffer pCtx = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create(pCtx)); + long ctx = pCtx.get(0); + assertNotEquals(0, ctx, "Context should be non-null"); + Spvc.spvc_context_destroy(ctx); + } + } + + private List reflectResourceNames(ByteBuffer spirv, int resourceType) { + List names = new ArrayList<>(); + try (var stack = stackPush()) { + long ctx = createSpvcContext(stack); + long compiler = createGLSLCompiler(ctx, spirv, stack); + long resources = createResources(compiler, stack); + + PointerBuffer pList = stack.pointers(0); + PointerBuffer pCount = stack.pointers(0); + if (Spvc.spvc_resources_get_resource_list_for_type(resources, resourceType, pList, pCount) == Spvc.SPVC_SUCCESS) { + long count = pCount.get(0); + if (count > 0) { + SpvcReflectedResource.Buffer resList = SpvcReflectedResource.create(pList.get(0), (int) count); + for (int i = 0; i < count; i++) { + String name = resList.get(i).nameString(); + if (name != null && !name.isEmpty()) { + names.add(name); + } + } + } + } + + Spvc.spvc_context_destroy(ctx); + } + return names; + } + + private long createSpvcContext(MemoryStack stack) { + PointerBuffer pCtx = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, Spvc.spvc_context_create(pCtx)); + return pCtx.get(0); + } + + private long createGLSLCompiler(long ctx, ByteBuffer spirv, MemoryStack stack) { + IntBuffer spirvWords = spirv.asIntBuffer(); + PointerBuffer pIR = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, + Spvc.spvc_context_parse_spirv(ctx, spirvWords, spirvWords.remaining(), pIR)); + + PointerBuffer pCompiler = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, + Spvc.spvc_context_create_compiler(ctx, Spvc.SPVC_BACKEND_GLSL, pIR.get(0), + Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, pCompiler)); + return pCompiler.get(0); + } + + private long createResources(long compiler, MemoryStack stack) { + PointerBuffer pResources = stack.pointers(0); + assertEquals(Spvc.SPVC_SUCCESS, + Spvc.spvc_compiler_create_shader_resources(compiler, pResources)); + return pResources.get(0); + } + + private ByteBuffer compileWithAutoBindUniforms(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "test", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("Compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140WriterTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140WriterTest.java new file mode 100644 index 000000000..b766ebb3d --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/Std140WriterTest.java @@ -0,0 +1,305 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.spvc.Spvc; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class Std140WriterTest { + private static final int FP32 = Spvc.SPVC_BASETYPE_FP32; + + private static FloatBuffer outBuf(int floats) { + return MemoryUtil.memCallocFloat(floats); + } + + private static ShaderManager.UniformMemberInfo single(int byteOffset, int byteSize, int vectorSize, int columns) { + return new ShaderManager.UniformMemberInfo(byteOffset, byteSize, /*arrayStride*/ 0, /*isVertex*/ true, vectorSize, columns, FP32, /*arrayLen*/ 1); + } + + private static ShaderManager.UniformMemberInfo array(int byteOffset, int arrayStride, int arrayLen, int vectorSize, int columns) { + return new ShaderManager.UniformMemberInfo(byteOffset, arrayStride * arrayLen, arrayStride, /*isVertex*/ true, vectorSize, columns, FP32, arrayLen); + } + + private static void assertEq(float expected, float actual, String at) { + assertEquals(expected, actual, 1e-6f, "mismatch at " + at); + } + + private static void assertEq(float expected, float actual) { + assertEquals(expected, actual, 1e-6f); + } + + @Test + void scalar_writesOneFloatAtOffset() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, single(/*off*/ 4, /*size*/ 4, 1, 1), new float[]{42f}, 1); + assertEq(0f, ubo.get(0), "[0] before offset"); + assertEq(42f, ubo.get(1), "[1] = scalar"); + assertEq(0f, ubo.get(2), "[2] untouched"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void scalarArray_writesEachAtStride16() { + final FloatBuffer ubo = outBuf(16); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 16, /*len*/ 4, 1, 1), new float[]{1, 2, 3, 4}, 4); + assertEq(1f, ubo.get(0), "elem0"); + assertEq(0f, ubo.get(1), "elem0 pad"); + assertEq(2f, ubo.get(4), "elem1"); + assertEq(3f, ubo.get(8), "elem2"); + assertEq(4f, ubo.get(12), "elem3"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void vec2_writesTwoFloatsPacked() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 8, 2, 1), new float[]{1f, 2f}, 1); + assertEq(1f, ubo.get(0), "x"); + assertEq(2f, ubo.get(1), "y"); + assertEq(0f, ubo.get(2), "after vec2"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void vec3_writesThreeFloatsPacked_noTrailingPaddingTouched() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 12, 3, 1), new float[]{1f, 2f, 3f}, 1); + assertEq(1f, ubo.get(0), "x"); + assertEq(2f, ubo.get(1), "y"); + assertEq(3f, ubo.get(2), "z"); + assertEq(0f, ubo.get(3), "no spurious write past vec3"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void vec4_writesFourFloatsPacked() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 16, 4, 1), new float[]{1f, 2f, 3f, 4f}, 1); + assertEq(1f, ubo.get(0), "x"); + assertEq(2f, ubo.get(1), "y"); + assertEq(3f, ubo.get(2), "z"); + assertEq(4f, ubo.get(3), "w"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void vec3Array_eachElementAtStride16_zeroPaddedFourthLane() { + + final FloatBuffer ubo = outBuf(16); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 16, /*len*/ 4, 3, 1), + new float[]{1, 2, 3, 10, 20, 30, 100, 200, 300, -1, -2, -3}, 4); + assertEq(1f, ubo.get(0), "e0.x"); assertEq(2f, ubo.get(1), "e0.y"); assertEq(3f, ubo.get(2), "e0.z"); + assertEq(0f, ubo.get(3), "e0.pad"); + assertEq(10f, ubo.get(4), "e1.x"); assertEq(20f, ubo.get(5), "e1.y"); assertEq(30f, ubo.get(6), "e1.z"); + assertEq(0f, ubo.get(7), "e1.pad"); + assertEq(100f, ubo.get(8), "e2.x"); assertEq(200f, ubo.get(9), "e2.y"); assertEq(300f, ubo.get(10), "e2.z"); + assertEq(0f, ubo.get(11), "e2.pad"); + assertEq(-1f, ubo.get(12), "e3.x"); assertEq(-2f, ubo.get(13), "e3.y"); assertEq(-3f, ubo.get(14), "e3.z"); + assertEq(0f, ubo.get(15), "e3.pad"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void vec4Array_eachElementAtStride16_noPaddingNeeded() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 16, /*len*/ 2, 4, 1), new float[]{1, 2, 3, 4, 5, 6, 7, 8}, 2); + assertEq(1f, ubo.get(0)); assertEq(2f, ubo.get(1)); assertEq(3f, ubo.get(2)); assertEq(4f, ubo.get(3)); + assertEq(5f, ubo.get(4)); assertEq(6f, ubo.get(5)); assertEq(7f, ubo.get(6)); assertEq(8f, ubo.get(7)); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat2_threeColsTimesVec4Each() { + final FloatBuffer ubo = outBuf(8); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 32, /*rows*/ 2, /*cols*/ 2), new float[]{1, 2, 3, 4}, 1); + assertEq(1f, ubo.get(0), "c0.x"); assertEq(2f, ubo.get(1), "c0.y"); + assertEq(0f, ubo.get(2), "c0.pad2"); assertEq(0f, ubo.get(3), "c0.pad3"); + assertEq(3f, ubo.get(4), "c1.x"); assertEq(4f, ubo.get(5), "c1.y"); + assertEq(0f, ubo.get(6), "c1.pad2"); assertEq(0f, ubo.get(7), "c1.pad3"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat3_threeColsEachPaddedToVec4() { + final FloatBuffer ubo = outBuf(12); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 48, 3, 3), new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 1); + assertEq(1f, ubo.get(0)); assertEq(2f, ubo.get(1)); assertEq(3f, ubo.get(2)); assertEq(0f, ubo.get(3)); + assertEq(4f, ubo.get(4)); assertEq(5f, ubo.get(5)); assertEq(6f, ubo.get(6)); assertEq(0f, ubo.get(7)); + assertEq(7f, ubo.get(8)); assertEq(8f, ubo.get(9)); assertEq(9f, ubo.get(10)); assertEq(0f, ubo.get(11)); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat3_reflectionUnderreportsSize_paddingStillApplied() { + final FloatBuffer ubo = outBuf(12); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 36, 3, 3), new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 1); + assertEq(1f, ubo.get(0)); assertEq(2f, ubo.get(1)); assertEq(3f, ubo.get(2)); assertEq(0f, ubo.get(3)); + assertEq(4f, ubo.get(4)); assertEq(5f, ubo.get(5)); assertEq(6f, ubo.get(6)); assertEq(0f, ubo.get(7)); + assertEq(7f, ubo.get(8)); assertEq(8f, ubo.get(9)); assertEq(9f, ubo.get(10)); assertEq(0f, ubo.get(11)); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat4_fourColsNoPaddingNeeded() { + final FloatBuffer ubo = outBuf(16); + try { + Std140Writer.write(ubo, single(/*off*/ 0, /*size*/ 64, 4, 4), new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, 1); + for (int i = 0; i < 16; i++) assertEq(i + 1, ubo.get(i), "[" + i + "]"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat3Array_perElementStride48_eachMatrixGetsItsOwnPadding() { + final FloatBuffer ubo = outBuf(24); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 48, /*len*/ 2, 3, 3), + new float[]{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, // matrix 0 (col-major packed) + 10, 20, 30, 40, 50, 60, 70, 80, 90 // matrix 1 + }, 2); + assertEq(1f, ubo.get(0)); assertEq(2f, ubo.get(1)); assertEq(3f, ubo.get(2)); assertEq(0f, ubo.get(3)); + assertEq(4f, ubo.get(4)); assertEq(5f, ubo.get(5)); assertEq(6f, ubo.get(6)); assertEq(0f, ubo.get(7)); + assertEq(7f, ubo.get(8)); assertEq(8f, ubo.get(9)); assertEq(9f, ubo.get(10)); assertEq(0f, ubo.get(11)); + assertEq(10f, ubo.get(12)); assertEq(20f, ubo.get(13)); assertEq(30f, ubo.get(14)); assertEq(0f, ubo.get(15)); + assertEq(40f, ubo.get(16)); assertEq(50f, ubo.get(17)); assertEq(60f, ubo.get(18)); assertEq(0f, ubo.get(19)); + assertEq(70f, ubo.get(20)); assertEq(80f, ubo.get(21)); assertEq(90f, ubo.get(22)); assertEq(0f, ubo.get(23)); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void mat4Array_perElementStride64() { + final FloatBuffer ubo = outBuf(32); + try { + final float[] data = new float[32]; + for (int i = 0; i < 32; i++) data[i] = i; + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 64, /*len*/ 2, 4, 4), data, 2); + for (int i = 0; i < 32; i++) assertEq(i, ubo.get(i), "[" + i + "]"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void nonZeroOffset_doesNotDisturbEarlierLanes() { + final FloatBuffer ubo = outBuf(16); + try { + for (int i = 0; i < 16; i++) ubo.put(i, -7f); + Std140Writer.write(ubo, single(/*off*/ 32, /*size*/ 12, 3, 1), new float[]{1, 2, 3}, 1); + for (int i = 0; i < 8; i++) assertEq(-7f, ubo.get(i), "preserved [" + i + "]"); + assertEq(1f, ubo.get(8)); + assertEq(2f, ubo.get(9)); + assertEq(3f, ubo.get(10)); + assertEq(-7f, ubo.get(11), "preserved (vec3 leaves 4th lane untouched)"); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void srcCount_clampedToArrayLen() { + final FloatBuffer ubo = outBuf(16); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 16, /*len*/ 2, 1, 1), new float[]{1, 2, 3, 4}, 4); + assertEq(1f, ubo.get(0)); + assertEq(2f, ubo.get(4)); + assertEq(0f, ubo.get(8)); // not written + assertEq(0f, ubo.get(12)); // not written + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void srcCount_clampedToSrcSize() { + final FloatBuffer ubo = outBuf(16); + try { + Std140Writer.write(ubo, array(/*off*/ 0, /*stride*/ 16, /*len*/ 4, 1, 1), new float[]{7, 8}, 4); + assertEq(7f, ubo.get(0)); + assertEq(8f, ubo.get(4)); + assertEq(0f, ubo.get(8)); // beyond src + assertEq(0f, ubo.get(12)); + } finally { + MemoryUtil.memFree(ubo); + } + } + + @Test + void degenerateTypeDescriptor_throws() { + assertThrows(IllegalStateException.class, () -> { + final FloatBuffer ubo = outBuf(4); + try { + Std140Writer.write(ubo, + new ShaderManager.UniformMemberInfo(0, 4, 0, true, /*vec*/ 0, /*cols*/ 0, FP32, 1), + new float[]{1f}, 1); + } finally { + MemoryUtil.memFree(ubo); + } + }); + } + + @Test + void regression_irisNormalMatrix_columnMajorJoml_paddedCorrectlyAtRealOffset() { + final FloatBuffer ubo = outBuf(1344 / 4 + 12); + try { + Std140Writer.write(ubo, single(/*off*/ 1344, /*size*/ 36, 3, 3), + new float[]{ + 0.8875f, 0f, 0.4607f, // col 0 + 0.2285f, 0.8684f, -0.4401f, // col 1 + -0.4001f, 0.4959f, 0.7707f // col 2 + }, 1); + final int b = 1344 / 4; + assertEq(0.8875f, ubo.get(b + 0), "c0.x"); + assertEq(0f, ubo.get(b + 1), "c0.y"); + assertEq(0.4607f, ubo.get(b + 2), "c0.z"); + assertEq(0f, ubo.get(b + 3), "c0.pad"); + assertEq(0.2285f, ubo.get(b + 4), "c1.x"); + assertEq(0.8684f, ubo.get(b + 5), "c1.y"); + assertEq(-0.4401f, ubo.get(b + 6), "c1.z"); + assertEq(0f, ubo.get(b + 7), "c1.pad"); + assertEq(-0.4001f, ubo.get(b + 8), "c2.x"); + assertEq(0.4959f, ubo.get(b + 9), "c2.y"); + assertEq(0.7707f, ubo.get(b + 10), "c2.z"); + assertEq(0f, ubo.get(b + 11), "c2.pad"); + } finally { + MemoryUtil.memFree(ubo); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformBoolRemapTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformBoolRemapTest.java new file mode 100644 index 000000000..b8a43cfe5 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UniformBoolRemapTest.java @@ -0,0 +1,41 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + + +import com.gtnewhorizons.angelica.sdlgpu.resource.FormatMap; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class UniformBoolRemapTest { + + @Test + void scalarUintToBool() { + assertEquals(GL20.GL_BOOL, FormatMap.remapUnsignedIntToBool(GL11.GL_UNSIGNED_INT)); + } + + @Test + void uvec2ToBvec2() { + assertEquals(GL20.GL_BOOL_VEC2, FormatMap.remapUnsignedIntToBool(GL30.GL_UNSIGNED_INT_VEC2)); + } + + @Test + void uvec3ToBvec3() { + assertEquals(GL20.GL_BOOL_VEC3, FormatMap.remapUnsignedIntToBool(GL30.GL_UNSIGNED_INT_VEC3)); + } + + @Test + void uvec4ToBvec4() { + assertEquals(GL20.GL_BOOL_VEC4, FormatMap.remapUnsignedIntToBool(GL30.GL_UNSIGNED_INT_VEC4)); + } + + @Test + void nonUintPassesThrough() { + assertEquals(GL20.GL_FLOAT_VEC4, FormatMap.remapUnsignedIntToBool(GL20.GL_FLOAT_VEC4)); + assertEquals(GL11.GL_INT, FormatMap.remapUnsignedIntToBool(GL11.GL_INT)); + assertEquals(GL20.GL_BOOL, FormatMap.remapUnsignedIntToBool(GL20.GL_BOOL)); + assertEquals(GL20.GL_FLOAT_MAT4, FormatMap.remapUnsignedIntToBool(GL20.GL_FLOAT_MAT4)); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetypeTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetypeTest.java new file mode 100644 index 000000000..3448a780a --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/UscaledRetypeTest.java @@ -0,0 +1,138 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.util.shaderc.Shaderc; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class UscaledRetypeTest { + + private static final String VS = """ + #version 330 core + layout(location = 0) in vec2 a_TexCoord; + layout(location = 1) in vec3 at_midBlock; + out vec2 v_uv; + void main() { + v_uv = a_TexCoord * 0.5; + gl_Position = vec4(at_midBlock, 1.0); + } + """; + + @Test + void unsignedExactWidthRetypesAndConverts() { + final String out = UscaledRetype.retype(VS, List.of(new UscaledRetype.Attrib("a_TexCoord", 0, 2, 2, false))); + assertNotNull(out); + assertTrue(out.contains("in uvec2 a_TexCoord_i"), out); + assertTrue(out.contains("vec2 a_TexCoord = vec2(a_TexCoord_i);"), out); + assertTrue(out.contains("v_uv = a_TexCoord * 0.5;"), out); + } + + @Test + void signedPromotedWidthSwizzlesDown() { + final String out = UscaledRetype.retype(VS, List.of(new UscaledRetype.Attrib("at_midBlock", 0, 3, 4, true))); + assertNotNull(out); + assertTrue(out.contains("in ivec4 at_midBlock_i"), out); + assertTrue(out.contains("vec3 at_midBlock = vec3(at_midBlock_i.xyz);"), out); + } + + @Test + void multipleAttributesConvertTogether() { + final String out = UscaledRetype.retype(VS, List.of( + new UscaledRetype.Attrib("a_TexCoord", 0, 2, 2, false), + new UscaledRetype.Attrib("at_midBlock", 0, 3, 4, true))); + assertNotNull(out); + assertTrue(out.contains("vec2 a_TexCoord = vec2(a_TexCoord_i);"), out); + assertTrue(out.contains("vec3 at_midBlock = vec3(at_midBlock_i.xyz);"), out); + } + + @Test + void emptyRequestIsIdentity() { + assertEquals(VS, UscaledRetype.retype(VS, List.of())); + } + + @Test + void missingAttributeFails() { + assertNull(UscaledRetype.retype(VS, List.of(new UscaledRetype.Attrib("not_present", 0, 2, 2, false)))); + } + + @Test + void narrowerBoundWidthPadsWithGlAttributeDefaults() { + final String out = UscaledRetype.retype(VS, List.of(new UscaledRetype.Attrib("at_midBlock", 0, 3, 2, true))); + assertNotNull(out); + assertTrue(out.contains("in ivec2 at_midBlock_i"), out); + assertTrue(out.contains("vec3 at_midBlock = vec3(vec2(at_midBlock_i), 0.0);"), out); + } + + @Test + void vec4FromShort2PadsZeroThenOne() { + final String src = """ + #version 330 core + layout(location = 3) in vec4 iris_MultiTexCoord1; + void main() { gl_Position = iris_MultiTexCoord1; } + """; + final String out = UscaledRetype.retype(src, List.of(new UscaledRetype.Attrib("iris_MultiTexCoord1", 0, 4, 2, true))); + assertNotNull(out); + assertTrue(out.contains("vec4 iris_MultiTexCoord1 = vec4(vec2(iris_MultiTexCoord1_i), 0.0, 1.0);"), out); + } + + @Test + void shadowIsInitializedBeforeAConsumingGlobalInitializer() { + final String src = """ + #version 330 core + in vec2 mc_midTexCoord; + vec4 iris_MidTex = vec4(mc_midTexCoord.xy * 3.0517578E-5, 0.0, 1.0); + void main() { gl_Position = iris_MidTex; } + """; + final String out = UscaledRetype.retype(src, List.of(new UscaledRetype.Attrib("mc_midTexCoord", 0, 2, 2, false))); + assertNotNull(out); + assertTrue(out.indexOf("vec2 mc_midTexCoord = vec2(mc_midTexCoord_i);") < out.indexOf("vec4 iris_MidTex ="), "the shadow must initialize before any global initializer that reads it\n\n" + out); + } + + @Test + void uniformOfSameNameIsNotRetyped() { + final String src = """ + #version 330 core + uniform vec2 a_TexCoord; + void main() { gl_Position = vec4(a_TexCoord, 0.0, 1.0); } + """; + assertNull(UscaledRetype.retype(src, List.of(new UscaledRetype.Attrib("a_TexCoord", 0, 2, 2, false)))); + } + + @Test + void retypesADeclarationGuardedByIfdefAfterPreprocessing() { + final String src = """ + #version 460 core + #define USE_VERTEX_COMPRESSION + #ifdef USE_VERTEX_COMPRESSION + in uvec4 a_PosId; + in vec2 a_TexCoord; + #else + in vec3 a_PosId; + in vec2 a_TexCoord; + #endif + out vec2 v_uv; + void main() { + v_uv = a_TexCoord * 3.0517578E-5; + gl_Position = vec4(vec3(a_PosId.xyz), 1.0); + } + """; + assertNull(UscaledRetype.retype(src, List.of(new UscaledRetype.Attrib("a_TexCoord", 0, 2, 2, false))), "the raw AST cannot see inside #ifdef; this is why the variant path preprocesses first"); + + final String pre = SpirvCompiler.preprocess(src, Shaderc.shaderc_vertex_shader, "test", SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(pre, "shaderc preprocessing must succeed"); + final String out = UscaledRetype.retype(pre, List.of(new UscaledRetype.Attrib("a_TexCoord", 0, 2, 2, false))); + assertNotNull(out, "preprocessed source must be parseable and retypeable\n\n" + pre); + assertTrue(out.contains("in uvec2 a_TexCoord_i"), out); + assertTrue(out.contains("vec2 a_TexCoord = vec2(a_TexCoord_i);"), out); + } + + @Test + void retypedInputKeepsTheNameSuffixTheLocationFixupKeysOn() { + final String out = UscaledRetype.retype(VS, List.of(new UscaledRetype.Attrib("a_TexCoord", 4, 2, 2, false))); + assertNotNull(out); + assertTrue(out.contains("a_TexCoord" + UscaledRetype.SUFFIX), out); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/LocalSizeParseTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/LocalSizeParseTest.java new file mode 100644 index 000000000..d0b3d7f43 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/cross/LocalSizeParseTest.java @@ -0,0 +1,86 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.cross; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import org.junit.jupiter.api.Test; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.fail; + +class LocalSizeParseTest { + + private static final String LS_8_8_1 = """ + #version 460 core + layout(local_size_x = 8, local_size_y = 8) in; + layout(std430, binding = 0) writeonly buffer B { uint b[]; } buf; + void main() { buf.b[gl_GlobalInvocationID.x] = 1u; } + """; + + private static final String LS_64 = """ + #version 460 core + layout(local_size_x = 64) in; + layout(std430, binding = 0) writeonly buffer B { uint b[]; } buf; + void main() { buf.b[gl_GlobalInvocationID.x] = 1u; } + """; + + private static final String LS_4_4_4 = """ + #version 460 core + layout(local_size_x = 4, local_size_y = 4, local_size_z = 4) in; + layout(std430, binding = 0) writeonly buffer B { uint b[]; } buf; + void main() { buf.b[gl_GlobalInvocationID.x] = 1u; } + """; + + @Test + void parsesLocalSize8x8x1() { + final ByteBuffer spirv = compile(LS_8_8_1); + try { + assertArrayEquals(new int[]{8, 8, 1}, CrossCompileUtil.parseLocalSize(spirv)); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void parsesLocalSize64x1x1() { + final ByteBuffer spirv = compile(LS_64); + try { + assertArrayEquals(new int[]{64, 1, 1}, CrossCompileUtil.parseLocalSize(spirv)); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void parsesLocalSize4x4x4() { + final ByteBuffer spirv = compile(LS_4_4_4); + try { + assertArrayEquals(new int[]{4, 4, 4}, CrossCompileUtil.parseLocalSize(spirv)); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void noExecutionModeFallsBackTo111() { + final ByteBuffer spirv = MemoryUtil.memAlloc(5 * 4).order(ByteOrder.nativeOrder()); + spirv.asIntBuffer().put(new int[]{0x07230203, 0x00010000, 0, 1, 0}); + try { + assertArrayEquals(new int[]{1, 1, 1}, CrossCompileUtil.parseLocalSize(spirv)); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static ByteBuffer compile(String source) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_compute_shader, "ls_test", + SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("Shader compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCompileTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCompileTest.java new file mode 100644 index 000000000..a8f589d6e --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcCompileTest.java @@ -0,0 +1,131 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.dxbc; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.SpirvTestShaders; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@EnabledOnOs(OS.WINDOWS) +class DxbcCompileTest { + + private static final byte DXBC_MAGIC_D = 'D'; + private static final byte DXBC_MAGIC_X = 'X'; + private static final byte DXBC_MAGIC_B = 'B'; + private static final byte DXBC_MAGIC_C = 'C'; + + + + @Test + void vertexShaderCrossCompilesAndProducesDxbc() { + final ByteBuffer spirv = compile(SpirvTestShaders.VERTEX_GLSL, Shaderc.shaderc_vertex_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_VERTEX_SHADER); + final DxbcCrossCompile.Output out = DxbcCrossCompile.compile(spirv, GL20.GL_VERTEX_SHADER); + try { + assertNotNull(out.code()); + assertTrue(out.code().remaining() >= 4, "DXBC output too short"); + assertDxbcMagic(out.code()); + assertEquals("main", out.entrypoint()); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void fragmentShaderCrossCompilesAndProducesDxbc() { + final ByteBuffer spirv = compile(SpirvTestShaders.FRAGMENT_GLSL, Shaderc.shaderc_fragment_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + final DxbcCrossCompile.Output out = DxbcCrossCompile.compile(spirv, GL20.GL_FRAGMENT_SHADER); + try { + assertNotNull(out.code()); + assertTrue(out.code().remaining() >= 4, "DXBC output too short"); + assertDxbcMagic(out.code()); + assertEquals("main", out.entrypoint()); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + + @Test + void computeShaderCrossCompilesAndProducesDxbc() { + final ByteBuffer spirv = compile(SpirvTestShaders.HIZ_INIT_GLSL, Shaderc.shaderc_compute_shader); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final DxbcCrossCompile.Output out = DxbcCrossCompile.compile(spirv, GL43.GL_COMPUTE_SHADER); + try { + assertNotNull(out.code()); + assertTrue(out.code().remaining() >= 4, "DXBC compute output too short"); + assertDxbcMagic(out.code()); + assertEquals("main", out.entrypoint()); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void garbageHlslSurfacesD3DCompileError() { + final String bad = "this is not valid hlsl !!!"; + final RuntimeException ex = assertThrows(RuntimeException.class, + () -> { + final ByteBuffer code = D3DCompiler.compile(bad, "main", "vs_5_0", D3DCompiler.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCompiler.D3DCOMPILE_ENABLE_STRICTNESS, 0); + MemoryUtil.memFree(code); + }); + assertTrue(ex.getMessage().contains("D3DCompile failed"), "Exception message should mention D3DCompile failure: " + ex.getMessage()); + assertTrue(ex.getMessage().length() > "D3DCompile failed (HRESULT=0x80004005): ".length(), "Exception message should include error blob text: " + ex.getMessage()); + } + + @Test + void crossCompileFreesNativeMemory() { + for (int i = 0; i < 200; i++) { + final ByteBuffer spirv = compile(SpirvTestShaders.VERTEX_GLSL, Shaderc.shaderc_vertex_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_VERTEX_SHADER); + final DxbcCrossCompile.Output out = DxbcCrossCompile.compile(spirv, GL20.GL_VERTEX_SHADER); + MemoryUtil.memFree(out.code()); + } finally { + MemoryUtil.memFree(spirv); + } + } + } + + private static void assertDxbcMagic(ByteBuffer dxbc) { + final ByteBuffer view = dxbc.duplicate(); + assertEquals(DXBC_MAGIC_D, view.get(0), "DXBC magic byte 0"); + assertEquals(DXBC_MAGIC_X, view.get(1), "DXBC magic byte 1"); + assertEquals(DXBC_MAGIC_B, view.get(2), "DXBC magic byte 2"); + assertEquals(DXBC_MAGIC_C, view.get(3), "DXBC magic byte 3"); + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "test_shader", SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("Shader compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcHlslSpacesTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcHlslSpacesTest.java new file mode 100644 index 000000000..866187e16 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/dxbc/DxbcHlslSpacesTest.java @@ -0,0 +1,98 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.dxbc; + +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.sdlgpu.shader.SpirvTestShaders; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class DxbcHlslSpacesTest { + + private static final String VS_WITH_UBO_AND_SAMPLER = """ + #version 460 core + layout(location = 0) in vec3 a_Position; + layout(location = 2) in vec2 a_TexCoord0; + layout(std140, binding = 0) uniform Matrices { mat4 mvp; } u; + layout(binding = 0) uniform sampler2D vsSampler; + layout(location = 0) out vec2 v_TexCoord0; + void main() { + // touch vsSampler so glslang doesn't strip it + float bias = texture(vsSampler, vec2(0.0)).r; + gl_Position = u.mvp * vec4(a_Position, 1.0 + bias * 0.0); + v_TexCoord0 = a_TexCoord0; + } + """; + + private static final String FS_WITH_UBO_AND_SAMPLER = """ + #version 460 core + layout(location = 0) in vec2 v_TexCoord0; + layout(binding = 0) uniform sampler2D u_Sampler0; + layout(std140, binding = 0) uniform Color { vec4 tint; } c; + layout(location = 0) out vec4 fragColor; + void main() { + fragColor = texture(u_Sampler0, v_TexCoord0) * c.tint; + } + """; + + @Test + void vsSpaceMapping_ubosAtSpace1_samplersAtSpace0() { + final ByteBuffer spirv = compile(VS_WITH_UBO_AND_SAMPLER, Shaderc.shaderc_vertex_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_VERTEX_SHADER); + final String hlsl = DxbcCrossCompile.compileToHlsl(spirv, GL20.GL_VERTEX_SHADER); + + assertTrue(hlsl.contains("space1"), "VS HLSL must reference space1 for the UBO. HLSL:\n" + hlsl); + assertFalse(hlsl.contains("space2"), "VS HLSL must not reference space2. HLSL:\n" + hlsl); + assertFalse(hlsl.contains("space3"), "VS HLSL must not reference space3. HLSL:\n" + hlsl); + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void fsSpaceMapping_ubosAtSpace3_samplersAtSpace2() { + final ByteBuffer spirv = compile(FS_WITH_UBO_AND_SAMPLER, Shaderc.shaderc_fragment_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + final String hlsl = DxbcCrossCompile.compileToHlsl(spirv, GL20.GL_FRAGMENT_SHADER); + + assertTrue(hlsl.contains("space2"), "FS HLSL must reference space2 for the sampler/SRV. HLSL:\n" + hlsl); + assertTrue(hlsl.contains("space3"), "FS HLSL must reference space3 for the UBO. HLSL:\n" + hlsl); + assertFalse(hlsl.contains("space1"), "FS HLSL must not reference space1. HLSL:\n" + hlsl); + } finally { + MemoryUtil.memFree(spirv); + } + } + + + @Test + void ldsMultiMipCompute_hlslHasGroupsharedAndBarrier() { + final ByteBuffer spirv = compile(SpirvTestShaders.LDS_MULTI_MIP_GLSL, Shaderc.shaderc_compute_shader); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final String hlsl = DxbcCrossCompile.compileToHlsl(spirv, GL43.GL_COMPUTE_SHADER); + assertTrue(hlsl.contains("groupshared"), "shared array must become groupshared. HLSL:\n" + hlsl); + assertTrue(hlsl.contains("GroupMemoryBarrierWithGroupSync"), "barrier() must become GroupMemoryBarrierWithGroupSync. HLSL:\n" + hlsl); + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "hlsl_spaces_test", + SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("shader compile failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/FragmentStorageTextureSlotTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/FragmentStorageTextureSlotTest.java new file mode 100644 index 000000000..a9f3597c1 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/FragmentStorageTextureSlotTest.java @@ -0,0 +1,178 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.msl; + +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class FragmentStorageTextureSlotTest { + + private static String fragmentSource(int samplerCount) { + final StringBuilder sb = new StringBuilder(); + sb.append("#version 460 core\n"); + for (int i = 0; i < samplerCount; i++) { + sb.append("uniform sampler2D tex").append(i).append(";\n"); + } + sb.append("layout(r16ui) readonly uniform uimage3D voxel_img;\n"); + sb.append("layout(location = 0) out vec4 fragColor;\n"); + sb.append("void main() {\n"); + sb.append(" vec4 acc = vec4(0.0);\n"); + for (int i = 0; i < samplerCount; i++) { + sb.append(" acc += texture(tex").append(i).append(", vec2(0.5));\n"); + } + sb.append(" uint v = imageLoad(voxel_img, ivec3(1, 2, 3)).x;\n"); + sb.append(" fragColor = acc + vec4(float(v));\n"); + sb.append("}\n"); + return sb.toString(); + } + + private static int mslTextureIndex(String msl, String name) { + final Matcher m = Pattern.compile(Pattern.quote(name) + "\\s*\\[\\[texture\\((\\d+)\\)\\]\\]").matcher(msl); + if (!m.find()) fail("no [[texture(n)]] attribute for '" + name + "' in MSL:\n" + msl); + return Integer.parseInt(m.group(1)); + } + + private void assertSlots(int samplerCount) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(fragmentSource(samplerCount), + GL20.GL_FRAGMENT_SHADER, "storage-slot-s" + samplerCount, true); + final String src = pre != null ? pre.rewrittenSource() : fragmentSource(samplerCount); + final SpirvCompiler.Result r = SpirvCompiler.compile(src, + Shaderc.shaderc_fragment_shader, "storage-slot-s" + samplerCount, SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) fail("compile failed: " + r.error() + "\nsource:\n" + src); + final ByteBuffer spirv = r.spirv(); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL20.GL_FRAGMENT_SHADER); + try { + final String msl = StandardCharsets.UTF_8.decode(out.code().duplicate()).toString(); + final boolean[] seen = new boolean[samplerCount]; + for (int i = 0; i < samplerCount; i++) { + final int idx = mslTextureIndex(msl, "tex" + i); + assertTrue(idx >= 0 && idx < samplerCount, "sampler tex" + i + " landed at Metal texture index " + idx + ", outside [0.." + samplerCount + "):\n" + msl); + assertTrue(!seen[idx], "duplicate Metal texture index " + idx + ":\n" + msl); + seen[idx] = true; + } + assertEquals(samplerCount, mslTextureIndex(msl, "voxel_img"), "storage image must sit at Metal texture index " + samplerCount + ":\n" + msl); + assertTrue(msl.contains("voxel_img.read("), "storage image must be read via texture read:\n" + msl); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test void storageTextureAfterZeroSamplers() { assertSlots(0); } + @Test void storageTextureAfterOneSampler() { assertSlots(1); } + @Test void storageTextureAfterThreeSamplers() { assertSlots(3); } + + @Test void multipleStorageImagesFollowReflectionOrder() throws Exception { + final String src = String.join("\n", + "#version 460 core", + "uniform sampler2D texA;", + "uniform sampler2D texB;", + "layout(r16ui) readonly uniform uimage3D wsr_img;", + "layout(r16ui) readonly uniform uimage3D voxel_img;", + "layout(r8ui) readonly uniform uimage3D wsr_lod_img;", + "layout(location = 0) out vec4 fragColor;", + "void main() {", + " uint v = imageLoad(voxel_img, ivec3(1)).x + imageLoad(wsr_img, ivec3(2)).x + imageLoad(wsr_lod_img, ivec3(3)).x;", + " fragColor = texture(texA, vec2(0.5)) + texture(texB, vec2(0.5)) + vec4(float(v));", + "}", + ""); + assertProductionContract(src, "multi-image"); + } + + @Test void terrainShapedFragmentFollowsReflectionOrder() throws Exception { + assertProductionContract(String.join("\n", + "#version 460 core", + "uniform sampler2D gtexture;", + "uniform sampler2D lightmap;", + "uniform sampler2D normals;", + "uniform sampler2D specular;", + "uniform sampler2D shadowtex0;", + "uniform sampler2D shadowtex1;", + "uniform sampler2D noisetex;", + "layout(r16ui) readonly uniform uimage3D voxel_img;", + "layout(r16ui) readonly uniform uimage3D wsr_img;", + "in vec4 iris_FrontColor;", + "in vec2 texcoord;", + "in vec3 iris_Normal;", + "layout(location = 0) out vec4 fragColor;", + "void main() {", + " vec4 albedo = texture(gtexture, texcoord) * iris_FrontColor;", + " albedo += texture(lightmap, texcoord) + texture(normals, texcoord) + texture(specular, texcoord);", + " albedo += texture(shadowtex0, texcoord) + texture(shadowtex1, texcoord) + texture(noisetex, texcoord);", + " uint v = imageLoad(voxel_img, ivec3(texcoord * 8.0, 1)).x + imageLoad(wsr_img, ivec3(2)).x;", + " fragColor = albedo + vec4(float(v)) + vec4(iris_Normal, 0.0);", + "}", + ""), "terrain-shaped"); + } + + private void assertProductionContract(String source, String label) throws Exception { + final ShaderManager sm = new ShaderManager(null); + final int shader = sm.createShader(GL20.GL_FRAGMENT_SHADER); + sm.shaderSource(shader, source); + sm.compileShader(shader); + + final Map shaderObjects = Reflect.get(sm, "shaderObjects"); + final Object obj = shaderObjects.values().iterator().next(); + assertTrue(Reflect.get(obj, "compiled"), label + " must compile"); + final ByteBuffer spirv = Reflect.get(obj, "spirv"); + final ShaderManager.StageReflection refl = Reflect.get(obj, "reflection"); + + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL20.GL_FRAGMENT_SHADER); + try { + final String msl = StandardCharsets.UTF_8.decode(out.code().duplicate()).toString(); + final int samplerCount = refl.counts().numSamplers(); + final StringBuilder report = new StringBuilder(); + for (int i = 0; i < refl.samplerNames().size(); i++) { + final String n = refl.samplerNames().get(i); + final int idx = mslTextureIndexOrMissing(msl, n); + report.append("sampler[").append(i).append("] ").append(n).append(" -> ") + .append(idx < 0 ? "ABSENT (SPIRV-Cross inactive)" : "texture(" + idx + ")").append('\n'); + } + for (int i = 0; i < refl.storageImageNames().size(); i++) { + final String n = refl.storageImageNames().get(i); + final int idx = mslTextureIndexOrMissing(msl, n); + report.append("storage[").append(i).append("] ").append(n).append(" -> ") + .append(idx < 0 ? "ABSENT" : "texture(" + idx + ")").append(" expected texture(").append(samplerCount + i).append(")\n"); + } + for (int i = 0; i < refl.samplerNames().size(); i++) { + final int idx = mslTextureIndexOrMissing(msl, refl.samplerNames().get(i)); + if (idx < 0) continue; // inactive: nothing reads it; a hole is only fatal if it shifts others + assertEquals(i, idx, label + ": active sampler '" + refl.samplerNames().get(i) + "' at wrong Metal index.\n" + report + "\nMSL:\n" + msl); + } + for (int i = 0; i < refl.storageImageNames().size(); i++) { + final int idx = mslTextureIndexOrMissing(msl, refl.storageImageNames().get(i)); + if (idx < 0) continue; // inactive: the binder still fills its API slot, which is exactly why shifts matter + assertEquals(samplerCount + i, idx, + label + ": storage image '" + refl.storageImageNames().get(i) + + "' at wrong Metal index (binder binds it at API slot " + i + + " => Metal texture " + (samplerCount + i) + ").\n" + report + "\nMSL head:\n" + + msl.substring(0, Math.min(1500, msl.length()))); + } + } finally { + MemoryUtil.memFree(out.code()); + } + } + + private static int mslTextureIndexOrMissing(String msl, String name) { + final Matcher m = Pattern.compile(Pattern.quote(name) + "\\s*\\[\\[texture\\((\\d+)\\)\\]\\]").matcher(msl); + return m.find() ? Integer.parseInt(m.group(1)) : -1; + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompileTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompileTest.java new file mode 100644 index 000000000..359d4f4ab --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/msl/MslCrossCompileTest.java @@ -0,0 +1,407 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader.msl; + +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; +import com.gtnewhorizons.angelica.sdlgpu.shader.SpirvTestShaders; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.shaderc.Shaderc; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Tests SPIR-V → MSL cross-compilation for the macOS/Metal backend. + */ +class MslCrossCompileTest { + + + + @Test + void vertexShaderCrossCompiles() { + final ByteBuffer spirv = compile(SpirvTestShaders.VERTEX_GLSL, Shaderc.shaderc_vertex_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_VERTEX_SHADER); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL20.GL_VERTEX_SHADER); + try { + final String msl = decode(out.code()); + assertTrue(msl.length() > 0, "MSL output non-empty"); + assertTrue(msl.contains("vertex "), "MSL should contain vertex stage qualifier:\n" + msl); + assertFalse(msl.contains("descriptor_set"), "MSL must not leak descriptor_set decorations:\n" + msl); + assertTrue(msl.contains("[[buffer(0)]]"), "UBO should land at [[buffer(0)]]:\n" + msl); + assertTrue(msl.contains("[[texture(0)]]"), "sampler2D should land at [[texture(0)]]:\n" + msl); + assertTrue(msl.contains("[[sampler(0)]]"), "sampler2D should land at [[sampler(0)]]:\n" + msl); + assertEquals("main0", out.entrypoint(), "Metal forbids main; expect main0"); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + @Test + void fragmentShaderCrossCompiles() { + final ByteBuffer spirv = compile(SpirvTestShaders.FRAGMENT_GLSL, Shaderc.shaderc_fragment_shader); + try { + ShaderManager.remapSpirvForSDLGPU(spirv, GL20.GL_FRAGMENT_SHADER); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL20.GL_FRAGMENT_SHADER); + try { + final String msl = decode(out.code()); + assertTrue(msl.contains("fragment "), "MSL should contain fragment stage qualifier:\n" + msl); + assertTrue(msl.contains("[[buffer(0)]]"), "Fragment UBO should land at [[buffer(0)]]:\n" + msl); + assertTrue(msl.contains("[[texture(0)]]"), "First sampler at [[texture(0)]]:\n" + msl); + assertTrue(msl.contains("[[texture(1)]]"), "Second sampler at [[texture(1)]]:\n" + msl); + assertTrue(msl.contains("[[sampler(0)]]") && msl.contains("[[sampler(1)]]"), + "Samplers at slots 0 and 1:\n" + msl); + assertEquals("main0", out.entrypoint()); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static final String CHUNK_CULL_GLSL = """ + #version 460 core + layout(local_size_x = 64) in; + layout(std430, binding = 0) readonly buffer A { uint a[]; } visible; + layout(std430, binding = 1) readonly buffer B { uint b[]; } meta; + layout(std430, binding = 2) writeonly buffer C { uint c[]; } indirect; + layout(binding = 3) uniform sampler2D u_Hiz; + layout(std140, binding = 0) uniform Frustum { vec4 control; } frustum; + void main() { + uint gid = gl_GlobalInvocationID.x; + if (gid >= uint(frustum.control.x)) return; + indirect.c[gid] = visible.a[gid] + meta.b[gid] + uint(textureLod(u_Hiz, vec2(0), 0).r); + } + """; + + + @Test + void ldsMultiMipComputeCrossCompiles() { + final ByteBuffer spirv = compile(SpirvTestShaders.LDS_MULTI_MIP_GLSL, Shaderc.shaderc_compute_shader); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL43.GL_COMPUTE_SHADER); + try { + final String msl = decode(out.code()); + assertTrue(msl.contains("kernel "), "Compute MSL should contain kernel stage qualifier:\n" + msl); + assertTrue(msl.contains("threadgroup spvUnsafeArray= _vg_startVertex + _vg_vertexCount) return; + imageAtomicAdd(endcrystal_img, ivec2(id, 0), 1); + imageStore(voxel_img, ivec3(0), uvec4(uint(id), 0u, 0u, 0u)); + } + """; + + @Test + void chunkComputeWithImageAtomic_mslBufferSlotsAreUnique() { + assertMslBufferSlotsUnique(CHUNK_COMPUTE_WITH_ATOMIC_IMAGE_GLSL); + } + + private static final String COMPOSITE_VSH_COMPUTE_WITH_ATOMIC_IMAGE_GLSL = """ + #version 460 core + layout(local_size_x = 64) in; + layout(binding = 0, r32i) uniform iimage2D endcrystal_img; + uniform mat4 iris_ModelViewProjectionMatrix; + const vec4 _vg_quad[4] = vec4[4]( + vec4(1.0, 1.0, 0.0, 1.0), + vec4(0.0, 1.0, 0.0, 1.0), + vec4(1.0, 0.0, 0.0, 1.0), + vec4(0.0, 0.0, 0.0, 1.0)); + vec4 _vg_gl_vertex; + int _vg_gl_vertex_id; + #define iris_GlVertex _vg_gl_vertex + #define iris_GlVertexID _vg_gl_vertex_id + vec4 iris_ftransform() { return iris_ModelViewProjectionMatrix * iris_GlVertex; } + void _vg_body() { + imageAtomicAdd(endcrystal_img, ivec2(iris_GlVertexID, 0), 1); + } + void main() { + uint vid = gl_GlobalInvocationID.x; + if (vid >= 4u) return; + _vg_gl_vertex = _vg_quad[vid]; + _vg_gl_vertex_id = int(vid); + _vg_body(); + } + """; + + @Test + void compositeVshComputeWithImageAtomic_mslBufferSlotsAreUnique() { + assertMslBufferSlotsUnique(COMPOSITE_VSH_COMPUTE_WITH_ATOMIC_IMAGE_GLSL); + } + + // Mirrors composite-fsh: 2D dispatch + _vg_target_size uniform + gl_FragCoord shim. + private static final String COMPOSITE_FSH_COMPUTE_WITH_ATOMIC_IMAGE_GLSL = """ + #version 460 core + layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + layout(binding = 0, r32i) uniform iimage2D endcrystal_img; + uniform ivec2 _vg_target_size; + vec4 _vg_gl_fragcoord_raw; + #define gl_FragCoord _vg_gl_fragcoord_raw + void _vg_body() { + imageAtomicAdd(endcrystal_img, ivec2(gl_FragCoord.xy), 1); + } + void main() { + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (px.x >= _vg_target_size.x || px.y >= _vg_target_size.y) return; + _vg_gl_fragcoord_raw = vec4(vec2(px) + 0.5, 0.0, 1.0); + _vg_body(); + } + """; + + @Test + void compositeFshComputeWithImageAtomic_mslBufferSlotsAreUnique() { + assertMslBufferSlotsUnique(COMPOSITE_FSH_COMPUTE_WITH_ATOMIC_IMAGE_GLSL); + } + + private static final String CHUNK_COMPUTE_WITH_INLINE_ATOMIC_GLSL = """ + #version 460 core + layout(local_size_x = 64) in; + layout(binding = 0, r32i) uniform iimage2D endcrystal_img; + uniform int _vg_startVertex; + uniform int _vg_vertexCount; + layout(std430, binding = 9) readonly buffer _VgVbuf { uint data[]; } _vg_vbuf; + void main() { + { int _vg_prev = imageLoad(endcrystal_img, ivec2(0, 0)).x; + imageStore(endcrystal_img, ivec2(0, 0), ivec4(_vg_prev + 1, 0, 0, 0)); } + } + """; + + @Test + void chunkComputeWithInlineAtomic_shadercAccepts() { + final ByteBuffer spirv = compile(CHUNK_COMPUTE_WITH_INLINE_ATOMIC_GLSL, Shaderc.shaderc_compute_shader); + MemoryUtil.memFree(spirv); + } + + private static void assertMslBufferSlotsUnique(String glsl) { + final ByteBuffer spirv = compile(glsl, Shaderc.shaderc_compute_shader); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL43.GL_COMPUTE_SHADER); + try { + final String msl = decode(out.code()); + assertUniqueBufferSlots(msl); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + + private static void assertUniqueBufferSlots(String msl) { + final Set seen = new HashSet<>(); + int from = 0; + final String marker = "[[buffer("; + while (true) { + final int open = msl.indexOf(marker, from); + if (open < 0) break; + final int numStart = open + marker.length(); + final int close = msl.indexOf(')', numStart); + if (close < 0) break; + final String numText = msl.substring(numStart, close).trim(); + final int slot; + try { + slot = Integer.parseInt(numText); + } catch (NumberFormatException nfe) { + from = close + 1; + continue; + } + assertTrue(seen.add(slot), + "duplicate [[buffer(" + slot + ")]] annotation in MSL output (SDL_GPU MSL atomic emulation collision?):\n" + msl); + from = close + 1; + } + assertFalse(seen.isEmpty(), "expected at least one [[buffer(N)]] in MSL output:\n" + msl); + } + + private static void assertSlot(String msl, String imageName, int slot, String shader) { + final Matcher m = Pattern .compile(imageName + "\\s*\\[\\[texture\\((\\d+)\\)\\]\\]").matcher(msl); + assertTrue(m.find(), shader + ": " + imageName + " missing [[texture(N)]]:\n" + msl); + assertEquals(slot, Integer.parseInt(m.group(1)), shader + ": " + imageName + " at wrong Metal texture slot:\n" + msl); + } + + @Test + void realCullingShadersCrossCompile() throws IOException { + final String[] names = { "chunk_cull.csh" }; + for (String name : names) { + Path p = Path.of("src/main/resources/assets/angelica/shaders/culling/" + name); + if (!Files.exists(p)) { + p = Path.of("../src/main/resources/assets/angelica/shaders/culling/" + name); + } + final String glsl = Files.readString(p); + final ByteBuffer spirv = compile(glsl, Shaderc.shaderc_compute_shader); + try { + ShaderManager.remapSpirvForComputeSDLGPU(spirv); + final MslCrossCompile.Output out = MslCrossCompile.compile(spirv, GL43.GL_COMPUTE_SHADER); + try { + assertTrue(decode(out.code()).contains("kernel "), name + " should produce compute MSL"); + } finally { + MemoryUtil.memFree(out.code()); + } + } finally { + MemoryUtil.memFree(spirv); + } + } + } + + private static String decode(ByteBuffer buf) { + final ByteBuffer slice = buf.duplicate(); + int len = slice.remaining(); + if (len > 0 && slice.get(slice.limit() - 1) == 0) len--; + final byte[] bytes = new byte[len]; + slice.get(bytes, 0, len); + return new String(bytes, StandardCharsets.UTF_8); + } + + private static ByteBuffer compile(String source, int shaderKind) { + final SpirvCompiler.Result r = SpirvCompiler.compile(source, shaderKind, "test_shader", + SpirvCompiler.Options.vulkanForced460Core()); + if (r.spirv() == null) { + fail("Shader compilation failed: " + r.error()); + } + return r.spirv(); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/AutoVaoBindTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/AutoVaoBindTest.java new file mode 100644 index 000000000..adce78e21 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/AutoVaoBindTest.java @@ -0,0 +1,57 @@ +package com.gtnewhorizons.angelica.sdlgpu.threading; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.*; + +class AutoVaoBindTest { + + private static final class Gate { + final ThreadLocal autoBound = ThreadLocal.withInitial(() -> Boolean.FALSE); + final Thread mainThread; + Gate(Thread main) { this.mainThread = main; } + + boolean wouldAutoBind() { + if (Thread.currentThread() == mainThread) return false; + if (autoBound.get()) return false; + autoBound.set(Boolean.TRUE); + return true; + } + } + + @Test + void mainThreadDoesNotAutoBind() { + final Gate g = new Gate(Thread.currentThread()); + assertFalse(g.wouldAutoBind()); + assertFalse(g.wouldAutoBind(), "still false on subsequent calls"); + } + + @Test + void nonMainThreadAutoBindsOnce() throws Exception { + final Gate g = new Gate(Thread.currentThread()); + final AtomicBoolean firstCall = new AtomicBoolean(); + final AtomicBoolean secondCall = new AtomicBoolean(); + final Thread t = new Thread(() -> { + firstCall.set(g.wouldAutoBind()); + secondCall.set(g.wouldAutoBind()); + }, "non-main"); + t.start(); + t.join(); + assertTrue(firstCall.get(), "first call from non-main thread auto-binds"); + assertFalse(secondCall.get(), "second call does not"); + } + + @Test + void distinctNonMainThreadsEachAutoBind() throws Exception { + final Gate g = new Gate(Thread.currentThread()); + final AtomicBoolean a = new AtomicBoolean(); + final AtomicBoolean b = new AtomicBoolean(); + final Thread tA = new Thread(() -> a.set(g.wouldAutoBind()), "non-main-a"); + final Thread tB = new Thread(() -> b.set(g.wouldAutoBind()), "non-main-b"); + tA.start(); tB.start(); tA.join(); tB.join(); + assertTrue(a.get()); + assertTrue(b.get()); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/ContextStateNativeBufsAllocatedTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/ContextStateNativeBufsAllocatedTest.java new file mode 100644 index 000000000..08ae62d9b --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/ContextStateNativeBufsAllocatedTest.java @@ -0,0 +1,36 @@ +package com.gtnewhorizons.angelica.sdlgpu.threading; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +class ContextStateNativeBufsAllocatedTest { + + @Test + void freshContextStateHasAllNativeBufsAllocated() { + final ContextState cs = new ContextState(); + assertNotEquals(0L, cs.vboBindingsAddr, "vboBindingsAddr must be allocated"); + assertNotNull(cs.eboBinding, "eboBinding must be allocated"); + assertNotNull(cs.cachedViewport, "cachedViewport must be allocated"); + assertNotNull(cs.cachedScissor, "cachedScissor must be allocated"); + assertNotNull(cs.cachedBlendColor, "cachedBlendColor must be allocated"); + } + + @Test + void nonMainThreadContextStateHasAllNativeBufsAllocated() throws Exception { + final AtomicReference result = new AtomicReference<>(); + final Thread t = new Thread(() -> result.set(new ContextState()), "non-main-ctxstate"); + t.start(); + t.join(); + final ContextState cs = result.get(); + assertNotNull(cs); + assertNotEquals(0L, cs.vboBindingsAddr); + assertNotNull(cs.cachedViewport); + assertNotNull(cs.cachedScissor); + assertNotNull(cs.cachedBlendColor); + assertNotNull(cs.eboBinding); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PerThreadContextStateTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PerThreadContextStateTest.java new file mode 100644 index 000000000..f69cfe120 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PerThreadContextStateTest.java @@ -0,0 +1,82 @@ +package com.gtnewhorizons.angelica.sdlgpu.threading; + +import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +class PerThreadContextStateTest { + + @Test + void twoThreadsHaveIndependentBoundProgram() throws Exception { + final ThreadLocal tl = ThreadLocal.withInitial(ContextState::new); + final CountDownLatch start = new CountDownLatch(1); + final CountDownLatch step1 = new CountDownLatch(2); + final CountDownLatch step2 = new CountDownLatch(1); + final AtomicInteger seenA = new AtomicInteger(-1); + final AtomicInteger seenB = new AtomicInteger(-1); + final AtomicReference failure = new AtomicReference<>(); + + final Thread a = new Thread(() -> { + try { + start.await(); + tl.get().boundProgram = 100; + tl.get().boundTextures[0] = 1001; + tl.get().viewportX = 10.0f; tl.get().viewportY = 20.0f; + step1.countDown(); + step2.await(); + seenA.set(tl.get().boundProgram); + assertEquals(1001, tl.get().boundTextures[0]); + assertEquals(10.0f, tl.get().viewportX); + } catch (Throwable e) { failure.compareAndSet(null, e); } + }, "ctxstate-a"); + + final Thread b = new Thread(() -> { + try { + start.await(); + tl.get().boundProgram = 200; + tl.get().boundTextures[0] = 2002; + tl.get().viewportX = 30.0f; tl.get().viewportY = 40.0f; + step1.countDown(); + step2.await(); + seenB.set(tl.get().boundProgram); + assertEquals(2002, tl.get().boundTextures[0]); + assertEquals(30.0f, tl.get().viewportX); + } catch (Throwable e) { failure.compareAndSet(null, e); } + }, "ctxstate-b"); + + a.start(); b.start(); + start.countDown(); + assertTrue(step1.await(5, TimeUnit.SECONDS)); + step2.countDown(); + a.join(TimeUnit.SECONDS.toMillis(5)); + b.join(TimeUnit.SECONDS.toMillis(5)); + + assertNull(failure.get(), () -> "race: " + failure.get()); + assertEquals(100, seenA.get(), "thread A should see its own boundProgram"); + assertEquals(200, seenB.get(), "thread B should see its own boundProgram"); + } + + @Test + void freshContextStateHasIdentityAttribBinding() { + final ContextState cs = new ContextState(); + for (int i = 0; i < ContextState.MAX_VERTEX_ATTRIBS; i++) { + assertEquals(i, cs.currentVao.attribBinding[i], "currentVao.attribBinding[" + i + "] should default to identity per GL spec"); + } + } + + @Test + void freshContextStateHasGLSpecDefaults() { + final ContextState cs = new ContextState(); + assertEquals(0.0f, cs.viewportDepthNear); + assertEquals(1.0f, cs.viewportDepthFar); + assertTrue(cs.viewportDirty); + assertTrue(cs.scissorDirty); + assertTrue(cs.blendColorDirty); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PipelineCacheConcurrentBuildTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PipelineCacheConcurrentBuildTest.java new file mode 100644 index 000000000..240f9acdc --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/threading/PipelineCacheConcurrentBuildTest.java @@ -0,0 +1,75 @@ +package com.gtnewhorizons.angelica.sdlgpu.threading; + +import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PipelineCacheConcurrentBuildTest { + + @Test + void concurrentDistinctKeys_allBuiltOnce() throws Exception { + final PipelineStore store = new PipelineStore(null); + final AtomicInteger builds = new AtomicInteger(); + final int threads = 8; + final int keysPerThread = 500; + final CountDownLatch start = new CountDownLatch(1); + final Thread[] all = new Thread[threads]; + for (int t = 0; t < threads; t++) { + final int tid = t; + all[t] = new Thread(() -> { + try { start.await(); } catch (InterruptedException ignored) { return; } + for (int i = 0; i < keysPerThread; i++) { + final long key = ((long) tid << 16) | i; + final long p = store.getOrBuild(key, () -> { builds.incrementAndGet(); return key * 1000L + 1; }); + assertEquals(key * 1000L + 1, p); + } + }, "build-" + t); + all[t].start(); + } + start.countDown(); + for (Thread th : all) th.join(TimeUnit.SECONDS.toMillis(10)); + assertEquals(threads * keysPerThread, builds.get(), "Each distinct key should be built exactly once"); + } + + @Test + void concurrentSameKey_builtOnce_allCallersGetSamePipeline() throws Exception { + final PipelineStore store = new PipelineStore(null); + final AtomicInteger builds = new AtomicInteger(); + final int threads = 16; + final long key = 0xDEADBEEFL; + final long[] results = new long[threads]; + final CountDownLatch start = new CountDownLatch(1); + final Thread[] all = new Thread[threads]; + for (int t = 0; t < threads; t++) { + final int tid = t; + all[t] = new Thread(() -> { + try { start.await(); } catch (InterruptedException ignored) { return; } + results[tid] = store.getOrBuild(key, () -> { builds.incrementAndGet(); return key * 1000L + 1; }); + }, "race-" + t); + all[t].start(); + } + start.countDown(); + for (Thread th : all) th.join(TimeUnit.SECONDS.toMillis(10)); + assertEquals(1, builds.get(), "Same key must build exactly once across threads"); + for (int i = 0; i < threads; i++) { + assertEquals(results[0], results[i], "All threads must see the same pipeline handle"); + } + } + + @Test + void badSentinelKey_cachedAsZero_notRebuilt() { + final PipelineStore store = new PipelineStore(null); + final AtomicInteger builds = new AtomicInteger(); + final long key = 7L; + final long first = store.getOrBuild(key, () -> { builds.incrementAndGet(); return -1L; }); + final long second = store.getOrBuild(key, () -> { builds.incrementAndGet(); return 999L; }); + assertEquals(0L, first, "known-bad build reports 0"); + assertEquals(0L, second, "known-bad key returns 0 without rebuilding"); + assertEquals(1, builds.get(), "bad key builds once, then stays cached"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelayTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelayTest.java new file mode 100644 index 000000000..bdf822b37 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/util/DebugMessageRelayTest.java @@ -0,0 +1,124 @@ +package com.gtnewhorizons.angelica.sdlgpu.util; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.KHRDebug; +import org.lwjgl.sdl.SDLLog; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DebugMessageRelayTest { + + @AfterEach + void reset() { + DebugMessageRelay.setListener(null, 0L, true); + drainAll(); + } + + private static void drainAll() { + try (MemoryStack stack = MemoryStack.stackPush()) { + final ByteBuffer log = stack.malloc(4096); + while (DebugMessageRelay.drain(64, null, null, null, null, null, log) > 0) { + log.clear(); + } + } + } + + private record Received(int source, int type, int severity, String message) {} + + private static List captureFrom(int priority, String message, boolean validationLayerActive) { + final List got = new ArrayList<>(); + DebugMessageRelay.setListener((source, type, id, severity, length, msg, userParam) -> + got.add(new Received(source, type, severity, MemoryUtil.memUTF8(MemoryUtil.memByteBuffer(msg, length)))), + 0L, validationLayerActive); + try (MemoryStack stack = MemoryStack.stackPush()) { + DebugMessageRelay.onSdlMessage(priority, MemoryUtil.memAddress(stack.UTF8(message))); + } + return got; + } + + @Test + void errorMessageReachesTheListenerAsAHighSeverityApiError() { + final List got = captureFrom(SDLLog.SDL_LOG_PRIORITY_ERROR, "validation exploded", true); + + assertEquals(1, got.size()); + assertEquals(KHRDebug.GL_DEBUG_SOURCE_API, got.get(0).source()); + assertEquals(KHRDebug.GL_DEBUG_TYPE_ERROR, got.get(0).type()); + assertEquals(KHRDebug.GL_DEBUG_SEVERITY_HIGH, got.get(0).severity()); + assertEquals("validation exploded", got.get(0).message()); + } + + @Test + void warningIsMediumAndNotAnError() { + final List got = captureFrom(SDLLog.SDL_LOG_PRIORITY_WARN, "heads up", true); + + assertEquals(KHRDebug.GL_DEBUG_SEVERITY_MEDIUM, got.get(0).severity()); + assertNotEquals(KHRDebug.GL_DEBUG_TYPE_ERROR, got.get(0).type()); + } + + @Test + void registrationIsAcceptedWithTheValidationLayerOff() { + final List got = captureFrom(SDLLog.SDL_LOG_PRIORITY_ERROR, "still delivered if SDL logs", false); + + assertEquals(1, got.size(), "SDL only emits when the layer is on; if a message does arrive, deliver it"); + } + + @Test + void getDebugMessageLogDrainsOldestFirstThenReportsEmpty() { + DebugMessageRelay.setListener(null, 0L, true); + try (MemoryStack stack = MemoryStack.stackPush()) { + DebugMessageRelay.onSdlMessage(SDLLog.SDL_LOG_PRIORITY_ERROR, MemoryUtil.memAddress(stack.UTF8("first"))); + DebugMessageRelay.onSdlMessage(SDLLog.SDL_LOG_PRIORITY_WARN, MemoryUtil.memAddress(stack.UTF8("second"))); + + final IntBuffer severities = stack.mallocInt(4); + final IntBuffer lengths = stack.mallocInt(4); + final ByteBuffer log = stack.malloc(256); + + assertEquals(2, DebugMessageRelay.drain(4, null, null, null, severities, lengths, log)); + + assertEquals(KHRDebug.GL_DEBUG_SEVERITY_HIGH, severities.get(0)); + assertEquals(KHRDebug.GL_DEBUG_SEVERITY_MEDIUM, severities.get(1)); + assertEquals("first".length() + 1, lengths.get(0), "GL counts the NUL terminator"); + + log.flip(); + final byte[] bytes = new byte[log.remaining()]; + log.get(bytes); + final String flat = new String(bytes, StandardCharsets.UTF_8); + assertTrue(flat.startsWith("first\0"), () -> "oldest first, NUL separated: " + flat); + + assertEquals(0, DebugMessageRelay.drain(4, null, null, null, null, null, stack.malloc(64))); + } + } + + @Test + void nullListenerUnregisters() { + captureFrom(SDLLog.SDL_LOG_PRIORITY_ERROR, "before", true); + DebugMessageRelay.setListener(null, 0L, true); + try (MemoryStack stack = MemoryStack.stackPush()) { + DebugMessageRelay.onSdlMessage(SDLLog.SDL_LOG_PRIORITY_ERROR, MemoryUtil.memAddress(stack.UTF8("after"))); + } + try (MemoryStack stack = MemoryStack.stackPush()) { + assertTrue(DebugMessageRelay.drain(8, null, null, null, null, null, stack.malloc(512)) > 0); + } + } + + @Test + void drainStopsWhenTheMessageLogIsTooSmall() { + DebugMessageRelay.setListener(null, 0L, true); + try (MemoryStack stack = MemoryStack.stackPush()) { + DebugMessageRelay.onSdlMessage(SDLLog.SDL_LOG_PRIORITY_ERROR, MemoryUtil.memAddress(stack.UTF8("a long message"))); + + assertEquals(0, DebugMessageRelay.drain(4, null, null, null, null, null, stack.malloc(4))); + } + } +} diff --git a/sdl-gpu/src/test/java/net/minecraft/launchwrapper/Launch.java b/sdl-gpu/src/test/java/net/minecraft/launchwrapper/Launch.java new file mode 100644 index 000000000..e73f2cf3b --- /dev/null +++ b/sdl-gpu/src/test/java/net/minecraft/launchwrapper/Launch.java @@ -0,0 +1,15 @@ +package net.minecraft.launchwrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * Stub for tests - provides blackboard without loading real launchwrapper. + */ +public class Launch { + public static Map blackboard = new HashMap<>(); + + static { + blackboard.put("lwjgl3ify:rfb-booted", Boolean.FALSE); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 8ad5aedbd..9c85ccdf8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -19,5 +19,9 @@ plugins { id("com.gtnewhorizons.gtnhsettingsconvention") version ("2.0.27") } +apply(from = file("gradle/lwjgl-natives.settings.gradle.kts")) + include("glsm") include("lwjgl3-backend") +include("tracy-client") +include("sdl-gpu") diff --git a/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java b/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java index c21c16701..1127226ed 100644 --- a/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java +++ b/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java @@ -1,5 +1,7 @@ package com.gtnewhorizons.angelica; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.proxy.CommonProxy; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; @@ -29,7 +31,8 @@ public class AngelicaMod { public static final String MOD_ID = "angelica"; public static final Logger LOGGER = LogManager.getLogger("Angelica"); - public static final boolean lwjglDebug = Boolean.getBoolean("org.lwjgl.util.Debug"); + public static final boolean lwjglDebug = SystemProperties.LWJGL_DEBUG; + public static final boolean tracyEnabled = Tracy.ENABLED; @SidedProxy( clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartBatch.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartBatch.java new file mode 100644 index 000000000..3382679d6 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartBatch.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import net.minecraft.client.model.ModelRenderer; + +/** For parts that override {@code ModelRenderer.render} */ +public final class ModelPartBatch { + + private ModelPartBatch() {} + + /** @return false if it cannot be batched */ + public static boolean partDraw(ModelRenderer part, float scale) { + return ModelPartBatcher.partDraw(part, scale, null); + } + + public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { + return ModelPartBatcher.partDraw(part, scale, builder); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartMeshBuilder.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartMeshBuilder.java new file mode 100644 index 000000000..5f7dc7559 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/ModelPartMeshBuilder.java @@ -0,0 +1,11 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.renderer.Tessellator; + +/** Geometry for a part that keeps it outside {@code cubeList} */ +@FunctionalInterface +public interface ModelPartMeshBuilder { + + void angelica$buildPart(Tessellator tess, ModelRenderer part, float scale); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java new file mode 100644 index 000000000..25f5cb989 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java @@ -0,0 +1,164 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.experimental.Accessors; + +import java.util.concurrent.ConcurrentHashMap; + +/** Per-bucket render attributes. Interned: equal settings build the same instance. */ +@Getter +@Accessors(fluent = true) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@EqualsAndHashCode +public final class TesrMaterial { + + public enum Transparency { OPAQUE, TRANSLUCENT, ADDITIVE, ADDITIVE_ALPHA, GLINT } + + public enum SpecialRender { NONE, BEACON_BEAM, GLINT } + + private static final ConcurrentHashMap INTERNED = new ConcurrentHashMap<>(); + + public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, Transparency.OPAQUE, SpecialRender.NONE, null)); + + private static TesrMaterial intern(TesrMaterial material) { + final TesrMaterial existing = INTERNED.putIfAbsent(material, material); + return existing == null ? material : existing; + } + + private final boolean hasColor; + private final float colorRed, colorGreen, colorBlue, colorAlpha; + private final boolean hasLightmap; + private final float lightmapX, lightmapY; + private final boolean isNoCull; + private final boolean isUnlit; + private final boolean isNoDepthWrite; + private final boolean isDepthOnly; + private final boolean isStream; + private final float cutoutAlpha; + private final boolean isDepthEqual; + private final Transparency transparency; + private final SpecialRender special; + private final TesrShader shader; + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private boolean hasColor; + private float red, green, blue, alpha; + private boolean hasLightmap; + private float lightmapX, lightmapY; + private boolean noCull; + private boolean unlit; + private boolean noDepthWrite; + private boolean depthOnly; + private boolean stream; + private float cutoutAlpha; + private boolean depthEqual; + private Transparency transparency = Transparency.OPAQUE; + private SpecialRender special = SpecialRender.NONE; + private TesrShader shader; + + public Builder color(float red, float green, float blue, float alpha) { + this.hasColor = true; + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + return this; + } + + public Builder lightmap(float x, float y) { + this.hasLightmap = true; + this.lightmapX = x; + this.lightmapY = y; + return this; + } + + public Builder noCull() { + this.noCull = true; + return this; + } + + /** Disables FFP lighting */ + public Builder unlit() { + this.unlit = true; + return this; + } + + public Builder noDepthWrite() { + this.noDepthWrite = true; + return this; + } + + /** Depth prepass: writes depth only, no color. Mutually exclusive with noDepthWrite */ + public Builder depthOnly() { + this.depthOnly = true; + return this; + } + + /** Changes every frame, not cached */ + public Builder stream() { + this.stream = true; + return this; + } + + /** Discards pixels with alpha at or below threshold - hard-edged cutout, no blending. ALPHA_TEST GREATER */ + public Builder cutout(float threshold) { + this.cutoutAlpha = threshold; + return this; + } + + /** Draws only where geometry already exists at the same depth; for decal/overlay passes. GL_EQUAL depth */ + public Builder depthEqual() { + this.depthEqual = true; + return this; + } + + /** Standard alpha blending (glass, liquids). SRC_ALPHA, ONE_MINUS_SRC_ALPHA */ + public Builder translucent() { + this.transparency = Transparency.TRANSLUCENT; + return this; + } + + /** Additive glow; alpha ignored. ONE, ONE */ + public Builder additive() { + this.transparency = Transparency.ADDITIVE; + return this; + } + + /** Additive glow scaled by alpha. SRC_ALPHA, ONE */ + public Builder additiveAlpha() { + this.transparency = Transparency.ADDITIVE_ALPHA; + return this; + } + + /** Vanilla enchantment glint blend. SRC_COLOR, ONE */ + public Builder glint() { + this.transparency = Transparency.GLINT; + return this; + } + + public Builder special(SpecialRender special) { + this.special = special; + return this; + } + + /** Custom shader around this material's batched draws; see {@link TesrShaders#register} */ + public Builder shader(TesrShader shader) { + this.shader = shader; + return this; + } + + public TesrMaterial build() { + if (special != SpecialRender.NONE && shader != null) { + throw new IllegalStateException("special() and shader() are mutually exclusive"); + } + return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, transparency, special, shader)); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshBuilder.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshBuilder.java new file mode 100644 index 000000000..284e97788 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshBuilder.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.api.tesr; + +/** Emits local-space geometry into the sink's buckets. Prefer implementing {@link TesrMeshProvider}. */ +@FunctionalInterface +public interface TesrMeshBuilder { + + void angelica$build(TesrMeshSink sink); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshCache.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshCache.java new file mode 100644 index 000000000..013c235c9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshCache.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; + +/** TESR mesh cache entry points. Render thread only. */ +public final class TesrMeshCache { + + private TesrMeshCache() {} + + public static void renderCached(Object key, TesrMeshBuilder builder) { + AngelicaTesrMeshCache.INSTANCE.renderCached(key, builder); + } + + /** Manual invalidate ande force rebuild on next render */ + public static void invalidate(Object key) { + AngelicaTesrMeshCache.INSTANCE.invalidate(key); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshProvider.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshProvider.java new file mode 100644 index 000000000..6aa8315c9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshProvider.java @@ -0,0 +1,29 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.minecraft.tileentity.TileEntity; + +/** + * Implemented by a TileEntitySpecialRenderer to opt into Angelica's mesh cache/batch + * + * Use a compile-only dependency and guard with {@code @Optional.Interface(iface = "com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider", modid = "angelica|tesr")} + * and mark {@link #angelica$build} {@code @Optional.Method(modid = "angelica|tesr")} + */ +public interface TesrMeshProvider { + + /** Stable identity key for the mesh variant, null falls back to the vanilla render path this frame */ + Object angelica$meshKey(TileEntity te); + + /** True if the cached mesh must be rebuilt */ + default boolean angelica$meshDirty(TileEntity te) { + return false; + } + + /** Per-instance transform, defaults to TE position */ + default void angelica$transform(TileEntity te, double x, double y, double z) { + GLStateManager.glTranslated(x, y, z); + } + + /** Build and cache the mesh */ + void angelica$build(TesrMeshSink sink, TileEntity te); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshSink.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshSink.java new file mode 100644 index 000000000..cb4f80483 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMeshSink.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; + +/** Capture-time sink. draw() captures instead of drawing */ +public interface TesrMeshSink { + + Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture, TesrMaterial material); + + default Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture) { + return angelica$bucket(format, texture, TesrMaterial.CURRENT_STATE); + } + + default Tessellator angelica$bucket(VertexFormat format) { + return angelica$bucket(format, null, TesrMaterial.CURRENT_STATE); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShader.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShader.java new file mode 100644 index 000000000..7f5117add --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShader.java @@ -0,0 +1,17 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.Accessors; + +/** A registered mod-owned GL program; see {@link TesrShaders#register} */ +@Getter +@Accessors(fluent = true) +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +public final class TesrShader { + + private final String name; + private final Runnable bind; + private final Runnable release; +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShaders.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShaders.java new file mode 100644 index 000000000..bfae672ed --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrShaders.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +public final class TesrShaders { + + private static final ConcurrentHashMap REGISTRY = new ConcurrentHashMap<>(); + + private TesrShaders() {} + + /** Registers a GL program under a unique name and returns its handle, wraps draws of any {@link TesrMaterial} referencing it */ + public static TesrShader register(String name, Runnable bind, Runnable release) { + final int colon = name.indexOf(':'); + if (colon <= 0 || colon == name.length() - 1 || name.indexOf(':', colon + 1) >= 0) { + throw new IllegalArgumentException("TESR shader name must be namespace:path, got '" + name + "'"); + } + Objects.requireNonNull(bind, "bind"); + Objects.requireNonNull(release, "release"); + final TesrShader shader = new TesrShader(name, bind, release); + if (REGISTRY.putIfAbsent(name, shader) != null) { + throw new IllegalStateException("TESR shader '" + name + "' already registered"); + } + return shader; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java new file mode 100644 index 000000000..3c2f73c0a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java @@ -0,0 +1,5 @@ +/** TESR mesh cache/batch API (Render thread only) */ +@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "1") +package com.gtnewhorizons.angelica.api.tesr; + +import cpw.mods.fml.common.API; diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java index db54b933f..0ffddc2cb 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -12,9 +12,14 @@ import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PA import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.FontConfig; import com.gtnewhorizons.angelica.hudcaching.HUDCaching; +import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.Setter; import net.coderbot.iris.gl.program.Program; @@ -32,6 +37,7 @@ import org.lwjgl.opengl.GL20; import java.nio.ByteBuffer; import java.nio.FloatBuffer; +import java.util.Arrays; import java.util.Comparator; import java.util.Objects; @@ -133,10 +139,18 @@ public class BatchingFontRenderer { private static int vbo; private static IndexBuffer ebo; + private static final int RING_CAPACITY = 2 * 1024 * 1024; + private static PersistentStreamingBuffer streamRing; + private static boolean streamingInitialized; + private static int pendingBuffer; + private static int pendingBase; + private static int vaoBuffer = -1; + private static int vaoBase = -1; + private int batchDepth = 0; - private int vertexDataPos = 0; - private int idxWriterIndex = 0; + private static int vertexDataPos = 0; + private static int idxWriterIndex = 0; private final ObjectArrayList batchCommands = ObjectArrayList.wrap(new FontDrawCmd[64], 0); private final ObjectArrayList batchCommandPool = ObjectArrayList.wrap(new FontDrawCmd[64], 0); @@ -144,6 +158,24 @@ public class BatchingFontRenderer { private int blendSrcRGB = GL11.GL_SRC_ALPHA; private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA; + private static final class DeferredTextSegment { + final Matrix4f mvp = new Matrix4f(); + BatchingFontRenderer owner; + int cmdStart; + int cmdEnd; + } + + // 16-bit EBO index range + private static final int QUAD_BUDGET = 65536 / 4; + + private static int deferredVertexPos; + private static int deferredIdxPos; + + private int deferredCmdWatermark; + private static final ObjectArrayList deferredSegments = ObjectArrayList.wrap(new DeferredTextSegment[16], 0); + private static final ObjectArrayList deferredSegmentPool = ObjectArrayList.wrap(new DeferredTextSegment[16], 0); + private boolean deferCurrentBatch; + private void allocateBuffers() { populateEBO(rawCapacity / VERTEX_SIZE); @@ -174,6 +206,36 @@ public class BatchingFontRenderer { } + private static void initStreaming() { + if (streamingInitialized) return; + streamingInitialized = true; + streamRing = PersistentStreamingBuffer.createOrNull(RING_CAPACITY); + } + + public static void endFrame() { + if (streamRing != null) { + streamRing.postDraw(); + } + } + + private static void uploadVertexData(int limitPos) { + initStreaming(); + vertexData.position(0); + vertexData.limit(limitPos); + if (streamRing != null) { + final int firstVertex = streamRing.upload(vertexData, VERTEX_SIZE); + if (firstVertex >= 0) { + pendingBuffer = streamRing.getBufferId(); + pendingBase = firstVertex * VERTEX_SIZE; + return; + } + } + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + vboCapacity = StreamingUploader.upload(vertexData, vboCapacity); + pendingBuffer = vbo; + pendingBase = 0; + } + private void ensureCapacity() { if (vertexDataPos + (4 * VERTEX_SIZE) > rawCapacity) { rawCapacity *= 2; @@ -236,7 +298,8 @@ public class BatchingFontRenderer { } private void pushDrawCmd(int startIdx, int idxCount, ResourceLocation texture, boolean isUnicode) { - if (!batchCommands.isEmpty()) { + // Never coalesce into a command below the watermark - it belongs to a sealed deferred segment. + if (batchCommands.size() > deferredCmdWatermark) { final FontDrawCmd lastCmd = batchCommands.get(batchCommands.size() - 1); final int prevEndVtx = lastCmd.startVtx + lastCmd.idxCount; if (prevEndVtx == startIdx && lastCmd.texture == texture) { @@ -322,6 +385,101 @@ public class BatchingFontRenderer { } } + public void beginDeferredBatch() { + deferCurrentBatch = batchDepth == 0 && TesrBatchRenderer.INSTANCE.hasActivePass() || ModelPartBatcher.INSTANCE.isActive(); + if (deferCurrentBatch && deferredIdxPos / 6 > QUAD_BUDGET / 2) { + flushDeferredText(); + } + beginBatch(); + } + + public void endDeferredBatch() { + if (deferCurrentBatch && batchDepth == 1) { + deferCurrentBatch = false; + batchDepth = 0; + deferBatch(); + } else { + endBatch(); + } + } + + private void deferBatch() { + if (batchCommands.size() == deferredCmdWatermark || vertexDataPos == deferredVertexPos) { + truncateBatchToWatermark(); + return; + } + if (idxWriterIndex / 6 > QUAD_BUDGET) { + flushBatch(); + return; + } + final DeferredTextSegment segment = deferredSegmentPool.isEmpty() ? new DeferredTextSegment() : deferredSegmentPool.pop(); + segment.owner = this; + segment.cmdStart = deferredCmdWatermark; + segment.cmdEnd = batchCommands.size(); + GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), segment.mvp); + deferredSegments.add(segment); + deferredCmdWatermark = batchCommands.size(); + deferredVertexPos = vertexDataPos; + deferredIdxPos = idxWriterIndex; + } + + public static void flushDeferredText() { + if (deferredSegments.isEmpty()) return; + + uploadVertexData(deferredVertexPos); + + final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); + final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D); + final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND); + final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + + final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled(); + final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled(); + + deferredSegments.get(0).owner.setupFontDrawState(); + GLStateManager.glDepthMask(false); + flushLastTexture = DUMMY_RESOURCE_LOCATION; + flushTextureChanged = false; + try (MemoryStack stack = stackPush()) { + final FloatBuffer mvpBuf = stack.mallocFloat(16); + for (int i = 0, n = deferredSegments.size(); i < n; i++) { + final DeferredTextSegment segment = deferredSegments.get(i); + mvpBuf.clear(); + segment.mvp.get(mvpBuf); + GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf); + drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner); + } + } + restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore); + restoreDepth(depthTestBefore, depthMaskBefore); + + discardDeferredText(); + } + + public static void discardDeferredText() { + if (deferredSegments.isEmpty()) return; + for (int i = 0, n = deferredSegments.size(); i < n; i++) { + final DeferredTextSegment segment = deferredSegments.get(i); + segment.owner.clearDeferredCommands(); + segment.owner = null; + } + deferredSegmentPool.addAll(deferredSegments); + deferredSegments.clear(); + deferredVertexPos = 0; + deferredIdxPos = 0; + vertexDataPos = 0; + idxWriterIndex = 0; + } + + private void clearDeferredCommands() { + if (deferredCmdWatermark == 0) return; + for (int i = 0; i < deferredCmdWatermark; i++) { + batchCommandPool.add(batchCommands.get(i)); + } + batchCommands.removeElements(0, deferredCmdWatermark); + deferredCmdWatermark = 0; + } + private static final Matrix4f scratchMvp = new Matrix4f(); private int fontAAModeLast = -1; private int fontAAStrengthLast = -1; @@ -336,27 +494,42 @@ public class BatchingFontRenderer { } private void flushBatchInner() { - if (vertexDataPos == 0) { - clearBatch(); + final int cmdCount = batchCommands.size(); + if (vertexDataPos == deferredVertexPos || cmdCount == deferredCmdWatermark) { + truncateBatchToWatermark(); return; } - // Upload first (to reduce stalls) - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); - vertexData.limit(vertexDataPos); - vboCapacity = StreamingUploader.upload(vertexData, vboCapacity); + uploadVertexData(vertexDataPos); final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); - // Sort&Draw - batchCommands.sort(FontDrawCmd.DRAW_ORDER_COMPARATOR); + Arrays.sort(batchCommands.elements(), deferredCmdWatermark, cmdCount, FontDrawCmd.DRAW_ORDER_COMPARATOR); final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D); final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND); final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); - boolean textureChanged = false; + final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled(); + final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled(); - ResourceLocation lastTexture = DUMMY_RESOURCE_LOCATION; + setupFontDrawState(); + try (MemoryStack stack = stackPush()) { + final FloatBuffer mvpBuf = stack.mallocFloat(16); + GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), scratchMvp); + scratchMvp.get(mvpBuf); + GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf); + } + + flushLastTexture = DUMMY_RESOURCE_LOCATION; + flushTextureChanged = false; + drawCommands(batchCommands.elements(), deferredCmdWatermark, cmdCount, this); + restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore); + restoreDepth(depthTestBefore, depthMaskBefore); + + truncateBatchToWatermark(); + } + + private void setupFontDrawState() { GLStateManager.enableTexture(); GLStateManager.enableAlphaTest(); GLStateManager.enableBlend(); @@ -373,85 +546,88 @@ public class BatchingFontRenderer { GLStateManager.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f); } GLStateManager.glUniform1f(alphaTestRefLocation, GLStateManager.getAlphaState().getReference()); - try (MemoryStack stack = stackPush()) { - final FloatBuffer mvpBuf = stack.mallocFloat(16); - GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), scratchMvp); - scratchMvp.get(mvpBuf); - GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf); - } if (fontVAO == 0) { fontVAO = GLStateManager.glGenVertexArrays(); GLStateManager.glBindVertexArray(fontVAO); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); - ebo.bind(); - - // position - GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 0); GLStateManager.glEnableVertexAttribArray(0); - - // texcoords - GLStateManager.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 8); GLStateManager.glEnableVertexAttribArray(1); - - // color - GLStateManager.glVertexAttribPointer(2, 4, GL11.GL_UNSIGNED_BYTE, true, VERTEX_SIZE, 16); GLStateManager.glEnableVertexAttribArray(2); - - // tex bounds - GLStateManager.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, VERTEX_SIZE, 20); GLStateManager.glEnableVertexAttribArray(3); + } else { + GLStateManager.glBindVertexArray(fontVAO); } - GLStateManager.glBindVertexArray(fontVAO); + if (vaoBuffer != pendingBuffer || vaoBase != pendingBase) { + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, pendingBuffer); - // Use plain for loop to avoid allocations - final FontDrawCmd[] cmdsData = batchCommands.elements(); - final int cmdsSize = batchCommands.size(); - for (int i = 0; i < cmdsSize; i++) { + GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase); + GLStateManager.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase + 8); + GLStateManager.glVertexAttribPointer(2, 4, GL11.GL_UNSIGNED_BYTE, true, VERTEX_SIZE, pendingBase + 16); + GLStateManager.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase + 20); + + vaoBuffer = pendingBuffer; + vaoBase = pendingBase; + } + } + + private static ResourceLocation flushLastTexture; + private static boolean flushTextureChanged; + + private static void drawCommands(FontDrawCmd[] cmdsData, int from, int to, BatchingFontRenderer owner) { + for (int i = from; i < to; i++) { final FontDrawCmd cmd = cmdsData[i]; - if (!Objects.equals(lastTexture, cmd.texture)) { - if (lastTexture == null) { + if (!Objects.equals(flushLastTexture, cmd.texture)) { + if (flushLastTexture == null) { GLStateManager.glEnable(GL11.GL_TEXTURE_2D); } else if (cmd.texture == null) { GLStateManager.glDisable(GL11.GL_TEXTURE_2D); } if (cmd.texture != null) { - ((FontRendererAccessor) underlying).angelica$bindTexture(cmd.texture); - textureChanged = true; + ((FontRendererAccessor) owner.underlying).angelica$bindTexture(cmd.texture); + flushTextureChanged = true; } - lastTexture = cmd.texture; + flushLastTexture = cmd.texture; } GLStateManager.glDrawElements(GL11.GL_TRIANGLES, cmd.idxCount, GL11.GL_UNSIGNED_SHORT, (long) cmd.startVtx * 2L); } + } - + private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore) { GLStateManager.glUseProgram(prevProgram); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLStateManager.glBindVertexArray(0); - if (isTextureEnabledBefore) { - GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + if (textureEnabledBefore) { + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); } - if (!isBlendEnabledBefore) { + if (!blendEnabledBefore) { GLStateManager.disableBlend(); } - if (textureChanged) { - GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore); + if (flushTextureChanged) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore); } - - clearBatch(); } - private void clearBatch() { - // Clear for the next batch - batchCommandPool.addAll(batchCommands); - batchCommands.clear(); - vertexDataPos = 0; - idxWriterIndex = 0; + private static void restoreDepth(boolean testBefore, boolean maskBefore) { + if (testBefore != GLStateManager.getDepthTest().isEnabled()) { + if (testBefore) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest(); + } + if (maskBefore != GLStateManager.getDepthState().isEnabled()) { + GLStateManager.glDepthMask(maskBefore); + } + } + + private void truncateBatchToWatermark() { + for (int i = batchCommands.size() - 1; i >= deferredCmdWatermark; i--) { + batchCommandPool.add(batchCommands.get(i)); + } + batchCommands.size(deferredCmdWatermark); + vertexDataPos = deferredVertexPos; + idxWriterIndex = deferredIdxPos; } // === Actual text mesh generation diff --git a/src/main/java/com/gtnewhorizons/angelica/commands/AngelicaCommand.java b/src/main/java/com/gtnewhorizons/angelica/commands/AngelicaCommand.java index e2850349b..c33402b7c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/commands/AngelicaCommand.java +++ b/src/main/java/com/gtnewhorizons/angelica/commands/AngelicaCommand.java @@ -3,6 +3,8 @@ package com.gtnewhorizons.angelica.commands; // Debug commands adapted from Beddium by Ven and FalsePattern import com.gtnewhorizons.angelica.debug.ChunkDebugMinimap; +import com.gtnewhorizons.angelica.debug.flyby.FlybyRoute; +import com.gtnewhorizons.angelica.debug.flyby.FlybyRunner; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; import net.minecraft.command.CommandBase; @@ -17,7 +19,7 @@ import java.util.List; public class AngelicaCommand extends CommandBase { - private static final List SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "help"); + private static final List SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "flyby", "help"); @Override public String getCommandName() { @@ -26,12 +28,12 @@ public class AngelicaCommand extends CommandBase { @Override public String getCommandUsage(ICommandSender sender) { - return "/angelica "; + return "/angelica "; } @Override public int getRequiredPermissionLevel() { - return 0; // Available to all players (client-side only) + return 2; // op } @Override @@ -39,6 +41,14 @@ public class AngelicaCommand extends CommandBase { if (args.length == 1) { return getListOfStringsMatchingLastWord(args, SUBCOMMANDS.toArray(new String[0])); } + if (args.length == 2 && "flyby".equalsIgnoreCase(args[0])) { + final List options = new ArrayList<>(); + for (FlybyRoute route : FlybyRoute.values()) { + options.add(route.id()); + } + options.add("cancel"); + return getListOfStringsMatchingLastWord(args, options.toArray(new String[0])); + } return new ArrayList<>(); } @@ -53,6 +63,7 @@ public class AngelicaCommand extends CommandBase { case "wireframe" -> handleWireframe(sender); case "fog" -> handleFog(sender); case "minimap" -> handleMinimap(sender); + case "flyby" -> handleFlyby(sender, args); default -> sendHelp(sender); } } @@ -77,11 +88,62 @@ public class AngelicaCommand extends CommandBase { sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Chunk debug minimap: " + state)); } + private void handleFlyby(ICommandSender sender, String[] args) { + if (args.length >= 2 && "cancel".equalsIgnoreCase(args[1])) { + FlybyRunner.INSTANCE.cancel(); + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Flyby cancelled")); + return; + } + + if (args.length < 2) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Usage: /angelica flyby <" + FlybyRoute.ids() + "|cancel> [length] [blocksPerTick]")); + for (FlybyRoute r : FlybyRoute.values()) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " " + r.id() + " - default " + r.defaultLength() + " " + r.lengthUnit())); + } + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " current: " + FlybyRunner.INSTANCE.describe())); + return; + } + + final FlybyRoute route = FlybyRoute.byId(args[1]); + if (route == null) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Unknown route '" + args[1] + "', expected one of " + FlybyRoute.ids())); + return; + } + + int length = 0; + if (args.length >= 3) { + try { + length = Integer.parseInt(args[2]); + } catch (NumberFormatException e) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Not a length: " + args[2])); + return; + } + } + + double speed = 0.0D; + if (args.length >= 4) { + try { + speed = Double.parseDouble(args[3]); + } catch (NumberFormatException e) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Not a speed: " + args[3])); + return; + } + } + + FlybyRunner.INSTANCE.start(route, length, 0, speed); + final int used = length > 0 ? length : route.defaultLength(); + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + + "Flyby started: " + route.id() + " for " + used + " " + route.lengthUnit() + + " at " + route.speedOr(speed) + " b/t" + + " (" + route.toTicks(used, speed) + " ticks)")); + } + private void sendHelp(ICommandSender sender) { sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] Debug Commands:")); sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica wireframe" + EnumChatFormatting.WHITE + " - Toggle wireframe rendering")); sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica fog" + EnumChatFormatting.WHITE + " - Toggle fog debug on F3")); sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica minimap" + EnumChatFormatting.WHITE + " - Toggle chunk debug overlay")); + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica flyby <" + FlybyRoute.ids() + ">" + EnumChatFormatting.WHITE + " - Run a deterministic benchmark route")); } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/DriverCompatabilityCheck.java b/src/main/java/com/gtnewhorizons/angelica/compat/DriverCompatabilityCheck.java index b88cb80e7..2d3ebf373 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/DriverCompatabilityCheck.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/DriverCompatabilityCheck.java @@ -5,6 +5,7 @@ import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.ARBDebugOutput; import org.lwjgl.opengl.GL11; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.GLStateManager; /** @@ -15,8 +16,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; public class DriverCompatabilityCheck { private static final Logger LOGGER = LogManager.getLogger("Angelica"); - private static final boolean DISABLE_NVIDIA_WORKAROUND = Boolean.getBoolean("angelica.disableNvidiaWorkaround"); - /** * Should be called after GL context is created and GLStateManager is initialized. */ @@ -30,7 +29,7 @@ public class DriverCompatabilityCheck { LOGGER.info("OpenGL Version: {}", version); if (vendor != null && vendor.contains("NVIDIA")) { - if (DISABLE_NVIDIA_WORKAROUND) { + if (SystemProperties.DISABLE_NVIDIA_WORKAROUND) { LOGGER.info("NVIDIA workaround disabled via -Dangelica.disableNvidiaWorkaround=true"); } else { applyNvidiaWorkaround(); diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlend.java b/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlend.java new file mode 100644 index 000000000..7a081b166 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlend.java @@ -0,0 +1,126 @@ +package com.gtnewhorizons.angelica.compat.bop; + +public final class BopFogBlend { + + public static final int NO_FOG = -1; + + @FunctionalInterface + public interface ColorSource { + /** Packed 0xRRGGBB, or {@link #NO_FOG}. */ + int fogColour(int x, int y, int z); + } + + private static Object cachedWorld; + private static int cachedGeneration; + private static int cachedX, cachedY, cachedZ, cachedDistance; + private static float interiorR, interiorG, interiorB, interiorWeight; + + private BopFogBlend() {} + + public static void invalidate() { + cachedWorld = null; + } + + public static void accumulate(Object world, int generation, ColorSource source, double posX, double posZ, + int playerX, int playerY, int playerZ, int distance, float[] out) { + + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + + final double xDiffLow = 1 - (posX - playerX); + final double xDiffHigh = posX - playerX; + final double zDiffLow = 1 - (posZ - playerZ); + final double zDiffHigh = posZ - playerZ; + + if (distance <= 0) { + cell(source, 0, 0, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out); + return; + } + + if (world != cachedWorld || generation != cachedGeneration || playerX != cachedX || playerY != cachedY + || playerZ != cachedZ || distance != cachedDistance) { + recomputeInterior(source, playerX, playerY, playerZ, distance); + cachedWorld = world; + cachedGeneration = generation; + cachedX = playerX; + cachedY = playerY; + cachedZ = playerZ; + cachedDistance = distance; + } + + out[0] = interiorR; + out[1] = interiorG; + out[2] = interiorB; + out[3] = interiorWeight; + + for (int z = -distance; z <= distance; ++z) { + cell(source, -distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out); + cell(source, distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out); + } + for (int x = -distance + 1; x <= distance - 1; ++x) { + cell(source, x, -distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out); + cell(source, x, distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out); + } + } + + private static void recomputeInterior(ColorSource source, int playerX, int playerY, int playerZ, int distance) { + float r = 0, g = 0, b = 0, weight = 0; + for (int x = -distance + 1; x <= distance - 1; ++x) { + for (int z = -distance + 1; z <= distance - 1; ++z) { + final int colour = source.fogColour(playerX + x, playerY, playerZ + z); + if (colour == NO_FOG) continue; + r += (colour & 0xFF0000) >> 16; + g += (colour & 0x00FF00) >> 8; + b += colour & 0x0000FF; + weight += 1; + } + } + interiorR = r; + interiorG = g; + interiorB = b; + interiorWeight = weight; + } + + private static void cell(ColorSource source, int x, int z, double xDiffLow, double xDiffHigh, double zDiffLow, + double zDiffHigh, int playerX, int playerY, int playerZ, int distance, float[] out) { + + final int colour = source.fogColour(playerX + x, playerY, playerZ + z); + if (colour == NO_FOG) return; + + float rPart = (colour & 0xFF0000) >> 16; + float gPart = (colour & 0x00FF00) >> 8; + float bPart = colour & 0x0000FF; + float weightPart = 1; + + if (x == -distance) { + rPart *= xDiffLow; + gPart *= xDiffLow; + bPart *= xDiffLow; + weightPart *= xDiffLow; + } else if (x == distance) { + rPart *= xDiffHigh; + gPart *= xDiffHigh; + bPart *= xDiffHigh; + weightPart *= xDiffHigh; + } + + if (z == -distance) { + rPart *= zDiffLow; + gPart *= zDiffLow; + bPart *= zDiffLow; + weightPart *= zDiffLow; + } else if (z == distance) { + rPart *= zDiffHigh; + gPart *= zDiffHigh; + bPart *= zDiffHigh; + weightPart *= zDiffHigh; + } + + out[0] += rPart; + out[1] += gPart; + out[2] += bPart; + out[3] += weightPart; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogColorSource.java b/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogColorSource.java new file mode 100644 index 000000000..fdedce937 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/bop/BopFogColorSource.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.compat.bop; + +import biomesoplenty.client.fog.IBiomeFog; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public final class BopFogColorSource implements BopFogBlend.ColorSource { + + public static final BopFogColorSource INSTANCE = new BopFogColorSource(); + + private World world; + + private BopFogColorSource() {} + + public BopFogColorSource forWorld(World world) { + this.world = world; + return this; + } + + @Override + public int fogColour(int x, int y, int z) { + final BiomeGenBase biome = FogBiomeCache.get(world, x, z); + if (!(biome instanceof IBiomeFog fog)) return BopFogBlend.NO_FOG; + return fog.getFogColour(x, y, z) & 0xFFFFFF; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCache.java b/src/main/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCache.java new file mode 100644 index 000000000..7afa61f50 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCache.java @@ -0,0 +1,39 @@ +package com.gtnewhorizons.angelica.compat.bop; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public final class FogBiomeCache { + + private static final int MAX_ENTRIES = 16384; + + private static final Long2ObjectOpenHashMap CACHE = new Long2ObjectOpenHashMap<>(); + private static World lastWorld; + private static int generation; + + private FogBiomeCache() {} + + public static int generation() { + return generation; + } + + public static BiomeGenBase get(World world, int x, int z) { + if (world != lastWorld) { + CACHE.clear(); + lastWorld = world; + generation++; + } + final long key = ((long) x << 32) | (z & 0xFFFFFFFFL); + BiomeGenBase biome = CACHE.get(key); + if (biome == null) { + biome = world.getBiomeGenForCoords(x, z); + if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { + if (CACHE.size() >= MAX_ENTRIES) CACHE.clear(); + CACHE.put(key, biome); + generation++; + } + } + return biome; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderLayer.java b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java similarity index 70% rename from src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderLayer.java rename to src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java index d78a19070..414d1850b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderLayer.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java @@ -1,16 +1,25 @@ -package com.gtnewhorizons.angelica.compat.toremove; +package com.gtnewhorizons.angelica.compat.mojang; import com.google.common.collect.ImmutableList; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrShader; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; import lombok.Getter; +import net.coderbot.batchedentityrendering.impl.BatchVertexFormats; +import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; +import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; +import net.coderbot.iris.layer.GbufferPrograms; import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; import javax.annotation.Nullable; +import java.util.Locale; import java.util.Objects; import java.util.Optional; @@ -59,6 +68,72 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return TRANSLUCENT; } + private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material) { + final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder(); + if (texture != null) { + b.texture(new RenderPhase.Texture(texture, false, false)); + } + if (material.isNoCull()) { + b.cull(DISABLE_CULLING); + } + if (material.isUnlit()) { + b.texturing(NO_FFP_LIGHTING); + } + if (material.isNoDepthWrite()) { + b.writeMaskState(COLOR_MASK); + } + if (material.isDepthOnly()) { + b.writeMaskState(DEPTH_MASK); + } + if (material.cutoutAlpha() > 0) { + b.alpha(new RenderPhase.Alpha(material.cutoutAlpha())); + } + if (material.isDepthEqual()) { + b.depthTest(EQUAL_DEPTH_TEST); + } + switch (material.transparency()) { + case TRANSLUCENT -> b.transparency(TRANSLUCENT_TRANSPARENCY); + case ADDITIVE -> b.transparency(ADDITIVE_TRANSPARENCY); + case ADDITIVE_ALPHA -> b.transparency(LIGHTNING_TRANSPARENCY); + case GLINT -> b.transparency(GLINT_TRANSPARENCY); + case OPAQUE -> {} + } + switch (material.special()) { + case GLINT -> b.shader(SPECIAL_GLINT); + case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM); + case NONE -> { + final TesrShader shader = material.shader(); + if (shader != null) { + b.shader(new RenderPhase.Shader("angelica_tesr_shader_" + shader.name(), shader.bind(), shader.release())); + } + } + } + return b; + } + + private static final RenderPhase.Shader SPECIAL_GLINT = new RenderPhase.Shader("angelica_special_glint", + () -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT), + GbufferPrograms::teardownSpecialRenderCondition); + private static final RenderPhase.Shader SPECIAL_BEACON_BEAM = new RenderPhase.Shader("angelica_special_beacon_beam", + () -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM), + GbufferPrograms::teardownSpecialRenderCondition); + + public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) { + final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material).shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP); + if (material.transparency() == TesrMaterial.Transparency.TRANSLUCENT) { + b.target(TRANSLUCENT_TARGET); + } + final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE; + return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT), + BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, sortsTranslucent, b.build(false)); + } + + public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) { + return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT), + BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false, + tesrMaterialPhases(texture, material).build(false)); + } + public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) { return of("outline", DefaultVertexFormat.POSITION_COLOR_TEXTURE, 7, 256, RenderLayer.MultiPhaseParameters.builder().texture(new RenderPhase.Texture(texture, false, false)).cull(cull).depthTest(ALWAYS_DEPTH_TEST).alpha(ONE_TENTH_ALPHA).fog(NO_FOG).target(OUTLINE_TARGET).build(RenderLayer.OutlineMode.IS_OUTLINE)); } @@ -67,17 +142,32 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return this.drawMode; } - static final class MultiPhase extends RenderLayer { + public ResourceLocation getTextureId() { + return null; + } + + static final class MultiPhase extends RenderLayer implements BlendingStateHolder { private static final ObjectOpenCustomHashSet CACHE; private final MultiPhaseParameters phases; private final int hash; private final Optional affectedOutline; + @Override + public TransparencyType getTransparencyType() { + return phases.transparency.getTransparencyType(); + } + private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) { super(name, vertexFormat, drawMode, expectedBufferSize, () -> { - phases.phases.forEach(RenderPhase::startDrawing); + final ImmutableList p = phases.phases; + for (int i = 0, n = p.size(); i < n; i++) { + p.get(i).startDrawing(); + } }, () -> { - phases.phases.forEach(RenderPhase::endDrawing); + final ImmutableList p = phases.phases; + for (int i = 0, n = p.size(); i < n; i++) { + p.get(i).endDrawing(); + } }); this.phases = phases; this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE ? phases.texture.getId().map((arg2) -> { @@ -95,6 +185,11 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return this.affectedOutline; } + @Override + public ResourceLocation getTextureId() { + return phases.texture.getId().orElse(null); + } + @Override public boolean equals(@Nullable Object object) { return this == object; @@ -148,10 +243,11 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris private final RenderPhase.Target target; private final RenderPhase.Texturing texturing; private final RenderPhase.WriteMaskState writeMaskState; + private final RenderPhase.Shader shader; private final OutlineMode outlineMode; private final ImmutableList phases; - private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, OutlineMode outlineMode) { + private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, RenderPhase.Shader shader, OutlineMode outlineMode) { this.texture = texture; this.transparency = transparency; this.diffuseLighting = diffuseLighting; @@ -165,8 +261,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris this.target = target; this.texturing = texturing; this.writeMaskState = writeMaskState; + this.shader = shader; this.outlineMode = outlineMode; - this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState); + this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader); } @Override @@ -209,6 +306,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris private RenderPhase.Target target; private RenderPhase.Texturing texturing; private RenderPhase.WriteMaskState writeMaskState; + private RenderPhase.Shader shader; private Builder() { this.texture = RenderPhase.NO_TEXTURE ; @@ -224,6 +322,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris this.target = RenderPhase.MAIN_TARGET; this.texturing = RenderPhase.DEFAULT_TEXTURING; this.writeMaskState = RenderPhase.ALL_MASK; + this.shader = RenderPhase.NO_SHADER; } public Builder texture(RenderPhase.Texture texture) { @@ -276,12 +375,22 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return this; } + public Builder writeMaskState(RenderPhase.WriteMaskState writeMaskState) { + this.writeMaskState = writeMaskState; + return this; + } + + public Builder shader(RenderPhase.Shader shader) { + this.shader = shader; + return this; + } + public MultiPhaseParameters build(boolean affectsOutline) { return this.build(affectsOutline ? RenderLayer.OutlineMode.AFFECTS_OUTLINE : RenderLayer.OutlineMode.NONE); } public MultiPhaseParameters build(OutlineMode outlineMode) { - return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, outlineMode); + return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader, outlineMode); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderPhase.java b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java similarity index 90% rename from src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderPhase.java rename to src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java index 110116104..738a8bcd3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/toremove/RenderPhase.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java @@ -1,7 +1,7 @@ -package com.gtnewhorizons.angelica.compat.toremove; +package com.gtnewhorizons.angelica.compat.mojang; -import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; @@ -17,7 +17,7 @@ public abstract class RenderPhase { protected final String name; protected Runnable beginAction; private final Runnable endAction; - protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", GLStateManager::disableBlend, () -> { + protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", TransparencyType.OPAQUE, GLStateManager::disableBlend, () -> { }); protected static final Transparency ADDITIVE_TRANSPARENCY = new Transparency("additive_transparency", () -> { GLStateManager.enableBlend(); @@ -33,14 +33,14 @@ public abstract class RenderPhase { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); - protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", () -> { + protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", TransparencyType.DECAL, () -> { GLStateManager.enableBlend(); GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); - protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", () -> { + protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", TransparencyType.DECAL, () -> { GLStateManager.enableBlend(); GLStateManager.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO); }, () -> { @@ -63,6 +63,7 @@ public abstract class RenderPhase { protected static final Texture BLOCK_ATLAS_TEXTURE; protected static final Texture NO_TEXTURE; protected static final Texturing DEFAULT_TEXTURING; + protected static final Texturing NO_FFP_LIGHTING; protected static final Lightmap ENABLE_LIGHTMAP; protected static final Lightmap DISABLE_LIGHTMAP; protected static final DiffuseLighting ENABLE_DIFFUSE_LIGHTING; @@ -82,6 +83,7 @@ public abstract class RenderPhase { protected static final Target MAIN_TARGET; protected static final Target OUTLINE_TARGET; protected static final Target TRANSLUCENT_TARGET; + protected static final Shader NO_SHADER = new Shader("no_shader", () -> {}, () -> {}); public RenderPhase(String name, Runnable beginAction, Runnable endAction) { this.name = name; @@ -128,6 +130,7 @@ public abstract class RenderPhase { DEFAULT_TEXTURING = new Texturing("default_texturing", () -> { }, () -> { }); + NO_FFP_LIGHTING = new Texturing("no_ffp_lighting", GLStateManager::disableLighting, GLStateManager::enableLighting); ENABLE_LIGHTMAP = new Lightmap(true); DISABLE_LIGHTMAP = new Lightmap(false); ENABLE_DIFFUSE_LIGHTING = new DiffuseLighting(true); @@ -144,35 +147,23 @@ public abstract class RenderPhase { NO_FOG = new Fog("no_fog", () -> { }, () -> { }); - FOG = new Fog("fog", () -> { - // Unclear what this should do - // BackgroundRenderer.setFogBlack(), also levelFogColor() - AngelicaMod.LOGGER.debug("Fog - Not setting level fog color"); - GLStateManager.enableFog(); - }, GLStateManager::disableFog); + FOG = new Fog("fog", GLStateManager::enableFog, GLStateManager::disableFog); BLACK_FOG = new Fog("black_fog", () -> { GLStateManager.fogColor(0.0F, 0.0F, 0.0F, 1.0F); GLStateManager.enableFog(); - }, () -> { - // Unclear what this should do - // BackgroundRenderer.setFogBlack(), also levelFogColor() - AngelicaMod.LOGGER.debug("Fog - Not setting level fog color"); - GLStateManager.disableFog(); - }); + }, GLStateManager::disableFog); MAIN_TARGET = new Target("main_target", () -> { }, () -> { }); OUTLINE_TARGET = new Target("outline_target", () -> { - // TODO: Sodium - AngelicaMod.LOGGER.debug("NOT enabling the entity outline framebuffer"); + // TODO: Sodium - entity outline framebuffer //MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false); }, () -> { Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); }); TRANSLUCENT_TARGET = new Target("translucent_target", () -> { if (Minecraft.isFancyGraphicsEnabled()) { - // TODO: Sodium - AngelicaMod.LOGGER.debug("NOT enabling the translucent framebuffer"); + // TODO: Sodium - translucent framebuffer // MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false); } @@ -342,24 +333,7 @@ public abstract class RenderPhase { public static class Lightmap extends Toggleable { public Lightmap(boolean lightmap) { - super("lightmap", () -> { - if (lightmap) { - // TODO: Sodium - LightmapTextureManager - AngelicaMod.LOGGER.debug("Lightmap - enable (not implemented)"); -// throw new RuntimeException("Not Implemented Yet"); -// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable(); - - } - - }, () -> { - if (lightmap) { - // TODO: Sodium - LightmapTextureManager - AngelicaMod.LOGGER.debug("Lightmap - disable (not implemented)"); -// throw new RuntimeException("Not Implemented Yet"); -// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable(); - } - - }, lightmap); + super("lightmap", () -> {}, () -> {}, lightmap); } } @@ -396,6 +370,12 @@ public abstract class RenderPhase { } + public static class Shader extends RenderPhase { + public Shader(String name, Runnable bind, Runnable release) { + super(name, bind, release); + } + } + public static class Texturing extends RenderPhase { public Texturing(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); @@ -538,8 +518,19 @@ public abstract class RenderPhase { public static class Transparency extends RenderPhase { + private final TransparencyType transparencyType; + public Transparency(String string, Runnable runnable, Runnable runnable2) { + this(string, TransparencyType.GENERAL_TRANSPARENT, runnable, runnable2); + } + + public Transparency(String string, TransparencyType transparencyType, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); + this.transparencyType = transparencyType; + } + + public TransparencyType getTransparencyType() { + return transparencyType; } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/Tc4JarMeshes.java b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/Tc4JarMeshes.java new file mode 100644 index 000000000..94db9ce1e --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/Tc4JarMeshes.java @@ -0,0 +1,197 @@ +package com.gtnewhorizons.angelica.compat.thaumcraft; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL13; +import thaumcraft.api.aspects.Aspect; +import thaumcraft.common.blocks.BlockJar; +import thaumcraft.common.config.ConfigBlocks; +import thaumcraft.common.tiles.TileJarFillable; + +import java.util.HashMap; +import java.util.Map; + +public final class Tc4JarMeshes { + + private static final double MIN_X = 0.25, MIN_Y = 0.0625, MIN_Z = 0.25, MAX_X = 0.75, MAX_Z = 0.75; + private static final double OFF_X = -0.5, OFF_Y = 0.0, OFF_Z = -0.5; + + private record LiquidKey(int color, int level64) {} + + private static final class Holder { + final Object cacheKey = new Object(); + final TesrMaterial material; + + Holder(int color) { + this.material = TesrMaterial.builder() + .color(((color >> 16) & 0xFF) / 255f, ((color >> 8) & 0xFF) / 255f, (color & 0xFF) / 255f, 1f) + .noCull().unlit().build(); + } + } + + private static final Map HOLDERS = new HashMap<>(); + private static final RenderBlocks FALLBACK_RENDER_BLOCKS = new RenderBlocks(); + + private static final ResourceLocation LABEL_TEXTURE = new ResourceLocation("thaumcraft", "textures/models/label.png"); + private static final TesrMaterial LABEL_MATERIAL = TesrMaterial.builder().color(1f, 1f, 1f, 1f).translucent().cutout(1f / 255f).noCull().build(); + private static final TesrMaterial TAG_MATERIAL = TesrMaterial.builder().color(0.1f, 0.1f, 0.1f, 0.8f).translucent().cutout(1f / 255f).noCull().unlit().build(); + private static final Object LABEL_KEY = new Object(); + private static final Map TAG_KEYS = new HashMap<>(); + + private static final TesrMeshBuilder LABEL_BUILDER = sink -> { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, LABEL_TEXTURE, LABEL_MATERIAL); + t.setNormal(0f, 0f, 1f); + t.addVertexWithUV(-0.25, 0.25, 0.0, 0.0, 1.0); + t.addVertexWithUV(0.25, 0.25, 0.0, 1.0, 1.0); + t.addVertexWithUV(0.25, -0.25, 0.0, 1.0, 0.0); + t.addVertexWithUV(-0.25, -0.25, 0.0, 0.0, 0.0); + }; + + private static final TagBuilder TAG_BUILDER = new TagBuilder(); + + private static final class TagBuilder implements TesrMeshBuilder { + private Aspect aspect; + + @Override + public void angelica$build(TesrMeshSink sink) { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, aspect.getImage(), TAG_MATERIAL); + t.setNormal(0f, 0f, 1f); + t.addVertexWithUV(-8.0, 8.0, 0.0, 0.0, 1.0); + t.addVertexWithUV(8.0, 8.0, 0.0, 1.0, 1.0); + t.addVertexWithUV(8.0, -8.0, 0.0, 1.0, 0.0); + t.addVertexWithUV(-8.0, -8.0, 0.0, 0.0, 0.0); + } + } + + public static void renderLabelBacking(TileEntity te) { + applyBrightness(jarBrightness(te)); + AngelicaTesrMeshCache.INSTANCE.renderCached(LABEL_KEY, LABEL_BUILDER); + } + + public static void renderLabelTag(Aspect aspect, TileEntity te) { + applyBrightness(jarBrightness(te)); + final Object key = TAG_KEYS.computeIfAbsent(aspect, k -> new Object()); + TAG_BUILDER.aspect = aspect; + AngelicaTesrMeshCache.INSTANCE.renderCached(key, TAG_BUILDER); + } + + private static int jarBrightness(TileEntity te) { + if (te == null || te.getWorldObj() == null) return 200; + return Math.max(200, ConfigBlocks.blockJar.getMixedBrightnessForBlock(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord)); + } + + private static void applyBrightness(int bright) { + GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, bright % 65536, (float) (bright / 65536)); + } + + private Tc4JarMeshes() {} + + public static RenderBlocks fallbackRenderBlocks() { + return FALLBACK_RENDER_BLOCKS; + } + + public static boolean renderLiquid(TileJarFillable te) { + if (TileEntityRendererDispatcher.instance.field_147553_e == null) { + return true; + } + final BlockJar jar = (BlockJar) ConfigBlocks.blockJar; + final IIcon icon = jar.iconLiquid; + if (icon == null || te.maxAmount <= 0) { + return false; + } + final int level64 = Math.round(te.amount * 64f / te.maxAmount); + if (level64 <= 0) { + return true; + } + final int color = te.aspect != null ? te.aspect.getColor() : 0xFFFFFF; + + applyBrightness(jarBrightness(te)); + + final Holder holder = HOLDERS.computeIfAbsent(new LiquidKey(color, level64), k -> new Holder(k.color())); + GLStateManager.glPushMatrix(); + GLStateManager.glRotatef(180.0f, 1.0f, 0.0f, 0.0f); + BUILDER.material = holder.material; + BUILDER.level64 = level64; + BUILDER.icon = icon; + AngelicaTesrMeshCache.INSTANCE.renderCached(holder.cacheKey, BUILDER); + GLStateManager.glPopMatrix(); + return true; + } + + private static final Builder BUILDER = new Builder(); + + private static final class Builder implements TesrMeshBuilder { + private TesrMaterial material; + private int level64; + private IIcon icon; + + @Override + public void angelica$build(TesrMeshSink sink) { + build(sink, material, level64, icon); + } + } + + private static void build(TesrMeshSink sink, TesrMaterial material, int level64, IIcon icon) { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TextureMap.locationBlocksTexture, material); + final double maxY = MIN_Y + level64 / 64f * 0.625f; + + final double x1 = OFF_X + MIN_X, x2 = OFF_X + MAX_X; + final double y1 = OFF_Y + MIN_Y, y2 = OFF_Y + maxY; + final double z1 = OFF_Z + MIN_Z, z2 = OFF_Z + MAX_Z; + + // Horizontal faces + double u1 = icon.getInterpolatedU(MIN_X * 16.0); + double u2 = icon.getInterpolatedU(MAX_X * 16.0); + double v1 = icon.getInterpolatedV(MIN_Z * 16.0); + double v2 = icon.getInterpolatedV(MAX_Z * 16.0); + // YNeg + t.addVertexWithUV(x1, y1, z2, u1, v2); + t.addVertexWithUV(x1, y1, z1, u1, v1); + t.addVertexWithUV(x2, y1, z1, u2, v1); + t.addVertexWithUV(x2, y1, z2, u2, v2); + // YPos + t.addVertexWithUV(x2, y2, z2, u2, v2); + t.addVertexWithUV(x2, y2, z1, u2, v1); + t.addVertexWithUV(x1, y2, z1, u1, v1); + t.addVertexWithUV(x1, y2, z2, u1, v2); + + // Z faces + v1 = icon.getInterpolatedV(16.0 - maxY * 16.0); + v2 = icon.getInterpolatedV(16.0 - MIN_Y * 16.0); + // ZNeg + t.addVertexWithUV(x1, y2, z1, u2, v1); + t.addVertexWithUV(x2, y2, z1, u1, v1); + t.addVertexWithUV(x2, y1, z1, u1, v2); + t.addVertexWithUV(x1, y1, z1, u2, v2); + // ZPos + t.addVertexWithUV(x1, y2, z2, u1, v1); + t.addVertexWithUV(x1, y1, z2, u1, v2); + t.addVertexWithUV(x2, y1, z2, u2, v2); + t.addVertexWithUV(x2, y2, z2, u2, v1); + + // X faces + u1 = icon.getInterpolatedU(MIN_Z * 16.0); + u2 = icon.getInterpolatedU(MAX_Z * 16.0); + // XNeg + t.addVertexWithUV(x1, y2, z2, u2, v1); + t.addVertexWithUV(x1, y2, z1, u1, v1); + t.addVertexWithUV(x1, y1, z1, u1, v2); + t.addVertexWithUV(x1, y1, z2, u2, v2); + // XPos + t.addVertexWithUV(x2, y1, z2, u1, v2); + t.addVertexWithUV(x2, y1, z1, u2, v2); + t.addVertexWithUV(x2, y2, z1, u2, v1); + t.addVertexWithUV(x2, y2, z2, u1, v1); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 0a7d66a4f..4fed6888c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -1,19 +1,23 @@ package com.gtnewhorizons.angelica.config; import com.gtnewhorizon.gtnhlib.config.Config; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; @Config(modid = "angelica", filename = "angelica-modules") public class AngelicaConfig { - @Config.Comment("Enable Celeritas terrain rendering") - @Config.DefaultBoolean(true) - @Config.RequiresMcRestart - public static boolean enableCeleritas; - - @Config.Comment("Enable multi-threaded chunk building for improved performance [Requires Celeritas]") + @Config.Comment("Enable multi-threaded chunk building for improved performance") @Config.DefaultBoolean(true) @Config.RequiresWorldRestart public static boolean enableThreadedChunkBuilding; + @Config.Comment({ + "GPU-driven chunk culling mode (requires compute shader support):", + " CPU_ONLY - Compute culling off; CPU emitter handles culling.", + " COMPUTE - GPU compute frustum cull." + }) + @Config.DefaultEnum("CPU_ONLY") + public static GpuCullingMode gpuCullingMode; + @Config.Comment("Number of chunk builder threads. 0 = auto-detect, -1 = use single-threaded fallback") @Config.DefaultInt(0) @Config.RangeInt(min = -1, max = 16) @@ -38,7 +42,7 @@ public class AngelicaConfig { @Config.Ignore() public static boolean enableTestBlocks; - @Config.Comment("Enable Iris Shaders [Requires Celeritas]") + @Config.Comment("Enable Iris Shaders") @Config.DefaultBoolean(true) @Config.RequiresMcRestart public static boolean enableIris; @@ -112,6 +116,51 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean enableFontRenderer; + @Config.Comment("Collapse vanilla sign text into a single batched draw per sign (requires font batching)") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRSignCache; + + @Config.Comment("Cache the vanilla chest mesh and share it across chests") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRChestCache; + + @Config.Comment("Batch and instance living-entity model parts on FFP-managed passes") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableEntityBatching; + + @Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean shaderParityFlip; + + @Config.Comment("Skip the end-of-frame glFlush before the buffer swap [Experimental]") + @Config.DefaultBoolean(false) + @Config.RequiresMcRestart + public static boolean skipEndOfFrameFlush; + + @Config.Comment("Cache the vanilla skull mesh per skull type/player skin and batch skull draws") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRSkullCache; + + @Config.Comment("Cache the Thaumcraft jar liquid and batch jar draws") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRJarCache; + + @Config.Comment("Cache the vanilla beacon beam mesh and batch beam draws") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRBeaconCache; + + @Config.Comment("Route tile-entity renderers implementing TesrMeshProvider through the batched mesh cache") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableTESRProviderDispatch; + @Config.Comment("Enable full RGB color support (16.7M colors) using &#RRGGBB syntax in text") @Config.DefaultBoolean(true) public static boolean enableRGBColors; @@ -160,11 +209,6 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean speedupAnimations; - @Config.Comment("Optimize Texture Loading. [From Hodgepodge]") - @Config.DefaultBoolean(true) - @Config.RequiresMcRestart - public static boolean optimizeTextureLoading; - @Config.Comment("Fix RenderBlockFluid reading the block type from the world access multiple times") @Config.DefaultBoolean(true) @Config.RequiresMcRestart @@ -278,6 +322,7 @@ public class AngelicaConfig { @Config.Comment("Register HardcodedCustomUniforms in Iris Shaders. May help with compatibility in certain shader packs") @Config.DefaultBoolean(false) + @Config.RequiresMcRestart public static boolean enableHardcodedCustomUniforms; @Config.Comment("Modern MC_VERSION to try if shader pack has no 1.7.10 section. 0 = default (260101)") @@ -289,6 +334,19 @@ public class AngelicaConfig { @Config.DefaultBoolean(true) public static boolean defineIsIris; + @Config.Comment("Cull tile entities in the Iris shadow pass.") + @Config.DefaultBoolean(true) + public static boolean cullShadowTileEntities; + + @Config.Comment("Max distance (blocks) a tile entity is re-drawn into the shadow pass when cullShadowTileEntities is on") + @Config.DefaultInt(32) + @Config.RangeInt(min = 8, max = 256) + public static int shadowTileEntityMaxDistance; + + @Config.Comment({"Skip tile entities whose block already renders in the terrain mesh (getRenderType() != -1) from the shadow pass"}) + @Config.DefaultBoolean(true) + public static boolean shadowSkipInMeshTileEntities; + @Config.Comment("ASM transformer exclusion narrowing for mod compatibility. Disable per-mod if narrowing causes class loading issues.") public static TransformerCompat transformerCompat = new TransformerCompat(); @@ -366,4 +424,22 @@ public class AngelicaConfig { @Config.DefaultBoolean(true) @Config.RequiresMcRestart public static boolean entityModernDamageOverlay; + + public enum GLProfile { AUTO, CORE, ES } + + @Config.Comment("GL context profile: AUTO (probes Core first), CORE (desktop only), ES (GLES 3.2 only). Also settable via -Dangelica.glProfile=auto|core|es.") + @Config.DefaultEnum("AUTO") + @Config.RequiresMcRestart + public static GLProfile glProfile; + + public static void applyGpuCullingMode() { + GpuCulling.setMode(gpuCullingMode == null ? GpuCullingMode.CPU_ONLY : gpuCullingMode); + } + + public static GLProfile getEffectiveGlProfile() { + final String sys = SystemProperties.GL_PROFILE.trim().toUpperCase(); + if ("GLES".equals(sys)) return GLProfile.ES; + if (sys.isEmpty()) return glProfile; + try { return GLProfile.valueOf(sys); } catch (IllegalArgumentException e) { return glProfile; } + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/config/GpuCullingMode.java b/src/main/java/com/gtnewhorizons/angelica/config/GpuCullingMode.java new file mode 100644 index 000000000..74c8cb1a2 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/config/GpuCullingMode.java @@ -0,0 +1,23 @@ +package com.gtnewhorizons.angelica.config; + +import me.jellysquid.mods.sodium.client.gui.options.named.NamedState; + +public enum GpuCullingMode implements NamedState { + CPU_ONLY(false, "options.angelica.gpuCullingMode.cpu_only"), + COMPUTE (true, "options.angelica.gpuCullingMode.compute"); + + private final boolean compute; + private final String key; + + GpuCullingMode(boolean compute, String key) { + this.compute = compute; + this.key = key; + } + + @Override + public String getKey() { + return key; + } + + public boolean computeEnabled() { return compute; } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRoute.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRoute.java new file mode 100644 index 000000000..4946f2ec9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRoute.java @@ -0,0 +1,117 @@ +package com.gtnewhorizons.angelica.debug.flyby; + +/** + * A deterministic camera path, expressed relative to the position the player held when the run was started. + *

+ * Moving routes are measured in blocks rather than tick. + */ +public enum FlybyRoute { + /** + * Straight line path, 512 blocks (32 chunks) by default. + */ + STRAIGHT("straight", Kind.STRAIGHT, 0.5D, 0.0D, 512), + + /** + * Stationary rotation, 720 degrees by default. + */ + PAN("pan", Kind.ROTATE, 0.0D, 1.5D, 720), + + /** + * Closed square: four legs of {@code length} blocks joined by four 90-degree turns, ending where it started. + */ + CIRCUIT("circuit", Kind.SQUARE, 0.5D, 4.0D, 128), + + /** Fixed vantage, no motion, measured in ticks. */ + STATIC("static", Kind.STILL, 0.0D, 0.0D, 600); + + public enum Kind { STRAIGHT, ROTATE, SQUARE, STILL } + + public static final int CIRCUIT_LEGS = 4; + public static final double CIRCUIT_TURN_DEGREES = 90.0D; + + private final String id; + private final Kind kind; + private final double blocksPerTick; + private final double degreesPerTick; + private final int defaultLength; + + FlybyRoute(String id, Kind kind, double blocksPerTick, double degreesPerTick, int defaultLength) { + this.id = id; + this.kind = kind; + this.blocksPerTick = blocksPerTick; + this.degreesPerTick = degreesPerTick; + this.defaultLength = defaultLength; + } + + public String id() { + return this.id; + } + + public Kind kind() { + return this.kind; + } + + public double blocksPerTick() { + return this.blocksPerTick; + } + + public double degreesPerTick() { + return this.degreesPerTick; + } + + public int defaultLength() { + return this.defaultLength; + } + + public String lengthUnit() { + return switch (this.kind) { + case STRAIGHT -> "blocks"; + case SQUARE -> "blocks per leg"; + case ROTATE -> "degrees"; + case STILL -> "ticks"; + }; + } + + public double speedOr(double override) { + return override > 0.0D ? override : this.blocksPerTick; + } + + public int legTicks(int length, double speed) { + return (int) Math.ceil(length / this.speedOr(speed)); + } + + public int turnTicks() { + return (int) Math.ceil(CIRCUIT_TURN_DEGREES / this.degreesPerTick); + } + + /** + * Converts a run length in {@link #lengthUnit()} into ticks at {@code speed} blocks per tick. + */ + public int toTicks(int length, double speed) { + if (length <= 0) length = this.defaultLength; + return switch (this.kind) { + case STRAIGHT -> this.legTicks(length, speed); + case ROTATE -> (int) Math.ceil(length / this.degreesPerTick); + case SQUARE -> CIRCUIT_LEGS * (this.legTicks(length, speed) + this.turnTicks()); + case STILL -> length; + }; + } + + public static FlybyRoute byId(String id) { + for (FlybyRoute route : values()) { + if (route.id.equalsIgnoreCase(id)) { + return route; + } + } + return null; + } + + public static String ids() { + StringBuilder sb = new StringBuilder(); + for (FlybyRoute route : values()) { + if (sb.length() > 0) sb.append('|'); + sb.append(route.id); + } + return sb.toString(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java new file mode 100644 index 000000000..c826e2445 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java @@ -0,0 +1,431 @@ +package com.gtnewhorizons.angelica.debug.flyby; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.WorldServer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Arrays; + +/** Flies a deterministic camera path */ +public final class FlybyRunner { + public static final FlybyRunner INSTANCE = new FlybyRunner(); + + private static final Logger LOGGER = LogManager.getLogger("Angelica/Flyby"); + private static final long[] NO_FRAMES = new long[0]; + private static final double[] NO_PATH = new double[0]; + private static final float[] NO_YAW = new float[0]; + private static final byte[] NO_PHASE = new byte[0]; + private static final int MAX_RECORDED_FRAMES = 200_000; + private static final long FIXED_TIME_OF_DAY = 6000L; + + private enum State { IDLE, WAITING, WARMUP, RUNNING, SETTLE, EXITING, DONE } + + private static final int EXIT_TICKS = 20; + private static final int SETTLE_TICKS = 40; + + private State state = State.IDLE; + private FlybyRoute route; + private int warmupTicks; + private int runLength; + private double speed; + private int runTicks; + private int tick; + private boolean waitForTracy; + private boolean exitWhenDone; + private boolean startedFromProperties; + private volatile boolean freezeRequested; + + private double originX, originY, originZ; + private float originYaw, originPitch; + + private double[] pathX = NO_PATH; + private double[] pathZ = NO_PATH; + private float[] pathYaw = NO_YAW; + private byte[] pathLeg = NO_PHASE; + private byte[] pathTurning = NO_PHASE; + + private long plotLeg; + private long plotTurning; + private int lastPhase = -1; + + private long[] frameTimesNs = NO_FRAMES; + private int frameCount; + private boolean framesTruncated; + private long lastFrameNs; + private long runStartNs; + + private FlybyRunner() {} + + public void startFromProperties() { + final String id = SystemProperties.FLYBY_ROUTE; + if (id == null || id.isEmpty()) return; + + final FlybyRoute configured = FlybyRoute.byId(id); + if (configured == null) { + LOGGER.error("Unknown flyby route '{}', expected one of {}", id, FlybyRoute.ids()); + return; + } + + this.startedFromProperties = true; + this.start(configured, SystemProperties.FLYBY_LENGTH, SystemProperties.FLYBY_WARMUP_TICKS, SystemProperties.FLYBY_SPEED); + this.waitForTracy = SystemProperties.FLYBY_WAIT_FOR_TRACY; + this.exitWhenDone = SystemProperties.FLYBY_EXIT_WHEN_DONE; + LOGGER.info("Flyby started from properties: route={} warmup={} length={} {} ({} ticks) waitForTracy={} exitWhenDone={}", + configured.id(), this.warmupTicks, this.runLength, configured.lengthUnit(), this.runTicks, + this.waitForTracy, this.exitWhenDone); + } + + public void start(FlybyRoute route, int length, int warmupTicks, double speed) { + this.route = route; + this.speed = speed; + this.runLength = length > 0 ? length : route.defaultLength(); + this.runTicks = route.toTicks(this.runLength, speed); + this.warmupTicks = Math.max(0, warmupTicks); + this.tick = 0; + this.frameCount = 0; + this.framesTruncated = false; + this.waitForTracy = false; + this.exitWhenDone = false; + this.state = State.WAITING; + } + + public boolean isActive() { + return this.state != State.IDLE && this.state != State.DONE; + } + + public String describe() { + if (this.route == null) return "idle"; + return this.route.id() + " " + this.state + " tick " + this.tick + "/" + this.runTicks; + } + + @SubscribeEvent + public void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || this.state == State.IDLE || this.state == State.DONE) return; + + final Minecraft mc = Minecraft.getMinecraft(); + final EntityClientPlayerMP player = mc.thePlayer; + if (player == null || mc.theWorld == null) return; + + switch (this.state) { + case WAITING -> { + if (this.waitForTracy && !Tracy.isConnected()) return; + this.begin(mc, player); + } + case WARMUP -> { + this.applyPosition(player, 0); + if (++this.tick >= this.warmupTicks) { + this.tick = 0; + this.beginMeasuring(); + } + } + case RUNNING -> { + this.applyPosition(player, this.tick); + this.emitPhase(this.tick); + if (++this.tick > this.runTicks) { + this.finish(mc, player); + } + } + case SETTLE -> { + this.holdPosition(player); + if (++this.tick >= SETTLE_TICKS) { + this.teardown(mc, player); + } + } + case EXITING -> { + if (++this.tick >= EXIT_TICKS) { + this.state = State.DONE; + LOGGER.info("Flyby complete, shutting down so the capture can finalise"); + mc.shutdown(); + } + } + default -> { } + } + } + + @SubscribeEvent + public void onRenderTick(TickEvent.RenderTickEvent event) { + if (event.phase != TickEvent.Phase.END || this.state != State.RUNNING) return; + + final long now = System.nanoTime(); + if (this.lastFrameNs != 0L) { + if (this.frameCount < this.frameTimesNs.length) { + this.frameTimesNs[this.frameCount++] = now - this.lastFrameNs; + } else { + this.framesTruncated = true; + } + } + this.lastFrameNs = now; + } + + private void begin(Minecraft mc, EntityClientPlayerMP player) { + this.originX = player.posX; + this.originY = player.posY; + this.originZ = player.posZ; + this.originPitch = player.rotationPitch; + + this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F; + if (this.originYaw != player.rotationYaw) { + LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw); + } + + this.buildPath(); + this.freezeTimeAndWeather(mc); + + this.state = this.warmupTicks > 0 ? State.WARMUP : State.RUNNING; + this.tick = 0; + if (this.state == State.RUNNING) this.beginMeasuring(); + + LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(), + this.originX, this.originY, this.originZ, this.originYaw); + } + + private void buildPath() { + final int n = this.runTicks + 1; + this.pathX = new double[n]; + this.pathZ = new double[n]; + this.pathYaw = new float[n]; + this.pathLeg = new byte[n]; + this.pathTurning = new byte[n]; + + double x = this.originX; + double z = this.originZ; + double yaw = this.originYaw; + + final double effectiveSpeed = this.route.speedOr(this.speed); + final int legTicks = this.route.kind() == FlybyRoute.Kind.SQUARE ? this.route.legTicks(this.runLength, this.speed) : 0; + final int turnTicks = this.route.kind() == FlybyRoute.Kind.SQUARE ? this.route.turnTicks() : 0; + final int segment = legTicks + turnTicks; + + final double cornerStep = turnTicks > 0 ? FlybyRoute.CIRCUIT_TURN_DEGREES / turnTicks : 0.0D; + final double sweepStep = this.runTicks > 0 ? (double) this.runLength / this.runTicks : 0.0D; + + for (int i = 0; i < n; i++) { + this.pathX[i] = x; + this.pathZ[i] = z; + this.pathYaw[i] = (float) yaw; + + double advance = 0.0D; + double turn = 0.0D; + + switch (this.route.kind()) { + case STRAIGHT -> advance = effectiveSpeed; + case ROTATE -> turn = sweepStep; + case SQUARE -> { + if (segment > 0 && (i % segment) < legTicks) { + advance = effectiveSpeed; + } else { + turn = cornerStep; + this.pathTurning[i] = 1; + } + this.pathLeg[i] = (byte) Math.min(FlybyRoute.CIRCUIT_LEGS - 1, segment > 0 ? i / segment : 0); + } + case STILL -> { } + } + if (this.route.kind() == FlybyRoute.Kind.ROTATE) this.pathTurning[i] = 1; + + if (advance != 0.0D) { + final double yawRad = Math.toRadians(yaw); + x += -Math.sin(yawRad) * advance; + z += Math.cos(yawRad) * advance; + } + yaw += turn; + } + } + + private void emitPhase(int index) { + if (!Tracy.ENABLED || index >= this.pathLeg.length) return; + + final int leg = this.pathLeg[index]; + final int turning = this.pathTurning[index]; + Tracy.plotInt(this.plotLeg, leg); + Tracy.plotInt(this.plotTurning, turning); + + final int phase = (leg << 1) | turning; + if (phase != this.lastPhase) { + this.lastPhase = phase; + Tracy.message("flyby " + (turning != 0 ? "turn" : "leg") + " " + leg); + } + } + + private void beginMeasuring() { + this.state = State.RUNNING; + this.plotLeg = Tracy.plotHandle("flyby.leg"); + this.plotTurning = Tracy.plotHandle("flyby.turning"); + this.lastPhase = -1; + this.frameTimesNs = new long[Math.min(MAX_RECORDED_FRAMES, Math.max(1024, this.runTicks * 20))]; + this.frameCount = 0; + this.lastFrameNs = 0L; + this.runStartNs = System.nanoTime(); + Tracy.message("flyby start route=" + this.route.id() + + " length=" + this.runLength + this.route.lengthUnit() + + " speed=" + this.route.speedOr(this.speed) + "b/t" + + " ticks=" + this.runTicks + + " sdlgpu=" + SystemProperties.USE_SDL_GPU); + } + + private void holdPosition(EntityClientPlayerMP player) { + final int last = this.pathX.length - 1; + if (last < 0) return; + + player.motionX = 0.0D; + player.motionY = 0.0D; + player.motionZ = 0.0D; + player.ySize = 0.0F; + + player.prevPosX = player.lastTickPosX = this.pathX[last]; + player.prevPosY = player.lastTickPosY = this.originY; + player.prevPosZ = player.lastTickPosZ = this.pathZ[last]; + player.prevRotationYaw = player.rotationYaw = this.pathYaw[last]; + player.prevRotationYawHead = player.rotationYawHead = this.pathYaw[last]; + player.prevRotationPitch = player.rotationPitch = this.originPitch; + player.setPosition(this.pathX[last], this.originY, this.pathZ[last]); + } + + private void applyPosition(EntityClientPlayerMP player, int index) { + final int i = Math.min(index, this.pathX.length - 1); + final int prev = Math.max(0, i - 1); + + final double x = this.pathX[i]; + final double z = this.pathZ[i]; + final double prevX = this.pathX[prev]; + final double prevZ = this.pathZ[prev]; + final float yaw = this.pathYaw[i]; + final float prevYaw = this.pathYaw[prev]; + + player.motionX = 0.0D; + player.motionY = 0.0D; + player.motionZ = 0.0D; + player.ySize = 0.0F; + + player.prevPosX = player.lastTickPosX = prevX; + player.prevPosY = player.lastTickPosY = this.originY; + player.prevPosZ = player.lastTickPosZ = prevZ; + + player.prevRotationYaw = prevYaw; + player.rotationYaw = yaw; + player.prevRotationYawHead = prevYaw; + player.rotationYawHead = yaw; + player.prevRotationPitch = player.rotationPitch = this.originPitch; + + player.setPosition(x, this.originY, z); + } + + /** Requests the freeze; the write happens on the server thread in {@link #onServerTick}. */ + private void freezeTimeAndWeather(Minecraft mc) { + final MinecraftServer server = mc.getIntegratedServer(); + if (server == null) { + LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather - results may not be comparable"); + return; + } + + this.freezeRequested = true; + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END || !this.freezeRequested) return; + this.freezeRequested = false; + + final MinecraftServer server = MinecraftServer.getServer(); + if (server == null) return; + + for (WorldServer world : server.worldServers) { + if (world == null) continue; + + if (world.getGameRules().getGameRuleBooleanValue("doDaylightCycle")) { + world.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); + LOGGER.warn("Flyby: doDaylightCycle was on, disabled it"); + } + if (world.getWorldInfo().isRaining() || world.getWorldInfo().isThundering()) { + LOGGER.warn("Flyby: weather was active, clearing it"); + world.getWorldInfo().setRaining(false); + world.getWorldInfo().setThundering(false); + } + world.getWorldInfo().setRainTime(Integer.MAX_VALUE); + world.getWorldInfo().setThunderTime(Integer.MAX_VALUE); + + if (world.getWorldTime() % 24000L != FIXED_TIME_OF_DAY) { + LOGGER.info("Flyby: freezing time at {}", FIXED_TIME_OF_DAY); + world.setWorldTime(FIXED_TIME_OF_DAY); + } + } + } + + private void finish(Minecraft mc, EntityClientPlayerMP player) { + this.state = State.SETTLE; + this.tick = 0; + final long elapsedNs = System.nanoTime() - this.runStartNs; + Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount); + + final String summary = this.summarise(elapsedNs, player); + LOGGER.info(summary); + if (mc.thePlayer != null) { + mc.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + summary)); + } + + } + + private void teardown(Minecraft mc, EntityClientPlayerMP player) { + Tracy.message("flyby teardown"); + + this.returnToOrigin(player); + + this.tick = 0; + this.state = this.exitWhenDone ? State.EXITING : State.DONE; + } + + private void returnToOrigin(EntityClientPlayerMP player) { + player.motionX = 0.0D; + player.motionY = 0.0D; + player.motionZ = 0.0D; + player.ySize = 0.0F; + player.setPositionAndRotation(this.originX, this.originY, this.originZ, this.originYaw, this.originPitch); + player.lastTickPosX = this.originX; + player.lastTickPosY = this.originY; + player.lastTickPosZ = this.originZ; + LOGGER.info("Flyby returned to origin {} {} {}", this.originX, this.originY, this.originZ); + } + + private String summarise(long elapsedNs, EntityClientPlayerMP player) { + final StringBuilder sb = new StringBuilder(192); + sb.append("Flyby ").append(this.route.id()) + .append(": ").append(this.frameCount).append(" frames in ") + .append(String.format("%.2fs", elapsedNs / 1_000_000_000.0D)); + + if (this.frameCount > 0) { + final long[] sorted = Arrays.copyOf(this.frameTimesNs, this.frameCount); + Arrays.sort(sorted); + long total = 0L; + for (long ns : sorted) total += ns; + sb.append(String.format(", avg %.2fms, p50 %.2fms, p99 %.2fms, max %.2fms", + total / (double) this.frameCount / 1e6D, + sorted[this.frameCount / 2] / 1e6D, + sorted[Math.min(this.frameCount - 1, (int) (this.frameCount * 0.99D))] / 1e6D, + sorted[this.frameCount - 1] / 1e6D)); + } + if (this.framesTruncated) sb.append(" (frame samples truncated)"); + + sb.append(String.format(", end position %.6f %.6f %.6f", player.posX, player.posY, player.posZ)); + return sb.toString(); + } + + public void cancel() { + if (this.isActive()) { + LOGGER.info("Flyby cancelled"); + this.state = State.DONE; + } + } + + public boolean startedFromProperties() { + return this.startedFromProperties; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/dynamiclights/DynamicLights.java b/src/main/java/com/gtnewhorizons/angelica/dynamiclights/DynamicLights.java index 3adabcbb3..2d72f319a 100644 --- a/src/main/java/com/gtnewhorizons/angelica/dynamiclights/DynamicLights.java +++ b/src/main/java/com/gtnewhorizons/angelica/dynamiclights/DynamicLights.java @@ -587,18 +587,22 @@ public class DynamicLights { return 0; } + public static int getLuminanceFromEntityItem(@NotNull EntityItem item, int stackLuminance) { + if (stackLuminance <= 0) return 0; + if (item.isBurning()) return 15; + // TODO only have certain items not glow in water? + if (item.isInsideOfMaterial(Material.water)) return 0; + return stackLuminance; + } + public static int getLuminanceFromEntity(@NotNull Entity entity) { + if (entity instanceof EntityItem item) { + return getLuminanceFromEntityItem(item, getLuminanceFromItemStack(item.getEntityItem())); + } if (entity.isBurning()) return 15; - final boolean inWater = entity.isInsideOfMaterial(Material.water); - - // TODO only have certain items not glow in water? - if (inWater) return 0; - - if (entity instanceof EntityItem item) { - return getLuminanceFromItemStack(item.getEntityItem()); - } + if (entity.isInsideOfMaterial(Material.water)) return 0; int luminance = 0; if (entity instanceof EntityLivingBase living) { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java b/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java index cb149a240..bb11d1e82 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java @@ -4,8 +4,13 @@ import com.gtnewhorizons.angelica.client.rendering.TextureTracker; import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler; import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler; import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; import net.coderbot.iris.Iris; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; import net.coderbot.iris.gbuffer_overrides.state.StateTracker; import net.coderbot.iris.gl.blending.AlphaTestStorage; import net.coderbot.iris.gl.blending.BlendModeStorage; @@ -16,6 +21,8 @@ import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.samplers.IrisSamplers; import net.coderbot.iris.texture.pbr.PBRTextureManager; +import net.coderbot.iris.uniforms.SystemTimeUniforms; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; public class IrisGLSMBridge { @@ -28,7 +35,9 @@ public class IrisGLSMBridge { private static Runnable fogDensityListener = null; private static Runnable colorModulatorListener = null; + private static final Int2IntOpenHashMap programLastUpdatedFrame = new Int2IntOpenHashMap(); static { + programLastUpdatedFrame.defaultReturnValue(-1); StateUpdateNotifiers.alphaFuncNotifier = listener -> alphaFuncListener = listener; StateUpdateNotifiers.alphaTestNotifier = listener -> alphaTestListener = listener; StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener; @@ -40,7 +49,23 @@ public class IrisGLSMBridge { } public static void register() { + GLSMConfig.expandVertexFormats = Iris.enabled; IrisSamplers.initRenderer(); + GLSMHooks.shaderWorkSubmitter = new ShaderWorkSubmitter() { + @Override + public CompletableFuture submit(Supplier work) { + return Iris.ShaderTransformExecutor.submitTracked(work); + } + }; + GLSMHooks.postTransformProcessor = (src, shaderType) -> { + if (Iris.ShaderTransformExecutor.isOnWorker()) { + ShaderManager.prewarmSpirv(src, shaderType.id); + } else { + Iris.ShaderTransformExecutor.submitTracked(() -> { + ShaderManager.prewarmSpirv(src, shaderType.id); + }); + } + }; GLSMHooks.blendHandler = new DeferredBlendHandler() { @Override public boolean isBlendLocked() { @@ -171,6 +196,8 @@ public class IrisGLSMBridge { if (DepthColorStorage.isOwnedProgram(event.newProgram)) { DepthColorStorage.unlockDepthColor(); + } else { + drp.onModProgramOverride(); } }); @@ -181,10 +208,15 @@ public class IrisGLSMBridge { if (pipeline instanceof DeferredWorldRenderingPipeline drp) { DeferredWorldRenderingPipeline.Pass activePass = drp.getActivePassProgram(); if (activePass != null && activePass.getProgram() != null && activePass.getProgram().getProgramId() == event.newProgram) { - activePass.getProgram().getUniforms().update(); + final int frame = SystemTimeUniforms.COUNTER.getAsInt(); + if (programLastUpdatedFrame.get(event.newProgram) != frame) { + activePass.getProgram().getUniforms().update(); + programLastUpdatedFrame.put(event.newProgram, frame); + } } } }); + GLSMHooks.PROGRAM_DELETE.addListener(event -> programLastUpdatedFrame.remove(event.program)); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java index 4b157b7e3..32e7fe21e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java @@ -8,10 +8,12 @@ import com.gtnewhorizon.gtnhmixins.builders.ITransformers; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.CompatConfig; import com.gtnewhorizons.angelica.config.FontConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.loading.DependencyVerifier; import com.gtnewhorizons.angelica.glsm.loading.EcosystemNarrowRules; import com.gtnewhorizons.angelica.loading.fml.compat.CompatHandlers; import com.gtnewhorizons.angelica.lwjgl3.MissingDependencySdl; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; import com.gtnewhorizons.angelica.mixins.Mixins; import com.gtnewhorizons.retrofuturabootstrap.SharedConfig; import cpw.mods.fml.relauncher.FMLLaunchHandler; @@ -79,13 +81,21 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix ctx.updateLoggers(); // Debug features - AngelicaConfig.enableTestBlocks = Boolean.getBoolean("angelica.enableTestBlocks"); + AngelicaConfig.enableTestBlocks = SystemProperties.ENABLE_TEST_BLOCKS; } catch (ConfigException e) { throw new RuntimeException(e); } verifyDependencies(); + if (SystemProperties.USE_SDL_GPU) { + if (SDLGPUGate.isSDLGPUAvailable()) { + LOGGER.info("SDL GPU window mode enabled"); + } else { + LOGGER.warn("angelica.sdlgpu.enable=true but SDL GPU dependencies not available, falling back to GL"); + } + } + // Register a scoped redirector early so classes prematurely loaded by other coremods during discovery/injectData // (e.g. Mycelium using HookLoader.class.getName()) still get GL calls redirected to GLSM. Only targets specific mod // packages to avoid interfering with mixin delegation on game classes. AngelicaLateTweaker removes this registration once @@ -108,7 +118,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix for (String exclusion : EcosystemNarrowRules.LWJGL3IFY_EXCLUSIONS_SHARED) { handle.exclusions().add(exclusion); } - handle.exclusions().add("com.gtnewhorizons.angelica.vulkan"); + handle.exclusions().add("com.gtnewhorizons.angelica.sdlgpu"); } } @@ -204,9 +214,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix final boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE; if (!rfbLoaded) { tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.AngelicaLateTweaker"); - if (AngelicaConfig.enableCeleritas) { - tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker"); - } + tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker"); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java index ca06665bc..4048ac3c4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java @@ -9,6 +9,7 @@ import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.jar.Attributes; import java.util.jar.Manifest; /** RfbClassTransformer wrapper for {@link AngelicaRedirector} */ @@ -26,6 +27,13 @@ public class RFBAngelicaRedirector implements RfbClassTransformer { return "redirector"; } + private static final Attributes.Name LWJGL3_AWARE = new Attributes.Name("Lwjgl3ify-Aware"); + + /** We sort before lwjgl3ify:redirect, so an aware caller's descriptors are still org.lwjgl here and stay that way. */ + private static boolean isLwjgl3Aware(@Nullable Manifest manifest) { + return manifest != null && "true".equals(manifest.getMainAttributes().getValue(LWJGL3_AWARE)); + } + @Override public @NotNull String @Nullable [] sortAfter() { return new String[] {"*", "mixin:mixin"}; @@ -55,7 +63,7 @@ public class RFBAngelicaRedirector implements RfbClassTransformer { public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { - final boolean changed = inner.transformClassNode(className, classNode.getNode()); + final boolean changed = inner.transformClassNode(className, classNode.getNode(), isLwjgl3Aware(manifest)); if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/shared/AngelicaClassDump.java b/src/main/java/com/gtnewhorizons/angelica/loading/shared/AngelicaClassDump.java index a50010184..080ee9d99 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/shared/AngelicaClassDump.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/shared/AngelicaClassDump.java @@ -1,21 +1,20 @@ package com.gtnewhorizons.angelica.loading.shared; import com.gtnewhorizon.gtnhlib.asm.ASMUtil; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; public class AngelicaClassDump { - private static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.dumpClass"); - public static void dumpClass(String className, byte[] originalBytes, byte[] transformedBytes, Object transformer) { - if (DUMP_CLASS) { + if (SystemProperties.DUMP_CLASS) { ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer); ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer); } } public static void dumpRFBClass(String className, ClassNodeHandle classNode, Object transformer) { - if (DUMP_CLASS) { + if (SystemProperties.DUMP_CLASS) { final byte[] originalBytes = classNode.getOriginalBytes(); final byte[] transformedBytes = classNode.computeBytes(); ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer); diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java index ebffc8ab4..355e7bd41 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java @@ -37,4 +37,9 @@ public final class AngelicaRedirector { public boolean transformClassNode(String transformedName, ClassNode cn) { return core.transformClassNode(transformedName, cn); } + + /** @return Was the class changed? */ + public boolean transformClassNode(String transformedName, ClassNode cn, boolean lwjgl3Aware) { + return core.transformClassNode(transformedName, cn, lwjgl3Aware); + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/CeleritasBlockTransform.java b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/CeleritasBlockTransform.java index 9694bf7cf..2b4b50c42 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/CeleritasBlockTransform.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/CeleritasBlockTransform.java @@ -2,7 +2,7 @@ package com.gtnewhorizons.angelica.loading.shared.transformers; import com.google.common.collect.ImmutableList; import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser; -import net.minecraft.launchwrapper.Launch; +import com.gtnewhorizons.angelica.config.SystemProperties; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -16,8 +16,6 @@ import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -27,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap; public final class CeleritasBlockTransform implements Opcodes { - private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam"); + private static final boolean LOG_SPAM = SystemProperties.REDIRECTOR_LOGSPAM; private static final Logger LOGGER = LogManager.getLogger("CeleritasBlockTransformer"); private static final String BlockClass = "net/minecraft/block/Block"; private static final String ThreadedBlockData = "com/gtnewhorizons/angelica/client/rendering/ThreadedBlockData"; diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 13366eca2..05fef8a9d 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -6,6 +6,9 @@ import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.api.BlockLightProvider; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.CompatConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.CaptureGate; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; import jss.notfine.config.MCPatcherForgeConfig; import jss.notfine.config.NotFineConfig; import lombok.Getter; @@ -25,6 +28,14 @@ public enum Mixins implements IMixins { ) ), + ANGELICA_CHAT_CACHE(new MixinBuilder() + .setPhase(Phase.EARLY) + .addClientMixins( + "angelica.chat.MixinChatLine" + , "angelica.chat.MixinGuiNewChat" + ) + ), + ANGELICA(new MixinBuilder() .setPhase(Phase.EARLY) .addClientMixins( @@ -37,6 +48,7 @@ public enum Mixins implements IMixins { , "angelica.MixinMinecraft_FrameHook" , "angelica.MixinMinecraft_IconifyGuard" , "angelica.MixinMinecraftServer" + , "angelica.MixinSimpleReloadableResourceManager" , "angelica.bugfixes.MixinItemRenderer_EdgeDepth" , "angelica.bugfixes.MixinModelCreeper_AuraBodyInflate" , "angelica.bugfixes.MixinModelSkeleton_LegPelvisZFight" @@ -76,6 +88,18 @@ public enum Mixins implements IMixins { ) ), + ANGELICA_SDL_GPU_DISPLAY(new MixinBuilder("SDL-GPU-aware Display.create path") + .setPhase(Phase.EARLY) + .setApplyIf(() -> SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable()) + .addClientMixins("sdlgpu.MixinForgeHooksClient_SDLGPUDisplay") + ), + + ANGELICA_SDL_GPU_SHADOW_VOXEL_PREPASS(new MixinBuilder("Voxelization compute pre-pass before shadow raster (SDL_GPU)") + .setPhase(Phase.EARLY) + .setApplyIf(() -> SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable()) + .addClientMixins("sdlgpu.MixinDefaultChunkRenderer_ShadowVoxelization") + ), + ANGELICA_VBO_CLOUDS( new MixinBuilder() .setApplyIf(() -> AngelicaConfig.enableVBOClouds) @@ -113,13 +137,102 @@ public enum Mixins implements IMixins { ) ), + ANGELICA_TESR_SIGN_CACHE(new MixinBuilder() + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableFontRenderer && AngelicaConfig.enableTESRSignCache) + .addClientMixins( + "angelica.tesr.MixinTileEntitySignRenderer" + ) + ), + + ANGELICA_TESR_CHEST_CACHE(new MixinBuilder() + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableTESRChestCache) + .addClientMixins( + "angelica.tesr.MixinTileEntityChestRenderer", + "angelica.tesr.MixinTileEntityEnderChestRenderer" + ) + ), + + ANGELICA_TESR_SKULL_CACHE(new MixinBuilder() + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableTESRSkullCache) + .addClientMixins( + "angelica.tesr.MixinTileEntitySkullRenderer" + ) + ), + + ANGELICA_ENTITY_BATCHING(new MixinBuilder() + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableEntityBatching) + .addClientMixins( + "angelica.entity.MixinModelRenderer", + "angelica.entity.MixinRenderGlobal_EntityBatch", + "angelica.entity.MixinTextureManager" + ) + ), + + ANGELICA_SKIP_END_FRAME_FLUSH(new MixinBuilder("Skip the end-of-frame glFlush before the buffer swap") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.skipEndOfFrameFlush) + .addClientMixins( + "angelica.MixinMinecraft_SkipEndFrameFlush" + ) + ), + + THAUMCRAFT_TESR_JAR_CACHE(new MixinBuilder("Batch TC4 jar liquid via the retained TESR mesh cache") + .setPhase(Phase.LATE) + .setApplyIf(() -> AngelicaConfig.enableTESRJarCache) + .addRequiredMod(TargetedMod.THAUMCRAFT) + .addClientMixins( + "client.thaumcraft.MixinTileJarRenderer" + ) + ), + + ANGELICA_TESR_BEACON_CACHE(new MixinBuilder("Batch the vanilla beacon beam via the retained TESR mesh cache") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableTESRBeaconCache) + .addClientMixins( + "angelica.tesr.MixinTileEntityBeaconRenderer" + ) + ), + + ANGELICA_TESR_PROVIDER_DISPATCH(new MixinBuilder("Route TesrMeshProvider renderers through the batched mesh cache") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableTESRProviderDispatch) + .addClientMixins( + "angelica.tesr.MixinTileEntityRendererDispatcher" + ) + ), + + ANGELICA_TRACY(new MixinBuilder("Tracy profiler zones from vanilla Profiler sections") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaMod.tracyEnabled) + .addCommonMixins( + "angelica.tracy.MixinProfiler_Tracy" + , "angelica.tracy.MixinNetHandlerPlayServer_Tracy" + , "angelica.tracy.MixinMinecraftServer_Tracy" + ) + .addClientMixins( + "angelica.tracy.MixinMinecraft_Tracy" + , "angelica.tracy.MixinRenderGlobal_Tracy" + ) + ), + ANGELICA_ENABLE_DEBUG(new MixinBuilder() .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaMod.lwjglDebug) + .addClientMixins( + "angelica.debug.MixinSplashProgress" + ) + ), + ANGELICA_DEBUG_MARKERS(new MixinBuilder("RenderDoc/RGP debug groups + object labels") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaMod.lwjglDebug || CaptureGate.enabledAtStartup()) .addClientMixins( "angelica.debug.MixinProfiler" - , "angelica.debug.MixinSplashProgress" , "angelica.debug.MixinTextureManager" + , "celeritas.debug.MixinGLDebug" ) ), ANGELICA_DYNAMIC_LIGHTS(new MixinBuilder() @@ -168,7 +281,6 @@ public enum Mixins implements IMixins { ANGELICA_DEFERRED_TESSELLATOR_BATCH(new MixinBuilder("Deferred tessellator batching for particles to reduce draw calls") .setPhase(Phase.EARLY) - .setApplyIf(() -> AngelicaConfig.enableCeleritas) .addClientMixins("angelica.particles.MixinEffectRenderer_DeferredBatch")), // Not compatible with the lwjgl debug callbacks, so disable if that's enabled @@ -208,7 +320,6 @@ public enum Mixins implements IMixins { RENDERING_INFRASTRUCTURE(new MixinBuilder() .setPhase(Phase.EARLY) - .setApplyIf(() -> AngelicaConfig.enableCeleritas) .addClientMixins( "rendering.MixinBlock" , "rendering.MixinBlockFluidBase" @@ -239,11 +350,11 @@ public enum Mixins implements IMixins { CELERITAS(new MixinBuilder() .setPhase(Phase.EARLY) - .setApplyIf(() -> AngelicaConfig.enableCeleritas) .addClientMixins( "celeritas.terrain.MixinChunkProviderClient" , "celeritas.terrain.MixinMinecraft_ChunkUpdates" , "celeritas.terrain.MixinRenderGlobal" + , "celeritas.terrain.MixinRenderListManager" , "celeritas.terrain.MixinRenderSectionManager" , "celeritas.terrain.MixinWorldClient" , "celeritas.frustum.MixinClippingHelper" @@ -260,6 +371,10 @@ public enum Mixins implements IMixins { , "celeritas.biome_blending.MixinBlockLiquid" , "celeritas.threading.MixinForgeHooksClient" , "celeritas.terrain.MixinChunk" + , "celeritas.terrain.MixinRenderRegion" + , "celeritas.terrain.MixinSectionRenderDataStorage" + , "celeritas.terrain.MixinDefaultChunkRenderer" + , "celeritas.terrain.MixinDefaultChunkShaderInterface" ) ), @@ -267,7 +382,7 @@ public enum Mixins implements IMixins { .setPhase(Phase.EARLY) .setApplyIf(() -> { BlockLightProvider.freezeMixinConfig(); - return AngelicaConfig.enableCeleritas && BlockLightProvider.coloredLightEnabled(); + return BlockLightProvider.coloredLightEnabled(); }) .addClientMixins( "celeritas.light.MixinQuadLightData", @@ -373,7 +488,6 @@ public enum Mixins implements IMixins { ANGELICA_TEXTURE(new MixinBuilder() .setPhase(Phase.EARLY) - .setApplyIf(() -> AngelicaConfig.enableIris || AngelicaConfig.enableCeleritas) .addClientMixins( "angelica.textures.MixinTextureAtlasSprite" , "angelica.textures.MixinTextureUtil" @@ -426,7 +540,6 @@ public enum Mixins implements IMixins { FARSEEK_WORLDSLICE_COMPAT(new MixinBuilder("Let Farseek resolve celeritas' WorldSlice so Streams' water renders properly") .setPhase(Phase.LATE) .addRequiredMod(TargetedMod.FARSEEK) - .setApplyIf(() -> AngelicaConfig.enableCeleritas) .addClientMixins("client.farseek.MixinFarseekIBlockAccessValue")), SECURITYCRAFT_COMPAT(new MixinBuilder("Fix reflection in SecurityCraft for compat with Angelica") @@ -475,11 +588,6 @@ public enum Mixins implements IMixins { .setApplyIf(() -> AngelicaConfig.speedupAnimations) .addClientMixins("angelica.textures.ic2.MixinRenderLiquidCell")), - OPTIMIZE_TEXTURE_LOADING(new MixinBuilder() - .setPhase(Phase.EARLY) - .addClientMixins("angelica.textures.MixinTextureUtil_OptimizeMipmap") - .setApplyIf(() -> AngelicaConfig.optimizeTextureLoading)), - REPLACE_FFP(new MixinBuilder() .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.replaceFFPUploads) @@ -538,6 +646,12 @@ public enum Mixins implements IMixins { "MixinRenderBlocks" )) ), + BOP_FOG_BIOME_CACHE(new MixinBuilder() + .setPhase(Phase.LATE) + .addRequiredMod(TargetedMod.BIOMES_O_PLENTY) + .addClientMixins("client.biomesoplenty.MixinFogHandlerBiomeCache") + ), + NOTFINE_BOP_FOG(new MixinBuilder() .setPhase(Phase.LATE) .setApplyIf(() -> AngelicaConfig.enableNotFineFeatures) @@ -634,16 +748,6 @@ public enum Mixins implements IMixins { "MixinWorldRenderer" )) ), - MCPATCHER_FORGE_RENDERPASS_DISPLAYLIST(new MixinBuilder("RenderPass display list allocation increase") - .setPhase(Phase.EARLY) - .setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableCeleritas) - .addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_DisplayLists") - ), - MCPATCHER_FORGE_RENDERPASS_FEATURES(new MixinBuilder("RenderPass rendering features") - .setPhase(Phase.EARLY) - .setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableCeleritas) - .addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_Features") - ), MCPATCHER_FORGE_CUSTOM_COLORS(new MixinBuilder() .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.CustomColors.enabled) diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ChatLineFormattedAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ChatLineFormattedAccessor.java new file mode 100644 index 000000000..b004f2ccf --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ChatLineFormattedAccessor.java @@ -0,0 +1,7 @@ +package com.gtnewhorizons.angelica.mixins.interfaces; + +public interface ChatLineFormattedAccessor { + String angelica$getFormatted(long epoch); + + void angelica$setFormatted(String formatted, long epoch); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ITileEntityBoundingBoxCache.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ITileEntityBoundingBoxCache.java index 462e03c25..611fd8526 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ITileEntityBoundingBoxCache.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ITileEntityBoundingBoxCache.java @@ -6,4 +6,6 @@ public interface ITileEntityBoundingBoxCache { AxisAlignedBB angelica$getCachedRenderBoundingBox(); byte angelica$boundsClass(); + + byte angelica$passClass(); } diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderListManagerAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderListManagerAccessor.java new file mode 100644 index 000000000..cc7950e82 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderListManagerAccessor.java @@ -0,0 +1,5 @@ +package com.gtnewhorizons.angelica.mixins.interfaces; + +public interface RenderListManagerAccessor { + boolean angelica$hasOcclusionFutureInFlight(); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderSectionManagerAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderSectionManagerAccessor.java index 496068479..ce69f2691 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderSectionManagerAccessor.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/RenderSectionManagerAccessor.java @@ -2,10 +2,13 @@ package com.gtnewhorizons.angelica.mixins.interfaces; import it.unimi.dsi.fastutil.longs.Long2ReferenceMap; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; import java.util.concurrent.ConcurrentLinkedDeque; public interface RenderSectionManagerAccessor { Long2ReferenceMap angelica$getSectionByPosition(); ConcurrentLinkedDeque angelica$getAsyncSubmittedTasks(); + RenderRegionManager angelica$getRegions(); + float angelica$getSearchDistance(); } diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/SectionRenderDataStorageRegionAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/SectionRenderDataStorageRegionAccessor.java new file mode 100644 index 000000000..0985a3f89 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/SectionRenderDataStorageRegionAccessor.java @@ -0,0 +1,14 @@ +package com.gtnewhorizons.angelica.mixins.interfaces; + +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; + +public interface SectionRenderDataStorageRegionAccessor { + RenderRegion angelica$getRegion(); + void angelica$setRegion(RenderRegion region); + + int angelica$getPassIndex(); + void angelica$setPassIndex(int passIndex); + + /** Per-section meta slot indexed by localSectionIndex; null when the backend has no GPU culling. */ + int[] angelica$getSlotCache(); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java b/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java new file mode 100644 index 000000000..e9557af02 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java @@ -0,0 +1,86 @@ +package com.gtnewhorizons.angelica.profiling; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import it.unimi.dsi.fastutil.objects.Reference2IntMap; +import it.unimi.dsi.fastutil.objects.Reference2IntMaps; +import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.minecraft.client.Minecraft; + +public final class BailClassCounts { + public static final BailClassCounts MATERIAL = new BailClassCounts("tesr.bailCls.mat.", "BailMat"); + public static final BailClassCounts TEMPLATE = new BailClassCounts("tesr.bailCls.tmpl.", "BailTmpl"); + + private final String plotPrefix; + private final String label; + private final Reference2IntOpenHashMap> counts = new Reference2IntOpenHashMap<>(); + private final Reference2ObjectOpenHashMap, String> plotNames = new Reference2ObjectOpenHashMap<>(); + private String debugLine = ""; + + private BailClassCounts(String plotPrefix, String label) { + this.plotPrefix = plotPrefix; + this.label = label; + } + + public void add(Class cls) { + counts.addTo(cls == null ? Object.class : cls, 1); + } + + public void flushFrame(boolean plot) { + if (counts.isEmpty()) { + debugLine = ""; + return; + } + final boolean debugScreen = Minecraft.getMinecraft().gameSettings.showDebugInfo; + if (!plot && !debugScreen) { + debugLine = ""; + counts.clear(); + return; + } + Class a = null, b = null, c = null; + int an = 0, bn = 0, cn = 0; + final var it = Reference2IntMaps.fastIterator(counts); + while (it.hasNext()) { + final Reference2IntMap.Entry> entry = it.next(); + final int v = entry.getIntValue(); + if (plot) Tracy.plotInt(plotName(entry.getKey()), v); + if (v > an) { + c = b; cn = bn; + b = a; bn = an; + a = entry.getKey(); an = v; + } else if (v > bn) { + c = b; cn = bn; + b = entry.getKey(); bn = v; + } else if (v > cn) { + c = entry.getKey(); cn = v; + } + } + if (!debugScreen) { + debugLine = ""; + } else { + final StringBuilder sb = new StringBuilder(label).append(": "); + appendEntry(sb, a, an); + if (b != null) appendEntry(sb.append(", "), b, bn); + if (c != null) appendEntry(sb.append(", "), c, cn); + debugLine = sb.toString(); + } + counts.clear(); + } + + private String plotName(Class cls) { + String name = plotNames.get(cls); + if (name == null) { + name = plotPrefix + cls.getSimpleName(); + plotNames.put(cls, name); + } + return name; + } + + private void appendEntry(StringBuilder sb, Class cls, int count) { + sb.append(cls.getSimpleName()).append(" x").append(count); + } + + public String debugLine() { + return debugLine; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/GpuFrameLagMeter.java b/src/main/java/com/gtnewhorizons/angelica/profiling/GpuFrameLagMeter.java new file mode 100644 index 000000000..40a6a3d38 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/GpuFrameLagMeter.java @@ -0,0 +1,45 @@ +package com.gtnewhorizons.angelica.profiling; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import org.lwjgl.opengl.GL32; + +public final class GpuFrameLagMeter { + private static final int RING = 8; + private static final long[] syncs = new long[RING]; + private static final long[] submitNs = new long[RING]; + private static int head; + private static int tail; + private static final long P_GPU_LAG_NS = Tracy.plotHandle("gpuLagNs"); + + private GpuFrameLagMeter() {} + + public static void onFrame() { + if (!Tracy.ENABLED) return; + final RenderBackend rb = BackendManager.RENDER_BACKEND; + while (tail != head) { + final int slot = tail % RING; + final int status = rb.clientWaitSync(syncs[slot], 0, 0); + if (status != GL32.GL_ALREADY_SIGNALED && status != GL32.GL_CONDITION_SATISFIED) { + if (status == GL32.GL_WAIT_FAILED) { + rb.deleteSync(syncs[slot]); + tail++; + continue; + } + break; + } + Tracy.plotInt(P_GPU_LAG_NS, System.nanoTime() - submitNs[slot]); + rb.deleteSync(syncs[slot]); + tail++; + } + if (head - tail < RING) { + final long sync = rb.fenceSync(GL32.GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + if (sync != 0) { + syncs[head % RING] = sync; + submitNs[head % RING] = System.nanoTime(); + head++; + } + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/RenderClassTimings.java b/src/main/java/com/gtnewhorizons/angelica/profiling/RenderClassTimings.java new file mode 100644 index 000000000..132d97deb --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/RenderClassTimings.java @@ -0,0 +1,96 @@ +package com.gtnewhorizons.angelica.profiling; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2LongMap; +import it.unimi.dsi.fastutil.objects.Reference2LongMaps; +import it.unimi.dsi.fastutil.objects.Reference2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.minecraft.client.Minecraft; + +public final class RenderClassTimings { + public static final RenderClassTimings ENTITY = new RenderClassTimings("entity.cls.", "Entity"); + public static final RenderClassTimings SHADOW_ENTITY = new RenderClassTimings("shadow.entity.cls.", "ShadowEntity"); + public static final RenderClassTimings TESR = new RenderClassTimings("tesr.cls.", "TESR"); + + private static final long PLOT_THRESHOLD_NS = 20_000L; + + private final String plotPrefix; + private final String label; + private final Reference2LongOpenHashMap> nanos = new Reference2LongOpenHashMap<>(); + private final Reference2IntOpenHashMap> counts = new Reference2IntOpenHashMap<>(); + private final Reference2ObjectOpenHashMap, String> plotNames = new Reference2ObjectOpenHashMap<>(); + private String debugLine = ""; + + private RenderClassTimings(String plotPrefix, String label) { + this.plotPrefix = plotPrefix; + this.label = label; + } + + public void add(Class cls, long ns) { + nanos.addTo(cls, ns); + counts.addTo(cls, 1); + } + + public void flushFrame(boolean plot) { + if (nanos.isEmpty()) { + debugLine = ""; + return; + } + final boolean debugScreen = Minecraft.getMinecraft().gameSettings.showDebugInfo; + if (!plot && !debugScreen) { + debugLine = ""; + nanos.clear(); + counts.clear(); + return; + } + Class a = null, b = null, c = null; + long an = 0, bn = 0, cn = 0; + final var it = Reference2LongMaps.fastIterator(nanos); + while (it.hasNext()) { + final Reference2LongMap.Entry> entry = it.next(); + final long v = entry.getLongValue(); + if (plot && v >= PLOT_THRESHOLD_NS) { + Tracy.plotInt(plotName(entry.getKey()), v); + } + if (v > an) { + c = b; cn = bn; + b = a; bn = an; + a = entry.getKey(); an = v; + } else if (v > bn) { + c = b; cn = bn; + b = entry.getKey(); bn = v; + } else if (v > cn) { + c = entry.getKey(); cn = v; + } + } + if (a == null || !debugScreen) { + debugLine = ""; + } else { + final StringBuilder sb = new StringBuilder(label).append(": "); + appendEntry(sb, a, an); + if (b != null) appendEntry(sb.append(", "), b, bn); + if (c != null) appendEntry(sb.append(", "), c, cn); + debugLine = sb.toString(); + } + nanos.clear(); + counts.clear(); + } + + private String plotName(Class cls) { + String name = plotNames.get(cls); + if (name == null) { + name = plotPrefix + cls.getSimpleName(); + plotNames.put(cls, name); + } + return name; + } + + private void appendEntry(StringBuilder sb, Class cls, long ns) { + sb.append(cls.getSimpleName()).append(' ').append(ns / 1000).append("us x").append(counts.getInt(cls)); + } + + public String debugLine() { + return debugLine; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java b/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java new file mode 100644 index 000000000..011efeba5 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java @@ -0,0 +1,243 @@ +package com.gtnewhorizons.angelica.profiling; + +import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; +import com.gtnewhorizons.angelica.glsm.CaptureGate; +import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.culling.GpuIndirectMultiDrawEmitter; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; +import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; +import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; +import com.gtnewhorizons.angelica.rendering.celeritas.TerrainDrawStats; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; +import net.coderbot.iris.pipeline.ShadowRenderer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.WorldRenderer; +import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; + +public final class TracyFramePlots { + private static long lastChunkUpdates; + private static long lastDrawCalls, lastTexBindMisses, lastProgramSwitches, lastListPlaybacks; + private static long lastStreamedBytes, lastStreamDraws, lastOrphanFallbacks, lastStreamContiguous; + private static long lastSectionMetaBytes, lastRingWraps, lastVariantSwitches; + private static long lastTesrRebuilds, lastTesrRetainedDraws, lastTesrInstDraws, lastTesrInstInstances; + private static long lastTesrStreamedInstances, lastTesrPromotions, lastTesrCacheHits, lastTesrCacheMisses; + private static long lastBatcherParts, lastBatcherLiveFallbacks; + private static final long[] lastBails = new long[ModelPartBatcher.BailReason.VALUES.length]; + private static long lastSectionsUploaded, lastBytesUploaded; + private static int lastCullSubmitted; + + private static final long P_ALLOC_RATE = Tracy.plotHandle("allocRate", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_HEAP_USED = Tracy.plotHandle("heapUsed", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_CHUNK_UPDATES = Tracy.plotHandle("chunkUpdates"); + private static final long P_ENTITIES_RENDERED = Tracy.plotHandle("entitiesRendered"); + private static final long P_ENTITIES_TOTAL = Tracy.plotHandle("entitiesTotal"); + + private static final long P_GL_DRAW_CALLS = Tracy.plotHandle("gl.drawCalls"); + private static final long P_GL_TEX_BIND_MISSES = Tracy.plotHandle("gl.texBindMisses"); + private static final long P_GL_PROGRAM_SWITCHES = Tracy.plotHandle("gl.programSwitches"); + private static final long P_GL_LIST_PLAYBACKS = Tracy.plotHandle("gl.listPlaybacks"); + private static final long P_GL_STREAMED_BYTES = Tracy.plotHandle("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_GL_STREAM_DRAWS = Tracy.plotHandle("gl.streamDraws"); + private static final long P_GL_ORPHAN_FALLBACKS = Tracy.plotHandle("gl.orphanFallbacks"); + private static final long P_GL_STREAM_CONTIGUOUS = Tracy.plotHandle("gl.streamContiguous"); + private static final long P_GL_RING_WRAPS = Tracy.plotHandle("gl.ringWraps"); + private static final long P_GL_SECTION_META_BYTES = Tracy.plotHandle("gl.sectionMetaBytes", TracyBackend.PLOT_FORMAT_MEMORY); + + private static final long P_SHADOW_RELAY_FRAMES = Tracy.plotHandle("shadow.relayFrames"); + + private static final long P_TERRAIN_DRAW_COMMANDS = Tracy.plotHandle("terrain.drawCommands"); + private static final long P_TERRAIN_REGIONS_DRAWN = Tracy.plotHandle("terrain.regionsDrawn"); + private static final long P_VOX_ENCODERS = Tracy.plotHandle("voxelization.encoders"); + private static final long P_VOX_DISPATCHES = Tracy.plotHandle("voxelization.dispatches"); + private static final long P_VOX_REGIONS = Tracy.plotHandle("voxelization.regions"); + private static final long P_DRAW_ARENA_GROWTHS = Tracy.plotHandle("draw.arenaGrowths"); + private static final long P_DRAW_INDEX_BUFFER_GROWTHS = Tracy.plotHandle("draw.indexBufferGrowths"); + + private static final long P_CULL_COMMANDS_SUBMITTED = Tracy.plotHandle("cull.commandsSubmitted"); + private static final long P_CULL_REGIONS_DRAWN = Tracy.plotHandle("cull.regionsDrawn"); + private static final long P_CULL_MAX_REGION_COMMANDS = Tracy.plotHandle("cull.maxRegionCommands"); + + private static final long P_FFP_PRE_DRAW_CALLS = Tracy.plotHandle("ffp.preDrawCalls"); + private static final long P_FFP_BLOCK_WRITES = Tracy.plotHandle("ffp.blockWrites"); + private static final long P_FFP_BLOCK_SKIPS = Tracy.plotHandle("ffp.blockSkips"); + private static final long P_FFP_STAGED_MATRICES = Tracy.plotHandle("ffp.stagedMatrices"); + private static final long P_FFP_STAGED_LIGHTING = Tracy.plotHandle("ffp.stagedLighting"); + private static final long P_FFP_STAGED_FRAGMENT = Tracy.plotHandle("ffp.stagedFragment"); + private static final long P_FFP_STAGED_COLOR = Tracy.plotHandle("ffp.stagedColor"); + private static final long P_FFP_STAGED_NORMAL = Tracy.plotHandle("ffp.stagedNormal"); + private static final long P_FFP_STAGED_TEX_COORD = Tracy.plotHandle("ffp.stagedTexCoord"); + private static final long P_FFP_STAGED_LIGHTMAP = Tracy.plotHandle("ffp.stagedLightmap"); + private static final long P_FFP_STAGED_TEX_GEN = Tracy.plotHandle("ffp.stagedTexGen"); + private static final long P_FFP_STAGED_CLIP_PLANES = Tracy.plotHandle("ffp.stagedClipPlanes"); + private static final long P_FFP_STAGED_MISC = Tracy.plotHandle("ffp.stagedMisc"); + private static final long P_FFP_PROGRAMS = Tracy.plotHandle("ffp.programs"); + private static final long P_FFP_VARIANT_SWITCHES = Tracy.plotHandle("ffp.variantSwitches"); + + private static final long P_TESR_REBUILDS = Tracy.plotHandle("tesr.rebuilds"); + private static final long P_TESR_RETAINED_DRAWS = Tracy.plotHandle("tesr.retainedDraws"); + private static final long P_TESR_INSTANCED_DRAWS = Tracy.plotHandle("tesr.instancedDraws"); + private static final long P_TESR_INSTANCED_INSTANCES = Tracy.plotHandle("tesr.instancedInstances"); + private static final long P_TESR_STREAMED_INSTANCES = Tracy.plotHandle("tesr.streamedInstances"); + private static final long P_TESR_VOLATILE_PROMOTIONS = Tracy.plotHandle("tesr.volatilePromotions"); + private static final long P_TESR_RETAINED_BYTES = Tracy.plotHandle("tesr.retainedBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_TESR_BUFFER_SOURCE_BYTES = Tracy.plotHandle("tesr.bufferSourceBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_TESR_CACHE_HITS = Tracy.plotHandle("tesr.cacheHits"); + private static final long P_TESR_CACHE_MISSES = Tracy.plotHandle("tesr.cacheMisses"); + private static final long P_TESR_MODEL_PARTS = Tracy.plotHandle("tesr.modelParts"); + private static final long P_TESR_LIVE_FALLBACKS = Tracy.plotHandle("tesr.liveFallbacks"); + private static final long[] P_TESR_BAILS = bailHandles(); + + private static final long P_MESH_UPLOADED_SECTIONS = Tracy.plotHandle("mesh.uploadedSections"); + private static final long P_MESH_UPLOADED_BYTES = Tracy.plotHandle("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_MESH_META_SLOTS = Tracy.plotHandle("mesh.metaSlots"); + private static final long P_MT_QUEUE_DEPTH = Tracy.plotHandle("mtQueue.depth"); + private static final long P_MT_QUEUE_TASKS = Tracy.plotHandle("mtQueue.tasksRan"); + private static final long P_MT_QUEUE_LONGEST_US = Tracy.plotHandle("mtQueue.longestTaskUs"); + + private static final long P_QUEUE_DEPTH = Tracy.plotHandle("queue.depth"); + private static final long P_QUEUE_TASKS_RAN = Tracy.plotHandle("queue.tasksRan"); + private static final long P_QUEUE_TIME_NS = Tracy.plotHandle("queue.timeNs"); + + private static final long P_DYN_LIGHT_SOURCES = Tracy.plotHandle("dyn.lightSources"); + private static final long P_DYN_UPDATES = Tracy.plotHandle("dyn.updates"); + private static final long P_DYN_PENDING_REBUILDS = Tracy.plotHandle("dyn.pendingRebuilds"); + + private static long[] bailHandles() { + final ModelPartBatcher.BailReason[] reasons = ModelPartBatcher.BailReason.VALUES; + final long[] out = new long[reasons.length]; + for (int i = 0; i < reasons.length; i++) out[i] = Tracy.plotHandle(reasons[i].plotName); + return out; + } + + private TracyFramePlots() {} + + public static void onFrame(Minecraft mc) { + if (!Tracy.ENABLED) return; + + final boolean plots = CaptureGate.markersThisFrame; + + Tracy.plotAllocRate(P_ALLOC_RATE); + Tracy.plotGcStats(); + if (plots) { + final Runtime runtime = Runtime.getRuntime(); + Tracy.plotInt(P_HEAP_USED, runtime.totalMemory() - runtime.freeMemory()); + } + final int chunksUpdated = WorldRenderer.chunksUpdated; + Tracy.plotInt(P_CHUNK_UPDATES, chunksUpdated - lastChunkUpdates); + lastChunkUpdates = chunksUpdated; + if (mc.renderGlobal != null) { + Tracy.plotInt(P_ENTITIES_RENDERED, mc.renderGlobal.countEntitiesRendered); + } + if (mc.theWorld != null) { + Tracy.plotInt(P_ENTITIES_TOTAL, mc.theWorld.loadedEntityList.size()); + } + + lastDrawCalls = delta(P_GL_DRAW_CALLS, GLStateManager.drawCalls, lastDrawCalls); + lastTexBindMisses = delta(P_GL_TEX_BIND_MISSES, GLStateManager.texBindMisses, lastTexBindMisses); + lastProgramSwitches = delta(P_GL_PROGRAM_SWITCHES, GLStateManager.programSwitches, lastProgramSwitches); + lastListPlaybacks = delta(P_GL_LIST_PLAYBACKS, DisplayListManager.listPlaybacks, lastListPlaybacks); + lastStreamedBytes = delta(P_GL_STREAMED_BYTES, TessellatorStreamingDrawer.streamedBytes, lastStreamedBytes); + lastStreamDraws = delta(P_GL_STREAM_DRAWS, TessellatorStreamingDrawer.streamDraws, lastStreamDraws); + lastOrphanFallbacks = delta(P_GL_ORPHAN_FALLBACKS, TessellatorStreamingDrawer.orphanFallbacks, lastOrphanFallbacks); + lastStreamContiguous = delta(P_GL_STREAM_CONTIGUOUS, TessellatorStreamingDrawer.streamContiguous, lastStreamContiguous); + lastRingWraps = delta(P_GL_RING_WRAPS, TessellatorStreamingDrawer.ringWraps(), lastRingWraps); + lastSectionMetaBytes = delta(P_GL_SECTION_META_BYTES, GpuIndirectMultiDrawEmitter.sectionMetaBytes, lastSectionMetaBytes); + Tracy.plotInt(P_SHADOW_RELAY_FRAMES, ShadowRenderer.SHADOW_TERRAIN_RELAID ? 1 : 0); + Tracy.plotInt(P_TERRAIN_DRAW_COMMANDS, TerrainDrawStats.takeCommandsSubmitted()); + Tracy.plotInt(P_TERRAIN_REGIONS_DRAWN, TerrainDrawStats.takeRegionsDrawn()); + Tracy.plotInt(P_DRAW_ARENA_GROWTHS, IndirectMultiDrawEmitter.takeArenaGrowths()); + Tracy.plotInt(P_DRAW_INDEX_BUFFER_GROWTHS, SharedQuadIndexBuffer.takeGrowths()); + Tracy.plotInt(P_VOX_ENCODERS, SdlShadowVoxelizationSink.takeEncoders()); + Tracy.plotInt(P_VOX_DISPATCHES, SdlShadowVoxelizationSink.takeDispatches()); + Tracy.plotInt(P_VOX_REGIONS, SdlShadowVoxelizationSink.takeRegions()); + Tracy.plotInt(P_CULL_REGIONS_DRAWN, GpuIndirectMultiDrawEmitter.takeRegionsDrawn()); + Tracy.plotInt(P_CULL_MAX_REGION_COMMANDS, GpuIndirectMultiDrawEmitter.takeMaxRegionCommands()); + final int submitted = GpuIndirectMultiDrawEmitter.commandsSubmitted(); + Tracy.plotInt(P_CULL_COMMANDS_SUBMITTED, submitted - lastCullSubmitted); + lastCullSubmitted = submitted; + + final ShaderManager ffp = ShaderManager.getInstance(); + Tracy.plotInt(P_FFP_PRE_DRAW_CALLS, ffp.statLastFramePreDrawCalls()); + Tracy.plotInt(P_FFP_BLOCK_WRITES, ffp.statLastFrameBlockWrites()); + Tracy.plotInt(P_FFP_BLOCK_SKIPS, ffp.statLastFrameBlockSkips()); + Tracy.plotInt(P_FFP_STAGED_MATRICES, ffp.statLastFrameStagedMatrices()); + Tracy.plotInt(P_FFP_STAGED_LIGHTING, ffp.statLastFrameStagedLighting()); + Tracy.plotInt(P_FFP_STAGED_FRAGMENT, ffp.statLastFrameStagedFragment()); + Tracy.plotInt(P_FFP_STAGED_COLOR, ffp.statLastFrameStagedColor()); + Tracy.plotInt(P_FFP_STAGED_NORMAL, ffp.statLastFrameStagedNormal()); + Tracy.plotInt(P_FFP_STAGED_TEX_COORD, ffp.statLastFrameStagedTexCoord()); + Tracy.plotInt(P_FFP_STAGED_LIGHTMAP, ffp.statLastFrameStagedLightmap()); + Tracy.plotInt(P_FFP_STAGED_TEX_GEN, ffp.statLastFrameStagedTexGen()); + Tracy.plotInt(P_FFP_STAGED_CLIP_PLANES, ffp.statLastFrameStagedClipPlanes()); + Tracy.plotInt(P_FFP_STAGED_MISC, ffp.statLastFrameStagedMisc()); + Tracy.plotInt(P_FFP_PROGRAMS, ffp.statProgramCount()); + lastVariantSwitches = delta(P_FFP_VARIANT_SWITCHES, ShaderManager.variantSwitches, lastVariantSwitches); + + final TesrBatchRenderer tesr = TesrBatchRenderer.INSTANCE; + final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE; + + lastTesrRebuilds = delta(P_TESR_REBUILDS, tesr.statRebuilds(), lastTesrRebuilds); + lastTesrRetainedDraws = delta(P_TESR_RETAINED_DRAWS, tesr.statRetainedDraws(), lastTesrRetainedDraws); + lastTesrInstDraws = delta(P_TESR_INSTANCED_DRAWS, tesr.statInstancedDraws(), lastTesrInstDraws); + lastTesrInstInstances = delta(P_TESR_INSTANCED_INSTANCES, tesr.statInstancedInstances(), lastTesrInstInstances); + lastTesrStreamedInstances = delta(P_TESR_STREAMED_INSTANCES, tesr.statStreamedInstances(), lastTesrStreamedInstances); + lastTesrPromotions = delta(P_TESR_VOLATILE_PROMOTIONS, tesr.statVolatilePromotions(), lastTesrPromotions); + if (plots) { + Tracy.plotInt(P_TESR_RETAINED_BYTES, tesr.statRetainedBytes()); + Tracy.plotInt(P_TESR_BUFFER_SOURCE_BYTES, tesr.statBufferSourceBytes()); + } + lastTesrCacheHits = delta(P_TESR_CACHE_HITS, AngelicaTesrMeshCache.cacheHits, lastTesrCacheHits); + lastTesrCacheMisses = delta(P_TESR_CACHE_MISSES, AngelicaTesrMeshCache.cacheMisses, lastTesrCacheMisses); + lastBatcherParts = delta(P_TESR_MODEL_PARTS, batcher.statParts(), lastBatcherParts); + lastBatcherLiveFallbacks = delta(P_TESR_LIVE_FALLBACKS, batcher.statLiveFallbacks(), lastBatcherLiveFallbacks); + for (final ModelPartBatcher.BailReason reason : ModelPartBatcher.BailReason.VALUES) { + final int i = reason.ordinal(); + lastBails[i] = delta(P_TESR_BAILS[i], batcher.statBail(reason), lastBails[i]); + } + + lastSectionsUploaded = delta(P_MESH_UPLOADED_SECTIONS, RenderRegionManager.getSectionsUploaded(), lastSectionsUploaded); + lastBytesUploaded = delta(P_MESH_UPLOADED_BYTES, RenderRegionManager.getBytesUploaded(), lastBytesUploaded); + Tracy.plotInt(P_MESH_META_SLOTS, GpuCulling.sectionMeta().getHighWaterMark()); + Tracy.plotInt(P_MT_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth()); + Tracy.plotInt(P_MT_QUEUE_TASKS, AngelicaRenderQueue.getLastFrameTasksRan()); + Tracy.plotInt(P_MT_QUEUE_LONGEST_US, AngelicaRenderQueue.getLastFrameLongestTaskNs() / 1000); + final CeleritasWorldRenderer cwr = CeleritasWorldRenderer.getInstanceOrNull(); + if (plots && cwr != null && cwr.isActive()) { + cwr.getRenderSectionManager().tracyPlots(); + } + + Tracy.plotInt(P_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth()); + Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan()); + Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs()); + + if (DynamicLights.isEnabled()) { + final DynamicLights dl = DynamicLights.get(); + Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount()); + Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount()); + if (DynamicLights.FrustumCullingEnabled) { + Tracy.plotInt(P_DYN_PENDING_REBUILDS, dl.getChunkRebuildManager().getPendingCount()); + } + } + + RenderClassTimings.ENTITY.flushFrame(plots); + RenderClassTimings.SHADOW_ENTITY.flushFrame(plots); + RenderClassTimings.TESR.flushFrame(plots); + BailClassCounts.MATERIAL.flushFrame(plots); + BailClassCounts.TEMPLATE.flushFrame(plots); + } + + private static long delta(long handle, long now, long last) { + Tracy.plotInt(handle, now - last); + return now; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java index ef93e63d3..a080227f9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java +++ b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.proxy; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID; import java.lang.management.ManagementFactory; @@ -41,9 +42,11 @@ import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat; import com.gtnewhorizons.angelica.compat.mojang.CompatMathHelper; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.config.CompatConfig; import com.gtnewhorizons.angelica.config.ConfigMigrator; import com.gtnewhorizons.angelica.debug.F3Direction; +import com.gtnewhorizons.angelica.debug.flyby.FlybyRunner; import com.gtnewhorizons.angelica.debug.FrametimeGraph; import com.gtnewhorizons.angelica.debug.TPSGraph; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; @@ -111,6 +114,7 @@ public final class ClientProxy extends CommonProxy { FMLCommonHandler.instance().bus().register(this); MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(new EmissiveTextureAutoloader()); + MinecraftForge.EVENT_BUS.register(new AngelicaTesrMeshCache.ReloadListener()); ModelRegistry.registerModid(MOD_ID); blockError = new BlockError(); } @@ -122,12 +126,8 @@ public final class ClientProxy extends CommonProxy { if (AngelicaConfig.enableHudCaching) { HUDCaching.init(); } - if (AngelicaConfig.enableCeleritas) { - CeleritasSetup.ensureInitialized(); - MinecraftForge.EVENT_BUS.register(CeleritasDebugScreenHandler.INSTANCE); - } else { - LOGGER.info("Celeritas is disabled, skipping initialization from init()"); - } + CeleritasSetup.ensureInitialized(); + MinecraftForge.EVENT_BUS.register(CeleritasDebugScreenHandler.INSTANCE); if (AngelicaConfig.enableIris) { IrisGLSMBridge.register(); MinecraftForge.EVENT_BUS.register(IrisDebugScreenHandler.INSTANCE); @@ -149,6 +149,7 @@ public final class ClientProxy extends CommonProxy { if (AngelicaConfig.enableZoom) { Zoom.init(); } + AngelicaConfig.applyGpuCullingMode(); if (AngelicaConfig.enableDynamicLights) { EntityLightConfig.init(new java.io.File(mc.mcDataDir, "config")); } @@ -157,9 +158,12 @@ public final class ClientProxy extends CommonProxy { BlockRenderListManager.registerReloadListener(); } - // Register debug commands in dev environment only + // Debug tooling if (!AngelicaClientTweaker.isObfEnv()) { ClientCommandHandler.instance.registerCommand(new AngelicaCommand()); + + FMLCommonHandler.instance().bus().register(FlybyRunner.INSTANCE); + FlybyRunner.INSTANCE.startFromProperties(); } } @@ -167,7 +171,7 @@ public final class ClientProxy extends CommonProxy { public void postInit(FMLPostInitializationEvent event) { super.postInit(event); - if (ModStatus.isLotrLoaded && AngelicaConfig.enableCeleritas && CompatConfig.fixLotr) { + if (ModStatus.isLotrLoaded && CompatConfig.fixLotr) { try { final Class lotrRendering = Class.forName("lotr.common.coremod.LOTRReplacedMethods$BlockRendering"); ReflectionHelper.setPrivateValue(lotrRendering, null, new ConcurrentHashMap<>(), "naturalBlockClassTable"); @@ -190,23 +194,22 @@ public final class ClientProxy extends CommonProxy { LOGGER.info("World loaded - Enabling GLSM Cache"); } - if (AngelicaConfig.enableCeleritas) { - ChunkTaskRegistry.reset(); - ChunkTaskRegistry.registerProvider(DefaultChunkTaskProvider.INSTANCE); - ChunkTaskRegistry.registerProvider(ThreadedChunkTaskProvider.INSTANCE); + ChunkTaskRegistry.reset(); + ChunkTaskRegistry.registerProvider(DefaultChunkTaskProvider.INSTANCE); + ChunkTaskRegistry.registerProvider(ThreadedChunkTaskProvider.INSTANCE); - // Register all blocks. Because blockids are unique to a world, this must be done each load - GameData.getBlockRegistry().typeSafeIterable().forEach(o -> { - AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, true, true); - AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, false, true); - }); - } + // Register all blocks. Because blockids are unique to a world, this must be done each load + GameData.getBlockRegistry().typeSafeIterable().forEach(o -> { + AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, true, true); + AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, false, true); + }); } @SubscribeEvent public void onWorldUnload(WorldEvent.Unload event) { if (!event.world.isRemote) return; DynamicLights.get().removeAllLightSources(); + GpuCulling.onWorldUnload(); } float lastIntegratedTickTime; diff --git a/src/main/java/com/gtnewhorizons/angelica/render/PanoramaRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/PanoramaRenderer.java index ec7c4908b..970aadb86 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/PanoramaRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/PanoramaRenderer.java @@ -277,9 +277,10 @@ public class PanoramaRenderer { GLStateManager.glBindVertexArray(0); blitProgram.unbind(); - GLStateManager.enableDepthTest(); - GLStateManager.enableCull(); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); GLStateManager.enableBlend(); + GLStateManager.enableTexture(); } private void drawCubeFaces(int panoramaTimer, float partialTicks, ResourceLocation[] panoramaPaths, Minecraft mc) { diff --git a/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java index 4f63e1403..86d781872 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java @@ -43,7 +43,7 @@ public final class SelectionBoxRenderer { private SelectionBoxRenderer() {} public static void init() { - final boolean needsGS = GLStateManager.wideLineEmulationEnabled; + final boolean needsGS = GLStateManager.wideLineEmulationEnabled && GLStateManager.supportsGeometryShaders(); final GlShader vs = ShaderLoader.loadShader(ShaderType.VERTEX, "angelica:selection_box.vert.glsl", ShaderConstants.EMPTY); final GlShader fs = ShaderLoader.loadShader(ShaderType.FRAGMENT, "angelica:selection_box.frag.glsl", ShaderConstants.EMPTY); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaRenderQueue.java b/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaRenderQueue.java index 6bfbf6687..c07f9b123 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaRenderQueue.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaRenderQueue.java @@ -15,6 +15,7 @@ public class AngelicaRenderQueue { // Metrics private static volatile int lastFrameTasksRan = 0; private static volatile long lastFrameTimeNs = 0; + private static volatile long lastFrameLongestTaskNs = 0; public static int getQueueDepth() { return TASKS.size(); @@ -28,9 +29,14 @@ public class AngelicaRenderQueue { return lastFrameTimeNs; } - public static void recordFrameStats(int tasksRan, long timeNs) { + public static long getLastFrameLongestTaskNs() { + return lastFrameLongestTaskNs; + } + + public static void recordFrameStats(int tasksRan, long timeNs, long longestTaskNs) { lastFrameTasksRan = tasksRan; lastFrameTimeNs = timeNs; + lastFrameLongestTaskNs = longestTaskNs; } private static final Executor EXECUTOR = (runnable) -> { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/TileEntityRenderBoundsRegistry.java b/src/main/java/com/gtnewhorizons/angelica/rendering/TileEntityRenderBoundsRegistry.java index 7d30e329c..41cb65339 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/TileEntityRenderBoundsRegistry.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/TileEntityRenderBoundsRegistry.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering; import it.unimi.dsi.fastutil.objects.Reference2ByteOpenHashMap; +import net.minecraft.launchwrapper.Launch; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; @@ -16,12 +17,25 @@ public final class TileEntityRenderBoundsRegistry { public static final byte INFINITE = 2; public static final byte DYNAMIC = 3; + public static final byte PASS0_ONLY = 1; + public static final byte PASS_OVERRIDES = 2; + + private static final byte NOT_OVERRIDDEN = 1; + private static final byte OVERRIDDEN = 2; + private static final Reference2ByteOpenHashMap> classRegistry = new Reference2ByteOpenHashMap<>(); + private static final Reference2ByteOpenHashMap> passClassRegistry = new Reference2ByteOpenHashMap<>(); + private static final Reference2ByteOpenHashMap> distanceOverrideRegistry = new Reference2ByteOpenHashMap<>(); private static final Set dynamicClassNames = ConcurrentHashMap.newKeySet(); + private static final String[] SHOULD_RENDER_IN_PASS_NAMES = { "shouldRenderInPass" }; + private static String[] distanceFromNames; + static { classRegistry.defaultReturnValue(UNKNOWN); + passClassRegistry.defaultReturnValue(UNKNOWN); + distanceOverrideRegistry.defaultReturnValue(UNKNOWN); } private TileEntityRenderBoundsRegistry() {} @@ -60,9 +74,71 @@ public final class TileEntityRenderBoundsRegistry { return result; } + public static boolean overridesMethod(Class clazz, Class base, String[] candidateNames, Class... params) { + for (String name : candidateNames) { + try { + return clazz.getMethod(name, params).getDeclaringClass() != base; + } catch (NoSuchMethodException ignored) { + } catch (Throwable t) { + return true; + } + } + return true; + } + + private static String[] distanceFromNames() { + String[] names = distanceFromNames; + if (names == null) { + String resolved; + try { + resolved = Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment")) ? "getDistanceFrom" : "func_145835_a"; + } catch (Throwable t) { + resolved = "getDistanceFrom"; + } + distanceFromNames = names = new String[] { resolved }; + } + return names; + } + + public static byte classifyPass(TileEntity te) { + final Class clazz = te.getClass(); + synchronized (passClassRegistry) { + final byte cached = passClassRegistry.getByte(clazz); + if (cached != UNKNOWN) return cached; + } + + final byte result = overridesMethod(clazz, TileEntity.class, SHOULD_RENDER_IN_PASS_NAMES, int.class) + ? PASS_OVERRIDES : PASS0_ONLY; + + synchronized (passClassRegistry) { + passClassRegistry.put(clazz, result); + } + return result; + } + + public static boolean overridesGetDistanceFrom(Class clazz) { + synchronized (distanceOverrideRegistry) { + final byte cached = distanceOverrideRegistry.getByte(clazz); + if (cached != UNKNOWN) return cached == OVERRIDDEN; + } + + final boolean overrides = overridesMethod(clazz, TileEntity.class, distanceFromNames(), double.class, double.class, double.class); + + synchronized (distanceOverrideRegistry) { + distanceOverrideRegistry.put(clazz, overrides ? OVERRIDDEN : NOT_OVERRIDDEN); + } + return overrides; + } + public static void clear() { synchronized (classRegistry) { classRegistry.clear(); } + synchronized (passClassRegistry) { + passClassRegistry.clear(); + } + synchronized (distanceOverrideRegistry) { + distanceOverrideRegistry.clear(); + } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java new file mode 100644 index 000000000..4e92af010 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData; + +import java.util.Arrays; + +public class AngelicaBuiltRenderSectionData extends MinecraftBuiltRenderSectionData { + public static final float[] EMPTY_BOUNDS = new float[0]; + + public float[] culledBlockEntityBounds = EMPTY_BOUNDS; + + public double maxTeRenderDistSq = Double.POSITIVE_INFINITY; + + public int cullEpoch = -1; + public int cullVerdict; + + public static void packSectionLocalBounds(FloatArrayList out, AxisAlignedBB aabb, int originX, int originY, int originZ) { + out.add((float) (aabb.minX - originX)); + out.add((float) (aabb.minY - originY)); + out.add((float) (aabb.minZ - originZ)); + out.add((float) (aabb.maxX - originX)); + out.add((float) (aabb.maxY - originY)); + out.add((float) (aabb.maxZ - originZ)); + } + + @Override + public boolean equals(Object o) { + if (!super.equals(o)) return false; + final AngelicaBuiltRenderSectionData other = (AngelicaBuiltRenderSectionData) o; + return maxTeRenderDistSq == other.maxTeRenderDistSq && Arrays.equals(culledBlockEntityBounds, other.culledBlockEntityBounds); + } + + @Override + public int hashCode() { + int result = 31 * super.hashCode() + Arrays.hashCode(culledBlockEntityBounds); + return 31 * result + Double.hashCode(maxTeRenderDistSq); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuildContext.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuildContext.java index 5cbac9b83..736a1a98d 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuildContext.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuildContext.java @@ -12,6 +12,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVert import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache; import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider; import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice; +import it.unimi.dsi.fastutil.floats.FloatArrayList; import lombok.Getter; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.vertices.ExtendedDataHelper; @@ -52,6 +53,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext { private final SmoothLightPipeline smoothLightPipeline; private final FlatLightPipeline flatLightPipeline; private final QuadLightData quadLightData = new QuadLightData(); + @Getter private final FloatArrayList teBoundsScratch = new FloatArrayList(); private final VertexArrayQuadView quadView; private final boolean hasColoredLight; private final float[] tintResult = new float[3]; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java index 8047e4851..d17813d8c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import com.gtnewhorizons.angelica.rendering.StateAwareTessellator; import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry; @@ -9,6 +10,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHold import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext; import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVertexEncoder; import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; +import it.unimi.dsi.fastutil.floats.FloatArrayList; import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; @@ -17,10 +19,10 @@ import net.coderbot.iris.vertices.ExtendedDataHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockDoublePlant; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; @@ -35,7 +37,6 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput; import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; -import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; @@ -51,6 +52,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask { + private static final Tracy.ZoneId Z_MESH_SECTION = Tracy.zoneId("meshSection"); + private static final Tracy.ZoneId Z_MESH_DEFERRED = Tracy.zoneId("meshDeferred"); + private static final Tracy.ZoneId Z_MESH_FINALIZE = Tracy.zoneId("meshFinalize"); + protected final RenderSection render; protected final int buildTime; protected final Vector3d camera; @@ -88,7 +93,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask renderData = new MinecraftBuiltRenderSectionData<>(); + final AngelicaBuiltRenderSectionData renderData = new AngelicaBuiltRenderSectionData(); final SectionVisibilityBuilder occluder = new SectionVisibilityBuilder(); final ChunkBuildBuffers buffers = buildContext.buffers; @@ -109,6 +114,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap(); - final net.minecraft.world.World mcWorld = Minecraft.getMinecraft().theWorld; + final World mcWorld = Minecraft.getMinecraft().theWorld; final long currentTick = mcWorld != null ? mcWorld.getTotalWorldTime() : 0L; final boolean threaded = isThreaded(); final List deferredBlocks = threaded ? new ArrayList<>() : null; + final FloatArrayList culledBounds = buildContext.getTeBoundsScratch(); + culledBounds.clear(); + double maxTeRenderDistSq = 0; + final RenderBlocks renderBlocks = new RenderBlocks(region); for (int y = minY; y < maxY; y++) { @@ -151,11 +161,11 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask maxTeRenderDistSq) maxTeRenderDistSq = teDistSq; + } } } @@ -213,18 +239,37 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask meshes = - BuiltSectionMeshParts.groupFromBuildBuffers(buffers, + if (Tracy.ENABLED) Tracy.beginZone(Z_MESH_FINALIZE); + final Reference2ReferenceMap meshes; + try { + meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers, (float) camera.x - minX, (float) camera.y - minY, (float) camera.z - minZ); + renderData.visibilityData = occluder.computeVisibilityEncoding(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } if (!meshes.isEmpty()) { renderData.hasBlockGeometry = true; + if (Tracy.ENABLED) { + long meshBytes = 0; + for (BuiltSectionMeshParts parts : meshes.values()) { + if (parts.vertexBuffer() != null) meshBytes += parts.vertexBuffer().getLength(); + } + Tracy.zoneValue(meshBytes); + } } - renderData.visibilityData = occluder.computeVisibilityEncoding(); + renderData.culledBlockEntityBounds = culledBounds.isEmpty() ? AngelicaBuiltRenderSectionData.EMPTY_BOUNDS : culledBounds.toFloatArray(); + renderData.maxTeRenderDistSq = maxTeRenderDistSq; SmoothBiomeColorCache.clearActiveCache(); tessellator.setTranslation(0, 0, 0); @@ -240,6 +285,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask irisProgram; private boolean usingIrisProgram; private int rgssSampler; private boolean rgssSamplerResolved; private boolean rgssSamplerBound; + private int regionIndex; public AngelicaChunkRenderer(RenderDevice device, RenderPassConfiguration renderPassConfiguration) { super(device, renderPassConfiguration, createEmitter()); @@ -50,16 +66,28 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { } private static MultiDrawEmitter createEmitter() { - MultiDrawMode mode = ClientProxy.options().advanced.multiDrawMode; + final MultiDrawMode configured = ClientProxy.options().advanced.multiDrawMode; + final MultiDrawMode mode = MultiDrawModeResolver.resolve(); - if (mode == MultiDrawMode.INDIRECT) { - boolean supported = GLStateManager.capabilities != null && (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_multi_draw_indirect); - if (!supported) { + if (mode != configured) { + if (mode == MultiDrawMode.INDIRECT) { + AngelicaMod.LOGGER.info("Backend requires indirect draw; {} -> INDIRECT", configured); + } else { AngelicaMod.LOGGER.warn("Indirect multi-draw not supported (requires GL 4.3 / ARB_multi_draw_indirect), falling back to Direct"); - mode = MultiDrawMode.DIRECT; } } + if (BackendManager.RENDER_BACKEND.isIndirectRequired() && mode != MultiDrawMode.INDIRECT) { + throw new IllegalStateException("Indirect multi-draw was required by the backend but resolved mode is " + mode); + } + + final GpuCulling.Availability availability = GpuCulling.availability(); + if (availability == GpuCulling.Availability.AVAILABLE) { + AngelicaMod.LOGGER.info("Compute-driven chunk culling available, mode={}", GpuCulling.mode()); + return new GpuIndirectMultiDrawEmitter(GpuCulling.culler(), GpuCulling.sectionMeta()); + } + AngelicaMod.LOGGER.warn("GPU culling unavailable ({}); terrain will use CPU culling", availability); + return switch (mode) { case DIRECT -> new DirectMultiDrawEmitter(); case INDIRECT -> new IndirectMultiDrawEmitter(); @@ -74,27 +102,33 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { @Override protected void begin(TerrainRenderPass pass) { - final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider(); + this.regionIndex = 0; + if (Tracy.ENABLED) Tracy.beginZone(Z_CHUNK_BEGIN); + try { + final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider(); - // Check if Iris shaders are active and we have an override - if (provider != null && provider.isShadersEnabled()) { - final GlProgram override = provider.getShaderOverride(pass); - if (override != null) { - pass.startDrawing(); - override.bind(); - override.getInterface().setupState(pass); - this.activeProgram = (GlProgram) override; - this.irisProgram = override; - this.usingIrisProgram = true; - return; + // Check if Iris shaders are active and we have an override + if (provider != null && provider.isShadersEnabled()) { + final GlProgram override = provider.getShaderOverride(pass); + if (override != null) { + pass.startDrawing(); + override.bind(); + override.getInterface().setupState(pass); + this.activeProgram = (GlProgram) override; + this.irisProgram = override; + this.usingIrisProgram = true; + return; + } } - } - // Fall back to default shader - this.usingIrisProgram = false; - this.irisProgram = null; - super.begin(pass); - bindRgssSampler(); + // Fall back to default shader + this.usingIrisProgram = false; + this.irisProgram = null; + super.begin(pass); + bindRgssSampler(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } @Override @@ -155,10 +189,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { @Override protected GlProgram createShader(String path, ChunkShaderOptions options) { - if (this.enableLegacyGLPatches) { - return super.createShader(path, options); - } - final ShaderConstants constants = options.constants(); final List loadedShaders = new ArrayList<>(); @@ -179,6 +209,52 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer { } } + @Override + protected void drawRegion(ChunkShaderInterface shader, CommandList commandList, RenderRegion region, + CameraTransform camera, long timestamp) { + if (Tracy.ENABLED) Tracy.beginZone(regionIndex == 0 ? Z_CHUNK_REGION_FIRST : Z_CHUNK_REGION); + try { + regionIndex++; + super.drawRegion(shader, commandList, region, camera, timestamp); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + @Override + protected void assembleRegion(DrawCommandSink sink, RenderRegion region, SectionRenderDataStorage storage, + ChunkRenderList renderList, CameraTransform occlusionCamera, + TerrainRenderPass renderPass, boolean useBlockFaceCulling) { + if (getEmitter() instanceof GpuIndirectMultiDrawEmitter gpu && gpu.isComputeActiveThisPass()) { + gpu.prepareRegion(region); + return; + } + + if (Tracy.ENABLED) Tracy.beginZone(Z_CHUNK_ASSEMBLE_REGION); + try { + super.assembleRegion(sink, region, storage, renderList, occlusionCamera, renderPass, useBlockFaceCulling); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + @Override + protected void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) { + if (Tracy.ENABLED) { + final MultiDrawEmitter emitter = getEmitter(); + // The compute path reports itself through GpuIndirectMultiDrawEmitter; counting it here too double-counts. + if (!(emitter instanceof GpuIndirectMultiDrawEmitter gpu && gpu.isComputeActiveThisPass())) { + TerrainDrawStats.recordBatch(emitter.getPendingCommandCount()); + } + Tracy.beginZone(Z_CHUNK_EXECUTE_BATCH); + } + try { + super.executeBatch(commandList, tessellation, primitiveType); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + @Override protected boolean useBlockFaceCulling() { return IrisShaderProviderHolder.shouldUseFaceCulling(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderSectionManager.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderSectionManager.java index caea66f65..ee99e4841 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderSectionManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderSectionManager.java @@ -3,6 +3,9 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.cardinalstar.cubicchunks.world.ICubicWorld; import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import com.gtnewhorizons.angelica.mixins.interfaces.RenderListManagerAccessor; import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; @@ -40,6 +43,20 @@ import java.util.concurrent.locks.LockSupport; import java.util.function.BooleanSupplier; public class AngelicaRenderSectionManager extends RenderSectionManager { + private static final long P_MESH_REGIONS = Tracy.plotHandle("mesh.regions"); + private static final long P_MESH_VISIBLE_CHUNKS = Tracy.plotHandle("mesh.visibleChunks"); + private static final long P_SHADOW_REGIONS = Tracy.plotHandle("shadow.regions"); + private static final long P_SHADOW_VISIBLE_CHUNKS = Tracy.plotHandle("shadow.visibleChunks"); + private static final long P_MESH_SCHEDULED_JOBS = Tracy.plotHandle("mesh.scheduledJobs"); + private static final long P_MESH_BUSY_THREADS = Tracy.plotHandle("mesh.busyThreads"); + private static final long P_MESH_DEVICE_USED = Tracy.plotHandle("mesh.deviceUsed", TracyBackend.PLOT_FORMAT_MEMORY); + private static final long P_MESH_DEVICE_ALLOCATED = Tracy.plotHandle("mesh.deviceAllocated", TracyBackend.PLOT_FORMAT_MEMORY); + + private static final Tracy.ZoneId Z_BIOME_REBUILDS = Tracy.zoneId("biomeRebuilds", Tracy.COLOR_TERRAIN); + private static final Tracy.ZoneId Z_GRAPH_SEARCH = Tracy.zoneId("graphSearch", Tracy.COLOR_TERRAIN); + private static final Tracy.ZoneId Z_SECTION_UPLOAD = Tracy.zoneId("sectionUpload", Tracy.COLOR_TERRAIN); + private static final Tracy.ZoneId Z_SHADOW_GRAPH_WAIT = Tracy.zoneId("shadowGraphWait", Tracy.COLOR_TERRAIN); + private boolean initialCameraSectionReady = false; private final WorldClient world; @@ -91,6 +108,9 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { @Override public void update(Viewport positionedViewport, int frame, boolean spectator) { + if (isInShadowPass() && !needsUpdate()) { + return; + } if (!isInShadowPass() && !initialCameraSectionReady) { var origin = positionedViewport.getChunkCoord(); long key = PositionUtil.packSection(origin.x(), origin.y(), origin.z()); @@ -179,24 +199,47 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { if (this.biomeRebuildColumns.isEmpty()) { return; } - final int sectionCountY = this.world.getHeight() >> 4; - for (final LongIterator it = this.biomeRebuildColumns.iterator(); it.hasNext(); ) { - final long column = it.nextLong(); - final int cx = PositionUtil.unpackChunkX(column); - final int cz = PositionUtil.unpackChunkZ(column); - for (int cy = 0; cy < sectionCountY; cy++) { - this.sectionCache.invalidate(cx, cy, cz); - this.scheduleRebuild(cx, cy, cz, false); + if (Tracy.ENABLED) Tracy.beginZone(Z_BIOME_REBUILDS); + try { + final int sectionCountY = this.world.getHeight() >> 4; + for (final LongIterator it = this.biomeRebuildColumns.iterator(); it.hasNext(); ) { + final long column = it.nextLong(); + final int cx = PositionUtil.unpackChunkX(column); + final int cz = PositionUtil.unpackChunkZ(column); + for (int cy = 0; cy < sectionCountY; cy++) { + this.sectionCache.invalidate(cx, cy, cz); + this.scheduleRebuild(cx, cy, cz, false); + } } + this.biomeRebuildColumns.clear(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); } - this.biomeRebuildColumns.clear(); } @Override public void updateChunks(boolean updateImmediately) { + if (isInShadowPass()) { + return; + } this.sectionCache.cleanup(); this.flushBiomeRebuilds(); - super.updateChunks(updateImmediately); + if (Tracy.ENABLED) Tracy.beginZone(Z_GRAPH_SEARCH); + try { + super.updateChunks(updateImmediately); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + @Override + public void uploadChunks() { + if (Tracy.ENABLED) Tracy.beginZone(Z_SECTION_UPLOAD); + try { + super.uploadChunks(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } @Override @@ -224,6 +267,20 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { } } + public boolean preSubmitShadowGraphUpdate(Viewport viewport, int frame, boolean spectator) { + if (this.shadowRenderListManager == null || !this.shadowRenderListManager.isNeedsUpdate()) return false; + if (((RenderListManagerAccessor) this.shadowRenderListManager).angelica$hasOcclusionFutureInFlight()) return false; + + final RenderSectionManagerAccessor self = (RenderSectionManagerAccessor) this; + final int targetQueueSize = shouldRespectUpdateTaskQueueSizeLimit() ? (int) Math.min(Integer.MAX_VALUE, (long) getBuilder().getTargetQueueSize() * 10) : Integer.MAX_VALUE; + this.shadowRenderListManager.startGraphUpdate(viewport, frame, self.angelica$getRegions().getRegionIdsLength(), self.angelica$getSearchDistance(), shouldUseOcclusionCulling(viewport, spectator), targetQueueSize); + return true; + } + + public boolean isShadowGraphDirty() { + return this.shadowRenderListManager != null && this.shadowRenderListManager.isNeedsUpdate(); + } + @Override public Collection getDebugStrings() { List list = new ArrayList<>(super.getDebugStrings()); @@ -252,7 +309,12 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { public void renderLayer(ChunkRenderMatrices matrices, TerrainRenderPass pass, CameraTransform occlusionCamera, CameraTransform camera) { // Shadow pass graph update is async - must wait for it to complete before rendering if (IrisShaderProviderHolder.isShadowPass()) { - finishAllGraphUpdates(); + if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_GRAPH_WAIT); + try { + finishAllGraphUpdates(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } super.renderLayer(matrices, pass, occlusionCamera, camera); } @@ -277,4 +339,27 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { LockSupport.parkNanos("Wait", 100000L); } } + + public void tracyPlots() { + int regions = 0; + for (var it = this.getRenderLists().iterator(); it.hasNext(); it.next()) { + regions++; + } + Tracy.plotInt(P_MESH_REGIONS, regions); + Tracy.plotInt(P_MESH_VISIBLE_CHUNKS, this.getVisibleChunkCount()); + if (this.shadowRenderListManager != null) { + int shadowRegions = 0, shadowSections = 0; + for (var it = this.shadowRenderListManager.getRenderLists().iterator(); it.hasNext(); ) { + shadowSections += it.next().getSectionsWithGeometryCount(); + shadowRegions++; + } + Tracy.plotInt(P_SHADOW_REGIONS, shadowRegions); + Tracy.plotInt(P_SHADOW_VISIBLE_CHUNKS, shadowSections); + } + Tracy.plotInt(P_MESH_SCHEDULED_JOBS, this.getBuilder().getScheduledJobCount()); + Tracy.plotInt(P_MESH_BUSY_THREADS, this.getBuilder().getBusyThreadCount()); + final var mem = this.getDeviceMemoryStats(); + Tracy.plotInt(P_MESH_DEVICE_USED, mem.deviceUsed + mem.indexUsed); + Tracy.plotInt(P_MESH_DEVICE_ALLOCATED, mem.deviceAllocated + mem.indexAllocated); + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java index 8b6e9a87b..ef601dcd3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java @@ -2,12 +2,18 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.gtnewhorizons.angelica.Tags; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.profiling.BailClassCounts; +import com.gtnewhorizons.angelica.profiling.RenderClassTimings; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import com.gtnewhorizons.angelica.glsm.states.FogState; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.client.Minecraft; @@ -15,12 +21,19 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.client.event.RenderGameOverlayEvent; import org.lwjgl.opengl.GL11; +import java.util.ArrayList; +import java.util.List; + public class CeleritasDebugScreenHandler { public static final CeleritasDebugScreenHandler INSTANCE = new CeleritasDebugScreenHandler(); /** Toggle for fog debug display on F3 screen */ public static boolean showFogDebug = false; + private static final long REBUILD_INTERVAL_NS = 500_000_000L; + private List cachedRight; + private long lastBuildNanos; + @SubscribeEvent(priority = EventPriority.LOW) public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) { final Minecraft mc = Minecraft.getMinecraft(); @@ -42,15 +55,48 @@ public class CeleritasDebugScreenHandler { event.left.add(getDynamicLightsDebugString()); } - event.right.add(""); - event.right.add(EnumChatFormatting.GREEN + "Angelica " + Tags.VERSION + " [Celeritas Renderer] [" + RENDER_BACKEND.getName() + "]"); - event.right.addAll(renderer.getDebugStrings()); + final long now = System.nanoTime(); + if (cachedRight == null || now - lastBuildNanos >= REBUILD_INTERVAL_NS) { + cachedRight = buildRightLines(renderer); + lastBuildNanos = now; + } + event.right.addAll(cachedRight); + } + + private static List buildRightLines(CeleritasWorldRenderer renderer) { + final List lines = new ArrayList<>(); + lines.add(""); + lines.add(EnumChatFormatting.GREEN + "Angelica " + Tags.VERSION + " [Celeritas Renderer] [" + RENDER_BACKEND.getName() + "]"); + lines.addAll(renderer.getDebugStrings()); final ShaderManager sm = ShaderManager.getInstance(); if (sm != null) { - event.right.add(sm.getDebugInfo()); + lines.add(sm.getDebugInfo()); + } + lines.add(TessellatorStreamingDrawer.getDebugInfo()); + lines.add(TesrBatchRenderer.INSTANCE.getDebugSummaryLine()); + final String transferInfo = RENDER_BACKEND.getTransferDebugInfo(); + if (transferInfo != null) { + lines.add(transferInfo); + } + if (SystemProperties.DEBUG_F3_DETAIL) { + lines.addAll(TesrBatchRenderer.INSTANCE.getDebugDetailStrings()); + lines.add(ModelPartBatcher.INSTANCE.getDebugString()); + if (Tracy.ENABLED) { + addIfPresent(lines, RenderClassTimings.TESR.debugLine()); + addIfPresent(lines, RenderClassTimings.ENTITY.debugLine()); + addIfPresent(lines, RenderClassTimings.SHADOW_ENTITY.debugLine()); + addIfPresent(lines, BailClassCounts.MATERIAL.debugLine()); + addIfPresent(lines, BailClassCounts.TEMPLATE.debugLine()); + } + } + lines.add(""); + return lines; + } + + private static void addIfPresent(List lines, String line) { + if (!line.isEmpty()) { + lines.add(line); } - event.right.add(TessellatorStreamingDrawer.getDebugInfo()); - event.right.add(""); } public static String getFogDebugString() { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java index 9253a2fa3..bbb32fae8 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java @@ -11,7 +11,7 @@ public class CeleritasSetup { private static boolean initialized = false; public static void ensureInitialized() { - if (!initialized && AngelicaConfig.enableCeleritas) { + if (!initialized) { GLRenderDevice.VANILLA_STATE_RESETTER = () -> GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); ChunkBiomeDataChangedEvent.BUS.addListener(CeleritasSetup::onChunkBiomeDataChanged); AngelicaClientTweaker.LOGGER.debug("Celeritas init"); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java index a4790ac5a..e329ba279 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import java.util.ArrayList; +import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -8,11 +9,15 @@ import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.client.MinecraftForgeClient; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.embeddedt.embeddium.impl.gl.device.CommandList; @@ -24,7 +29,11 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType; import org.embeddedt.embeddium.impl.render.terrain.SimpleWorldRenderer; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.Viewport; +import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum; +import org.joml.FrustumIntersection; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; @@ -33,16 +42,29 @@ import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache; +import com.gtnewhorizons.angelica.profiling.RenderClassTimings; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; +import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import net.coderbot.iris.pipeline.ShadowRenderer; public class CeleritasWorldRenderer extends SimpleWorldRenderer implements IDynamicLightWorldRenderer { private static final Logger LOGGER = LogManager.getLogger("Angelica"); + + private static final Tracy.ZoneId Z_TESR_COLLECT = Tracy.zoneId("tesrCollect", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_DISPATCH = Tracy.zoneId("tesrDispatch", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_MODEL_PARTS = Tracy.zoneId("tesrModelParts", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_RENDER_TE = Tracy.zoneId("tesrRenderTE", Tracy.COLOR_CLIENT); + private final Minecraft mc; private static CeleritasWorldRenderer instance; @@ -52,13 +74,19 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer frameTEs = new ObjectArrayList<>(); + private final ObjectArrayList frameOverride = new ObjectArrayList<>(); + // For sorting transparent TESRs - private final RenderSectionOrderer renderSectionOrderer = new RenderSectionOrderer(); private final TileEntityOrderer tileEntityOrderer = new TileEntityOrderer(); - private final ArrayList sortedRenderSections = new ArrayList<>(); private final ArrayList sortedTileEntities = new ArrayList<>(); private CeleritasWorldRenderer(Minecraft mc) { @@ -100,10 +128,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer list, TileEntityRenderContext context) { - for (TileEntity tileEntity : list) { - renderTE(tileEntity, context.pass, context.partialTicks); + for (int i = 0; i < list.size(); i++) { + final TileEntity te = list.get(i); + if (isTileEntityVisible(te)) { + frameTEs.add(te); + } } } + private CameraState lastMainCameraState; + @Override public void setupTerrain(Viewport viewport, CameraState cameraState, int frame, boolean spectator, boolean updateChunksImmediately) { var transform = viewport.getTransform(); @@ -186,6 +234,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer mcData) { final var culledEntities = (List) mcData.culledBlockEntities; - ShadowRenderer.visibleTileEntities.addAll(culledEntities); + if (!culledEntities.isEmpty()) { + ShadowRenderer.visibleTileEntities.add(culledEntities); + } } } } @@ -237,18 +302,37 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer mcData) { final var globalEntities = (List) mcData.globalBlockEntities; - ShadowRenderer.globalTileEntities.addAll(globalEntities); + if (!globalEntities.isEmpty()) { + ShadowRenderer.globalTileEntities.add(globalEntities); + } } } } + private CameraTransform cachedCameraTransform; + private double cachedCamX, cachedCamY, cachedCamZ; + @Override public void drawChunkLayer(BlockRenderLayer renderLayer, double x, double y, double z) { if (DEBUG_WIREFRAME_MODE) { GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); } - super.drawChunkLayer(renderLayer, x, y, z); + final ChunkRenderMatrices matrices = createChunkRenderMatrices(); + final Collection passes = this.renderSectionManager.getRenderPassConfiguration().vanillaRenderStages().get(renderLayer); + if (passes != null && !passes.isEmpty()) { + CameraTransform realCamera = cachedCameraTransform; + if (realCamera == null || cachedCamX != x || cachedCamY != y || cachedCamZ != z) { + realCamera = cachedCameraTransform = new CameraTransform(x, y, z); + cachedCamX = x; + cachedCamY = y; + cachedCamZ = z; + } + final CameraTransform occlusionCamera = this.getLastViewport().getTransform(); + for (final TerrainRenderPass pass : passes) { + this.renderSectionManager.renderLayer(matrices, pass, occlusionCamera, realCamera); + } + } if (DEBUG_WIREFRAME_MODE) { GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL); @@ -257,117 +341,216 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer renderListIterator = renderLists.iterator(); - - while (renderListIterator.hasNext()) { - var renderList = renderListIterator.next(); - - var renderRegion = renderList.getRegion(); - var renderSectionIterator = renderList.sectionsWithEntitiesIterator(); - - if (renderSectionIterator == null) { - continue; - } - - while (renderSectionIterator.hasNext()) { - var renderSectionId = renderSectionIterator.nextByteAsInt(); - var renderSection = renderRegion.getSection(renderSectionId); - - if (renderSection == null) { - continue; - } - - var context = renderSection.getBuiltContext(); - - if (!(context instanceof MinecraftBuiltRenderSectionData mcData)) { - continue; - } - - // noinspection unchecked - var blockEntities = (List) mcData.culledBlockEntities; - - if (blockEntities.isEmpty()) { - continue; - } - - for (TileEntity te : blockEntities) { - if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te); - } - } - } - - sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState)); - this.renderBlockEntityList(sortedTileEntities, renderContext); - - return sortedTileEntities.size(); - } - - private int renderGlobalTileEntities(TileEntityRenderContext renderContext) { - int count = 0; - sortedRenderSections.clear(); - sortedRenderSections.addAll(renderSectionManager.getSectionsWithGlobalEntities()); - sortedRenderSections.sort(renderSectionOrderer.setLastCameraState(lastCameraState)); - for (var renderSection : sortedRenderSections) { - sortedTileEntities.clear(); - var builtContext = renderSection.getBuiltContext(); - - if (!(builtContext instanceof MinecraftBuiltRenderSectionData mcData)) { - continue; - } - - // noinspection unchecked - var blockEntities = (List) mcData.globalBlockEntities; - - if (blockEntities.isEmpty()) { - continue; - } - - for (TileEntity te : blockEntities) { - if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te); - } - - count += sortedTileEntities.size(); - - sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState)); - this.renderBlockEntityList(sortedTileEntities, renderContext); - } - - return count; - } - public int renderBlockEntities(float partialTicks) { + AngelicaTesrMeshCache.INSTANCE.tick(); final int pass = MinecraftForgeClient.getRenderPass(); - teRenderContext.set(partialTicks, pass); - if (pass == 0 || !ClientProxy.options().performance.translucencySorting) { - return super.renderBlockEntities(teRenderContext); - } + + TesrBatchRenderer.INSTANCE.beginPass( + pass == 0 ? TesrBatchRenderer.PASS_MAIN_0 : TesrBatchRenderer.PASS_MAIN_1, + GLStateManager.getModelViewMatrix(), + TileEntityRendererDispatcher.staticPlayerX, + TileEntityRendererDispatcher.staticPlayerY, + TileEntityRendererDispatcher.staticPlayerZ); + ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES); int count = 0; - count += this.renderCulledTileEntities(teRenderContext); - count += this.renderGlobalTileEntities(teRenderContext); + if (pass == 0) { + teRenderContext.set(partialTicks, pass); + final Viewport viewport = this.currentViewport; + this.teTransform = viewport != null ? viewport.getTransform() : null; + this.teFrustum = viewport != null && ClientProxy.options().performance.sectionGatedTesrCulling && viewport.getFrustum() instanceof SimpleFrustum simpleFrustum ? simpleFrustum.frustumIntersection() : null; + this.teCullEpoch++; + this.teCamX = TileEntityRendererDispatcher.staticPlayerX; + this.teCamY = TileEntityRendererDispatcher.staticPlayerY; + this.teCamZ = TileEntityRendererDispatcher.staticPlayerZ; + frameTEs.clear(); + frameOverride.clear(); + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_COLLECT); + try { + super.renderBlockEntities(teRenderContext); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + this.teFrustum = null; + this.teTransform = null; + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH); + try { + for (int i = 0; i < frameTEs.size(); i++) { + final TileEntity te = frameTEs.get(i); + if (((ITileEntityBoundingBoxCache) te).angelica$passClass() == TileEntityRenderBoundsRegistry.PASS0_ONLY) { + dispatchTE(te, partialTicks); + count++; + continue; + } + frameOverride.add(te); + if (te.shouldRenderInPass(0)) { + dispatchTE(te, partialTicks); + count++; + } + } + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } else { + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH); + try { + sortedTileEntities.clear(); + for (int i = 0; i < frameOverride.size(); i++) { + final TileEntity te = frameOverride.get(i); + if (te.shouldRenderInPass(pass)) { + sortedTileEntities.add(te); + } + } + if (sortedTileEntities.size() > 1 && ClientProxy.options().performance.translucencySorting) { + sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState)); + } + for (int i = 0; i < sortedTileEntities.size(); i++) { + dispatchTE(sortedTileEntities.get(i), partialTicks); + } + count = sortedTileEntities.size(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_MODEL_PARTS); + try { + ModelPartBatcher.INSTANCE.flush(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + TesrBatchRenderer.INSTANCE.flush(); return count; } - private void renderTE(TileEntity tileEntity, int pass, float partialTicks) { - if (!tileEntity.shouldRenderInPass(pass)) { - return; + @Override + protected int renderSectionBlockEntities(RenderSection section, List blockEntities, boolean culled, TileEntityRenderContext renderContext) { + if (culled) { + if (section.getBuiltContext() instanceof AngelicaBuiltRenderSectionData angelicaData) { + if (TeDistanceMath.distSqToSection(teCamX, teCamY, teCamZ, + section.getOriginX(), section.getOriginY(), section.getOriginZ()) >= angelicaData.maxTeRenderDistSq) { + return 0; + } + if (teFrustum != null) { + return collectGatedSectionBlockEntities(section, angelicaData, blockEntities); + } + } + + int count = 0; + for (int i = 0; i < blockEntities.size(); i++) { + final TileEntity te = blockEntities.get(i); + if (isTileEntityVisible(te)) { + frameTEs.add(te); + count++; + } + } + return count; } + int count = 0; + for (int i = 0; i < blockEntities.size(); i++) { + final TileEntity te = blockEntities.get(i); + if (!(te.getDistanceFrom(teCamX, teCamY, teCamZ) < te.getMaxRenderDistanceSquared())) continue; + if (isTileEntityVisible(te)) { + frameTEs.add(te); + count++; + } + } + return count; + } + + private int collectGatedSectionBlockEntities(RenderSection section, AngelicaBuiltRenderSectionData angelicaData, List blockEntities) { + final CameraTransform t = this.teTransform; + final float ox = (section.getOriginX() - t.intX) - t.fracX; + final float oy = (section.getOriginY() - t.intY) - t.fracY; + final float oz = (section.getOriginZ() - t.intZ) - t.fracZ; + + final int verdict = sectionVerdict(angelicaData, ox, oy, oz); + if (verdict >= 0) { + return 0; + } + + if (verdict == FrustumIntersection.INSIDE) { + frameTEs.addAll(blockEntities); + return blockEntities.size(); + } + + final float[] bounds = angelicaData.culledBlockEntityBounds; + if (bounds.length != blockEntities.size() * 6) { + throw new IllegalStateException("culledBlockEntityBounds desync: " + bounds.length + " floats for " + blockEntities.size() + " tile entities"); + } + + int count = 0; + for (int i = 0, b = 0; i < blockEntities.size(); i++, b += 6) { + if (teFrustum.testAab(ox + bounds[b], oy + bounds[b + 1], oz + bounds[b + 2], + ox + bounds[b + 3], oy + bounds[b + 4], oz + bounds[b + 5])) { + frameTEs.add(blockEntities.get(i)); + count++; + } + } + return count; + } + + private int sectionVerdict(AngelicaBuiltRenderSectionData angelicaData, float ox, float oy, float oz) { + if (angelicaData.cullEpoch == this.teCullEpoch) { + return angelicaData.cullVerdict; + } + final int verdict = this.teFrustum.intersectAab(ox, oy, oz, ox + 16.0f, oy + 16.0f, oz + 16.0f); + angelicaData.cullEpoch = this.teCullEpoch; + angelicaData.cullVerdict = verdict; + return verdict; + } + + private boolean isTileEntityVisible(TileEntity tileEntity) { final ITileEntityBoundingBoxCache teCache = (ITileEntityBoundingBoxCache) tileEntity; final byte boundsClass = teCache.angelica$boundsClass(); if (boundsClass != TileEntityRenderBoundsRegistry.INFINITE) { final AxisAlignedBB aabb = boundsClass == TileEntityRenderBoundsRegistry.DYNAMIC ? tileEntity.getRenderBoundingBox() : teCache.angelica$getCachedRenderBoundingBox(); - if (aabb != null && !this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ)) { - return; - } + return aabb == null || isAabbVisible(aabb); } + return true; + } + private boolean isAabbVisible(AxisAlignedBB aabb) { + final FrustumIntersection frustum = this.teFrustum; + if (frustum == null) { + return this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ); + } + final CameraTransform t = this.teTransform; + return frustum.testAab( + (float) (aabb.minX - t.intX) - t.fracX, + (float) (aabb.minY - t.intY) - t.fracY, + (float) (aabb.minZ - t.intZ) - t.fracZ, + (float) (aabb.maxX - t.intX) - t.fracX, + (float) (aabb.maxY - t.intY) - t.fracY, + (float) (aabb.maxZ - t.intZ) - t.fracZ); + } + + private final Reference2ObjectOpenHashMap, Class> teLabelClasses = new Reference2ObjectOpenHashMap<>(); + + private Class teLabelClass(TileEntity tileEntity) { + final Class teClass = tileEntity.getClass(); + Class label = teLabelClasses.get(teClass); + if (label == null) { + final TileEntitySpecialRenderer renderer = TileEntityRendererDispatcher.instance.getSpecialRenderer(tileEntity); + label = renderer != null ? renderer.getClass() : teClass; + teLabelClasses.put(teClass, label); + } + return label; + } + + private void dispatchTE(TileEntity tileEntity, float partialTicks) { try { - TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks); + final long start = Tracy.ENABLED ? System.nanoTime() : 0L; + final boolean attribute = Tracy.ENABLED && TesrAttribution.currentRenderable == null; + if (attribute) TesrAttribution.currentRenderable = tileEntity.getClass(); + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_RENDER_TE); + try { + TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + if (attribute) TesrAttribution.currentRenderable = null; + if (Tracy.ENABLED) RenderClassTimings.TESR.add(teLabelClass(tileEntity), System.nanoTime() - start); + } } catch (RuntimeException e) { if (tileEntity.isInvalid()) { LOGGER.warn("Suppressed exception rendering invalid TileEntity {} at ({}, {}, {})", tileEntity.getClass().getName(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, e); @@ -413,30 +596,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer { - - public CameraState lastCameraState; - - public RenderSectionOrderer() { - super(); - } - - public RenderSectionOrderer setLastCameraState(CameraState lastCameraState) { - this.lastCameraState = lastCameraState; - return this; - } - - @Override - public int compare(RenderSection render1, RenderSection render2) { - final float x = (float) this.lastCameraState.x(); - final float y = (float) this.lastCameraState.y(); - final float z = (float) this.lastCameraState.z(); - final float d1 = render1.getSquaredDistance(x, y, z); - final float d2 = render2.getSquaredDistance(x, y, z); - return Float.compare(d2, d1); - } - } - private static class TileEntityOrderer implements Comparator { public CameraState lastCameraState; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/IndividualDrawEmitter.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/IndividualDrawEmitter.java index f702403c6..ee4aa8c26 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/IndividualDrawEmitter.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/IndividualDrawEmitter.java @@ -9,8 +9,7 @@ import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch; import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; -import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; -import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink; import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter; public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEmitter { @@ -19,29 +18,13 @@ public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEm } @Override - @SuppressWarnings("IntegerMultiplicationImplicitCastToLong") - public void addDrawCommands(long pMeshData, int mask, int indexPointerMask) { - var batch = this.batch; - final var pBaseVertex = batch.pBaseVertex; - final var pElementCount = batch.pElementCount; - final var pElementPointer = batch.pElementPointer; - - int size = batch.size; - - for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) { - LWJGL.memPutInt(pBaseVertex + (size << 2), SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing)); - LWJGL.memPutInt(pElementCount + (size << 2), SectionRenderDataUnsafe.getElementCount(pMeshData, facing)); - LWJGL.memPutAddress(pElementPointer + (size << 3), SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask); - - size += (mask >> facing) & 1; - } - - batch.size = size; + public DrawCommandSink getCommandSink() { + return this.batch; } @Override public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) { - try (DrawCommandList _ = commandList.beginTessellating(tessellation)) { + try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) { final int mode = primitiveType.getId(); final int type = GlIndexType.UNSIGNED_INT.getFormatId(); @@ -54,21 +37,6 @@ public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEm } } - @Override - public int getIndexBufferSize() { - return this.batch.getIndexBufferSize(); - } - - @Override - public boolean isEmpty() { - return this.batch.isEmpty(); - } - - @Override - public void clear() { - this.batch.clear(); - } - @Override public void delete() { this.batch.delete(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/MultiDrawModeResolver.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/MultiDrawModeResolver.java new file mode 100644 index 000000000..fb85c9e27 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/MultiDrawModeResolver.java @@ -0,0 +1,28 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.proxy.ClientProxy; +import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; +import org.lwjgl.opengl.ContextCapabilities; + +public final class MultiDrawModeResolver { + + private MultiDrawModeResolver() {} + + public static boolean indirectSupported() { + final ContextCapabilities caps = GLStateManager.capabilities; + return caps != null && (caps.OpenGL43 || caps.GL_ARB_multi_draw_indirect); + } + + public static MultiDrawMode resolve() { + final MultiDrawMode configured = ClientProxy.options().advanced.multiDrawMode; + if (configured != MultiDrawMode.INDIRECT && BackendManager.RENDER_BACKEND.isIndirectRequired()) { + return MultiDrawMode.INDIRECT; + } + if (configured == MultiDrawMode.INDIRECT && !indirectSupported()) { + return MultiDrawMode.DIRECT; + } + return configured; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMath.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMath.java new file mode 100644 index 000000000..fc0eab4a0 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMath.java @@ -0,0 +1,27 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +/** Decides when the section-age uniform upload can be skipped */ +public final class SectionAgeMath { + + public static final long STEP_NANOS = 100_000_000L; + + private SectionAgeMath() {} + + public static long quantize(long timestampNanos) { + return timestampNanos - Math.floorMod(timestampNanos, STEP_NANOS); + } + + public static long[] newState() { + return new long[] { Long.MIN_VALUE, Long.MIN_VALUE, 0L }; + } + + public static boolean canSkip(long[] state, long newestLoadTime, long quantizedTimestamp) { + return state[0] == newestLoadTime && (state[2] == 1L || state[1] == quantizedTimestamp); + } + + public static void record(long[] state, long newestLoadTime, long quantizedTimestamp, boolean allSaturated) { + state[0] = newestLoadTime; + state[1] = quantizedTimestamp; + state[2] = allSaturated ? 1L : 0L; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMath.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMath.java new file mode 100644 index 000000000..a44ed6097 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMath.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +public final class TeDistanceMath { + private TeDistanceMath() {} + + public static double distSqToSection(double camX, double camY, double camZ, int ox, int oy, int oz) { + final double dx = axisDist(camX, ox); + final double dy = axisDist(camY, oy); + final double dz = axisDist(camZ, oz); + return dx * dx + dy * dy + dz * dz; + } + + private static double axisDist(double cam, int min) { + if (cam < min) return min - cam; + final double max = min + 16; + if (cam > max) return cam - max; + return 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TerrainDrawStats.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TerrainDrawStats.java new file mode 100644 index 000000000..b4b450379 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/TerrainDrawStats.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +public final class TerrainDrawStats { + private static int commandsSubmitted; + private static int regionsDrawn; + + private TerrainDrawStats() { + } + + public static void recordBatch(int commandCount) { + commandsSubmitted += commandCount; + regionsDrawn++; + } + + public static int takeCommandsSubmitted() { + final int n = commandsSubmitted; + commandsSubmitted = 0; + return n; + } + + public static int takeRegionsDrawn() { + final int n = regionsDrawn; + regionsDrawn = 0; + return n; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java index 789a03f09..525d2c184 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/api/IrisShaderProvider.java @@ -27,4 +27,6 @@ public interface IrisShaderProvider { /** Block render layer overrides from shader pack */ @Nullable Map getBlockTypeIds(); + + default void preSubmitShadowGraph(int frame, boolean spectator) {} } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractor.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractor.java new file mode 100644 index 000000000..e43d34f44 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractor.java @@ -0,0 +1,77 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import org.joml.Matrix4fc; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public final class FrustumExtractor { + + public static final int UBO_SIZE_BYTES = 160; + public static final int PLANE_COUNT = 6; + + private static final int PLANE_STRIDE = 16; + private static final int CONTROL_OFFSET = 96; + private static final int CAMERA_WORLD_OFFSET = 112; + private static final int BATCH_OFFSET = 128; + private static final int PYR_OFFSET = 144; + + private FrustumExtractor() {} + + public static ByteBuffer allocateUboByteBuffer() { + return ByteBuffer.allocateDirect(UBO_SIZE_BYTES).order(ByteOrder.nativeOrder()); + } + + public static void writeStd140(Matrix4fc mvp, int visibleCount, int indexPointerMask, ByteBuffer out) { + final float r0x = mvp.m00(), r0y = mvp.m10(), r0z = mvp.m20(), r0w = mvp.m30(); + final float r1x = mvp.m01(), r1y = mvp.m11(), r1z = mvp.m21(), r1w = mvp.m31(); + final float r2x = mvp.m02(), r2y = mvp.m12(), r2z = mvp.m22(), r2w = mvp.m32(); + final float r3x = mvp.m03(), r3y = mvp.m13(), r3z = mvp.m23(), r3w = mvp.m33(); + + writePlane(out, 0 * PLANE_STRIDE, r3x + r0x, r3y + r0y, r3z + r0z, r3w + r0w); + writePlane(out, 1 * PLANE_STRIDE, r3x - r0x, r3y - r0y, r3z - r0z, r3w - r0w); + writePlane(out, 2 * PLANE_STRIDE, r3x + r1x, r3y + r1y, r3z + r1z, r3w + r1w); + writePlane(out, 3 * PLANE_STRIDE, r3x - r1x, r3y - r1y, r3z - r1z, r3w - r1w); + writePlane(out, 4 * PLANE_STRIDE, r3x + r2x, r3y + r2y, r3z + r2z, r3w + r2w); + writePlane(out, 5 * PLANE_STRIDE, r3x - r2x, r3y - r2y, r3z - r2z, r3w - r2w); + + out.putInt(CONTROL_OFFSET + 0, visibleCount); + out.putInt(CONTROL_OFFSET + 4, indexPointerMask); + out.putInt(CONTROL_OFFSET + 8, 0); + out.putInt(CONTROL_OFFSET + 12, 0); + out.putInt(BATCH_OFFSET, 0); + } + + public static void patchBatchEntryBase(int entryBase, ByteBuffer out) { + out.putInt(BATCH_OFFSET, entryBase); + } + + /** Small exact integers, so the float round trip through the UBO is lossless. */ + public static void patchPrimitiveRatio(int verticesPerPrimitive, int elementsPerPrimitive, ByteBuffer out) { + out.putFloat(PYR_OFFSET + 8, (float) verticesPerPrimitive); + out.putFloat(PYR_OFFSET + 12, (float) elementsPerPrimitive); + } + + public static void patchControl(int visibleCount, int indexPointerMask, ByteBuffer out) { + out.putInt(CONTROL_OFFSET + 0, visibleCount); + out.putInt(CONTROL_OFFSET + 4, indexPointerMask); + } + + public static void patchBypassFrustum(boolean bypass, ByteBuffer out) { + out.putInt(CONTROL_OFFSET + 8, bypass ? 1 : 0); + } + + public static void patchCameraWorld(float x, float y, float z, ByteBuffer out) { + out.putFloat(CAMERA_WORLD_OFFSET + 0, x); + out.putFloat(CAMERA_WORLD_OFFSET + 4, y); + out.putFloat(CAMERA_WORLD_OFFSET + 8, z); + } + + private static void writePlane(ByteBuffer out, int offset, float a, float b, float c, float d) { + final float invLen = 1.0f / (float) Math.sqrt(a * a + b * b + c * c); + out.putFloat(offset + 0, a * invLen); + out.putFloat(offset + 4, b * invLen); + out.putFloat(offset + 8, c * invLen); + out.putFloat(offset + 12, d * invLen); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuCulling.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuCulling.java new file mode 100644 index 000000000..a76cb0a3d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuCulling.java @@ -0,0 +1,77 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizons.angelica.config.GpuCullingMode; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import com.gtnewhorizons.angelica.rendering.celeritas.MultiDrawModeResolver; +import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; +import org.lwjgl.opengl.ContextCapabilities; + +public final class GpuCulling { + + private GpuCulling() {} + + private static final SectionMetaBuffer SECTION_META = new SectionMetaBuffer(); + + private static GpuDrivenChunkCuller culler; + + private static volatile GpuCullingMode activeMode = GpuCullingMode.CPU_ONLY; + + public static GpuCullingMode mode() { + return activeMode; + } + + public static void setMode(GpuCullingMode mode) { + activeMode = mode; + } + + public enum Availability { + AVAILABLE, + NO_BACKEND_COMPUTE, + MULTI_DRAW_NOT_INDIRECT, + NO_GL42, + NO_SSBO, + NO_MULTI_DRAW_INDIRECT + } + + public static Availability availability() { + final RenderBackend backend = BackendManager.RENDER_BACKEND; + if (!backend.supportsGpuDrivenCulling()) return Availability.NO_BACKEND_COMPUTE; + if (MultiDrawModeResolver.resolve() != MultiDrawMode.INDIRECT) return Availability.MULTI_DRAW_NOT_INDIRECT; + + if (backend.isSDLGPU()) return Availability.AVAILABLE; + + final ContextCapabilities caps = GLStateManager.capabilities; + if (caps == null || !caps.OpenGL42) return Availability.NO_GL42; + if (!RenderSystem.supportsSSBO()) return Availability.NO_SSBO; + if (!RenderSystem.supportsMultiDrawIndirect()) return Availability.NO_MULTI_DRAW_INDIRECT; + return Availability.AVAILABLE; + } + + public static boolean isAvailable() { + return availability() == Availability.AVAILABLE; + } + + public static SectionMetaBuffer sectionMeta() { + return SECTION_META; + } + + public static GpuDrivenChunkCuller culler() { + if (culler == null) culler = new GpuDrivenChunkCuller(); + return culler; + } + + public static void onWorldUnload() { + SECTION_META.reset(); + } + + public static void shutdown() { + if (culler != null) { + culler.shutdown(); + culler = null; + } + SECTION_META.shutdown(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuDrivenChunkCuller.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuDrivenChunkCuller.java new file mode 100644 index 000000000..619f2021c --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuDrivenChunkCuller.java @@ -0,0 +1,122 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.embeddedt.embeddium.impl.gl.shader.GlProgram; +import org.embeddedt.embeddium.impl.gl.shader.GlShader; +import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public final class GpuDrivenChunkCuller { + private static final Logger LOG = LogManager.getLogger("Angelica-Culling"); + private static final String COMPUTE_SHADER_RESOURCE = "angelica:culling/chunk_cull.csh"; + + public static final int VISIBLE_ENTRY_BYTES = 8; // uvec2 per visible section + static final int INDIRECT_COMMAND_BYTES = 20; // count, instCount, firstIdx, baseVtx, baseInst + static final int FACINGS_PER_SECTION = 7; + static final int LOCAL_SIZE_X = 64; + private static final int INITIAL_META_SECTIONS = 4096; + + static final int VISIBLE_SSBO_BINDING = 0; + static final int META_SSBO_BINDING = 1; + static final int INDIRECT_SSBO_BINDING = 2; + static final int FRUSTUM_UBO_BINDING = 0; + + private boolean ready; + private boolean disabled; + + private GlProgram program; + private int metaSsboGlId; + private int frustumUboGlId; + + private int metaCapacityBytes; + + public boolean ensureReady() { + if (ready) return true; + if (disabled) return false; + if (!RenderSystem.supportsCompute()) { + disabled = true; + LOG.info("GpuDrivenChunkCuller disabled: GL_ARB_compute_shader not supported"); + return false; + } + final GlShader cs = ShaderLoader.loadShader(ShaderType.COMPUTE, COMPUTE_SHADER_RESOURCE, ShaderConstants.EMPTY); + try { + program = GlProgram.builder("chunk_cull").attachShader(cs).link(ctx -> null); + } finally { + cs.delete(); + } + metaSsboGlId = GLStateManager.glGenBuffers(); + frustumUboGlId = GLStateManager.glGenBuffers(); + + GLStateManager.glBindBuffer(GL31.GL_UNIFORM_BUFFER, frustumUboGlId); + GLStateManager.glBufferData(GL31.GL_UNIFORM_BUFFER, FrustumExtractor.UBO_SIZE_BYTES, GL15.GL_STREAM_DRAW); + + metaCapacityBytes = SectionMetaBuffer.BYTES_PER_SECTION * INITIAL_META_SECTIONS; + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, metaSsboGlId); + GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, ByteBuffer.allocateDirect(metaCapacityBytes).order(ByteOrder.nativeOrder()), GL15.GL_DYNAMIC_DRAW); + + ready = true; + return true; + } + + public boolean uploadSectionMeta(ByteBuffer metaBytes) { + if (!ready || metaBytes == null || metaBytes.remaining() == 0) return false; + final int needed = metaBytes.remaining(); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, metaSsboGlId); + if (needed > metaCapacityBytes) { + final int newCap = Math.max(needed, Math.max(metaCapacityBytes * 2, SectionMetaBuffer.BYTES_PER_SECTION * INITIAL_META_SECTIONS)); + GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, newCap, GL15.GL_DYNAMIC_DRAW); + metaCapacityBytes = newCap; + } + GLStateManager.glBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, metaBytes); + return true; + } + + public void uploadFrustum(ByteBuffer frustumUboBytes) { + if (!ready || frustumUboBytes == null) return; + GLStateManager.glBindBuffer(GL31.GL_UNIFORM_BUFFER, frustumUboGlId); + GLStateManager.glBufferSubData(GL31.GL_UNIFORM_BUFFER, 0L, frustumUboBytes); + } + + public void dispatch(int visibleSsboGlId, int indirectSsboGlId, int visibleCount) { + if (!ready || visibleCount <= 0) return; + final int previousProgram = GLStateManager.getActiveProgram(); + final int prevSsbo0 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING); + final int prevSsbo1 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING); + final int prevSsbo2 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING); + final int prevUbo = RenderSystem.getIndexedBufferBinding(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING); + GLStateManager.glUseProgram(program.handle()); + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING, visibleSsboGlId); + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING, metaSsboGlId); + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING, indirectSsboGlId); + RenderSystem.bindBufferBase(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING, frustumUboGlId); + + final int groups = (visibleCount + LOCAL_SIZE_X - 1) / LOCAL_SIZE_X; + GLStateManager.glDispatchCompute(groups, 1, 1); + GLStateManager.glMemoryBarrier(GL43.GL_SHADER_STORAGE_BARRIER_BIT | GL42.GL_COMMAND_BARRIER_BIT); + + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING, prevSsbo0); + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING, prevSsbo1); + RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING, prevSsbo2); + RenderSystem.bindBufferBase(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING, prevUbo); + GLStateManager.glUseProgram(previousProgram); + } + + public synchronized void shutdown() { + if (program != null) { program.delete(); program = null; } + if (metaSsboGlId != 0) { GLStateManager.glDeleteBuffers(metaSsboGlId); metaSsboGlId = 0; } + if (frustumUboGlId != 0) { GLStateManager.glDeleteBuffers(frustumUboGlId); frustumUboGlId = 0; } + ready = false; + disabled = true; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuIndirectMultiDrawEmitter.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuIndirectMultiDrawEmitter.java new file mode 100644 index 000000000..e20b8c912 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/GpuIndirectMultiDrawEmitter.java @@ -0,0 +1,382 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import it.unimi.dsi.fastutil.objects.Reference2LongOpenHashMap; +import lombok.Getter; +import lombok.Setter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.gl.device.DrawCommandList; +import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; +import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL40; +import org.lwjgl.opengl.GL43; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public final class GpuIndirectMultiDrawEmitter implements MultiDrawEmitter { + + private static final Logger LOG = LogManager.getLogger("Angelica-Culling"); + + private static final int ENTRY_BYTES = GpuDrivenChunkCuller.VISIBLE_ENTRY_BYTES; + + private final GpuDrivenChunkCuller culler; + private final SectionMetaBuffer sectionMeta; + + private ByteBuffer visibleStaging; + private ByteBuffer visibleStagingView; + private int stagingCapacityEntries; + + private int visibleSsboGlId; + private int indirectSsboGlId; + private int gpuCapacityEntries; + + private static final class PassState { + int entryBase; + int entryCount; + int indexPointerMask; + int maxElementCount; + boolean dispatched; + final Reference2LongOpenHashMap regionRanges = new Reference2LongOpenHashMap<>(); + final Reference2LongOpenHashMap regionEntryRanges = new Reference2LongOpenHashMap<>(); + + PassState() { + regionRanges.defaultReturnValue(-1L); + regionEntryRanges.defaultReturnValue(-1L); + } + + void reset(int mask, int base) { + entryBase = base; + entryCount = 0; + indexPointerMask = mask; + maxElementCount = 0; + dispatched = false; + regionRanges.clear(); + regionEntryRanges.clear(); + } + } + + private final PassState primaryPass = new PassState(); + private final PassState secondPass = new PassState(); + private PassState buildPass = primaryPass; + private PassState current = primaryPass; + private boolean secondPrepared; + private int totalAppendedEntries; + @Getter private boolean computeActiveThisPass; + + private int currentDrawStart; + private int currentDrawCount; + private int currentEntryStart; + private int currentEntryCount; + private RenderRegion currentRegion; + + @Setter private ByteBuffer frustumUboBytes; + + private IndirectMultiDrawEmitter cpuFallback; + + public static long sectionMetaBytes; + + private static int commandsSubmitted; + private static int regionsDrawn; + private static int maxRegionCommands; + public static int commandsSubmitted() { return commandsSubmitted; } + public static int takeRegionsDrawn() { final int n = regionsDrawn; regionsDrawn = 0; return n; } + public static int takeMaxRegionCommands() { final int n = maxRegionCommands; maxRegionCommands = 0; return n; } + + private final SectionMetaBuffer.Sink uploadSectionMetaSink; + + public GpuIndirectMultiDrawEmitter(GpuDrivenChunkCuller culler, SectionMetaBuffer sectionMeta) { + this.culler = culler; + this.sectionMeta = sectionMeta; + this.uploadSectionMetaSink = buf -> { + final int bytes = buf.remaining(); + if (!culler.uploadSectionMeta(buf)) return false; + if (Tracy.ENABLED) sectionMetaBytes += bytes; + return true; + }; + } + + public void beginCullPass(int indexPointerMask) { + this.computeActiveThisPass = GpuCulling.mode().computeEnabled(); + this.totalAppendedEntries = 0; + this.secondPrepared = false; + primaryPass.reset(indexPointerMask, 0); + this.buildPass = primaryPass; + this.current = primaryPass; + this.currentDrawStart = 0; + this.currentDrawCount = 0; + this.currentEntryStart = 0; + this.currentEntryCount = 0; + if (computeActiveThisPass && cpuFallback != null) { + cpuFallback.getCommandSink().clear(); + } + } + + private IndirectMultiDrawEmitter cpuFallback() { + if (cpuFallback == null) cpuFallback = new IndirectMultiDrawEmitter(); + return cpuFallback; + } + + public void beginCombinedPasses(int firstMask, int secondMask) { + beginCullPass(firstMask); + secondPass.reset(secondMask, 0); + } + + public void startSecondPass() { + primaryPass.entryCount = totalAppendedEntries - primaryPass.entryBase; + secondPass.entryBase = totalAppendedEntries; + this.buildPass = secondPass; + this.current = secondPass; + } + + public void finishCombinedBuild() { + secondPass.entryCount = totalAppendedEntries - secondPass.entryBase; + this.secondPrepared = true; + this.buildPass = primaryPass; + this.current = primaryPass; + } + + public boolean selectPreparedSecondPass() { + if (!secondPrepared || !computeActiveThisPass) return false; + this.current = secondPass; + this.currentDrawStart = 0; + this.currentDrawCount = 0; + this.currentEntryStart = 0; + this.currentEntryCount = 0; + return true; + } + + public void reserveSections(int count) { + if (count > 0) ensureStagingCapacity(totalAppendedEntries + count); + } + + public int appendSection(int slot, int facingMask, int outputBase) { + if ((outputBase & ~0x00FFFFFF) != 0) { + throw new IllegalStateException("packed outputBase overflow: " + outputBase + " (max " + 0x00FFFFFF + ")"); + } + if (totalAppendedEntries >= stagingCapacityEntries) ensureStagingCapacity(totalAppendedEntries + 1); + final int idx = totalAppendedEntries; + final int off = idx * ENTRY_BYTES; + visibleStaging.putInt(off + 0, slot); + visibleStaging.putInt(off + 4, (outputBase << 8) | (facingMask & 0xFF)); + totalAppendedEntries = idx + 1; + buildPass.entryCount = totalAppendedEntries - buildPass.entryBase; + visibleStagingView.limit(totalAppendedEntries * ENTRY_BYTES); + return idx; + } + + public void recordRegion(RenderRegion region, int drawStart, int drawCount, int entryStart, int entryCount, int maxElementCount) { + if (drawCount <= 0) return; + buildPass.regionRanges.put(region, (((long) drawStart) << 32) | (drawCount & 0xFFFFFFFFL)); + buildPass.regionEntryRanges.put(region, (((long) entryStart) << 32) | (entryCount & 0xFFFFFFFFL)); + if (maxElementCount > buildPass.maxElementCount) buildPass.maxElementCount = maxElementCount; + } + + public void prepareRegion(RenderRegion region) { + currentRegion = region; + final long packed = current.regionRanges.getLong(region); + if (packed < 0L) { + currentDrawStart = 0; + currentDrawCount = 0; + } else { + currentDrawStart = (int) (packed >>> 32); + currentDrawCount = (int) (packed & 0xFFFFFFFFL); + } + final long entryPacked = current.regionEntryRanges.getLong(region); + if (entryPacked < 0L) { + currentEntryStart = 0; + currentEntryCount = 0; + } else { + currentEntryStart = (int) (entryPacked >>> 32); + currentEntryCount = (int) (entryPacked & 0xFFFFFFFFL); + } + } + + public void syncSectionMetaIfDirty() { + culler.ensureReady(); + sectionMeta.syncIfDirty(uploadSectionMetaSink); + } + + public void endPass() { + currentDrawStart = 0; + currentDrawCount = 0; + currentEntryStart = 0; + currentEntryCount = 0; + if (current == secondPass) secondPrepared = false; + } + + public void dispatchPreparedPasses() { + if (!computeActiveThisPass || totalAppendedEntries == 0) return; + if (!needsDispatch(primaryPass) && (!secondPrepared || !needsDispatch(secondPass))) return; + if (!culler.ensureReady()) return; + if (frustumUboBytes == null) { + LOG.warn("GpuIndirectMultiDrawEmitter: frustum UBO not set before dispatch; skipping cull"); + return; + } + + ensureGpuBuffers(totalAppendedEntries); + visibleStagingView.position(0).limit(totalAppendedEntries * ENTRY_BYTES); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, visibleSsboGlId); + GLStateManager.glBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, visibleStagingView); + + BackendManager.RENDER_BACKEND.beginComputeDispatchBatch(); + try { + dispatchPass(primaryPass); + if (secondPrepared) dispatchPass(secondPass); + } finally { + BackendManager.RENDER_BACKEND.endComputeDispatchBatch(); + } + } + + private static boolean needsDispatch(PassState r) { + return !r.dispatched && r.entryCount > 0; + } + + private void dispatchPass(PassState r) { + if (!needsDispatch(r)) return; + FrustumExtractor.patchControl(r.entryCount, r.indexPointerMask, frustumUboBytes); + FrustumExtractor.patchBatchEntryBase(r.entryBase, frustumUboBytes); + culler.uploadFrustum(frustumUboBytes); + culler.dispatch(visibleSsboGlId, indirectSsboGlId, r.entryCount); + r.dispatched = true; + } + + private void ensureGpuBuffers(int maxVisible) { + if (visibleSsboGlId == 0) visibleSsboGlId = GLStateManager.glGenBuffers(); + if (indirectSsboGlId == 0) indirectSsboGlId = GLStateManager.glGenBuffers(); + if (maxVisible <= gpuCapacityEntries) return; + final int newCap = Math.max(maxVisible, Math.max(gpuCapacityEntries * 2, 64)); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, visibleSsboGlId); + GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, (long) newCap * ENTRY_BYTES, GL15.GL_STREAM_DRAW); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, indirectSsboGlId); + final int indirectBytes = newCap * GpuDrivenChunkCuller.FACINGS_PER_SECTION * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES; + GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, ByteBuffer.allocateDirect(indirectBytes).order(ByteOrder.nativeOrder()), GL15.GL_STREAM_DRAW); + gpuCapacityEntries = newCap; + } + + private void ensureStagingCapacity(int needed) { + if (visibleStaging != null && needed <= stagingCapacityEntries) return; + final int newCap = Math.max(needed, Math.max(stagingCapacityEntries * 2, 64)); + final ByteBuffer next = MemoryUtilities.memAlloc(newCap * ENTRY_BYTES).order(ByteOrder.nativeOrder()); + if (visibleStaging != null) { + visibleStaging.position(0).limit(totalAppendedEntries * ENTRY_BYTES); + next.put(visibleStaging); + MemoryUtilities.memFree(visibleStaging); + } + next.position(0); + next.limit(newCap * ENTRY_BYTES); + visibleStaging = next; + visibleStagingView = visibleStaging.duplicate().order(ByteOrder.nativeOrder()); + stagingCapacityEntries = newCap; + } + + private final DrawCommandSink computeSink = new DrawCommandSink() { + @Override + public void clear() { + } + + @Override + public int size() { + return currentDrawCount; + } + + @Override + public int getIndexBufferSize() { + return current.maxElementCount; + } + + @Override + public void push(int baseVertex, int elementCount, long indexOffset) { + } + }; + + @Override + public DrawCommandSink getCommandSink() { + return computeActiveThisPass ? computeSink : cpuFallback().getCommandSink(); + } + + @Override + public boolean batchesWholePass() { + return !computeActiveThisPass && cpuFallback().batchesWholePass(); + } + + @Override + public void beginPass(CommandList commandList, int sectionCount) { + if (!computeActiveThisPass) cpuFallback().beginPass(commandList, sectionCount); + } + + @Override + public void finishAssembly(CommandList commandList) { + if (!computeActiveThisPass) cpuFallback().finishAssembly(commandList); + } + + @Override + public void selectDrawRange(int firstCommand, int commandCount) { + if (!computeActiveThisPass) cpuFallback().selectDrawRange(firstCommand, commandCount); + } + + @Override + public int getPendingCommandCount() { + return computeActiveThisPass ? currentDrawCount : cpuFallback().getPendingCommandCount(); + } + + @Override + public void onPassFinished(CommandList commandList) { + if (!computeActiveThisPass) cpuFallback().onPassFinished(commandList); + } + + @Override + public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) { + if (!computeActiveThisPass) { + cpuFallback().executeBatch(commandList, tessellation, primitiveType); + return; + } + if (currentDrawCount == 0) return; + dispatchPreparedPasses(); + if (!current.dispatched) return; + + if (Tracy.ENABLED) { + commandsSubmitted += currentDrawCount; + regionsDrawn++; + if (currentDrawCount > maxRegionCommands) maxRegionCommands = currentDrawCount; + } + + final long offsetBytes = (long) currentDrawStart * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES; + GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, indirectSsboGlId); + try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) { + GLStateManager.glMultiDrawElementsIndirect(primitiveType.getId(), GL11.GL_UNSIGNED_INT, offsetBytes, currentDrawCount, 0); + } + GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0); + } + + @Override + public void delete() { + if (visibleStaging != null) { + MemoryUtilities.memFree(visibleStaging); + visibleStaging = null; + visibleStagingView = null; + stagingCapacityEntries = 0; + } + if (visibleSsboGlId != 0) { GLStateManager.glDeleteBuffers(visibleSsboGlId); visibleSsboGlId = 0; } + if (indirectSsboGlId != 0) { GLStateManager.glDeleteBuffers(indirectSsboGlId); indirectSsboGlId = 0; } + gpuCapacityEntries = 0; + currentRegion = null; + frustumUboBytes = null; + primaryPass.regionRanges.clear(); + primaryPass.regionEntryRanges.clear(); + secondPass.regionRanges.clear(); + secondPass.regionEntryRanges.clear(); + if (cpuFallback != null) cpuFallback.delete(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/RenderPassIndex.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/RenderPassIndex.java new file mode 100644 index 000000000..239439882 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/RenderPassIndex.java @@ -0,0 +1,28 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; + +/** Stable index assignment for TerrainRenderPass instances. Keyed by pass name. */ +public final class RenderPassIndex { + public static final int MAX_PASSES = 8; + + private static final Object2IntOpenHashMap INDICES = new Object2IntOpenHashMap<>(MAX_PASSES); + static { INDICES.defaultReturnValue(-1); } + + private static int nextIndex; + + private RenderPassIndex() {} + + public static synchronized int indexOf(TerrainRenderPass pass) { + final String name = pass.name(); + final int existing = INDICES.getInt(name); + if (existing >= 0) return existing; + if (nextIndex >= MAX_PASSES) { + throw new IllegalStateException("RenderPassIndex: more than " + MAX_PASSES + " distinct TerrainRenderPass names; bump MAX_PASSES and the pass-bit budget in SectionMetaBuffer.sectionKey. Registered: " + INDICES); + } + final int assigned = nextIndex++; + INDICES.put(name, assigned); + return assigned; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBuffer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBuffer.java new file mode 100644 index 000000000..44a7bab9a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBuffer.java @@ -0,0 +1,166 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public final class SectionMetaBuffer { + private static final int INITIAL_CAPACITY = 16384; + public static final int BYTES_PER_SECTION = 64; + public static final int FACING_COUNT = 7; + public static final int POST_COUNT = FACING_COUNT + 1; + + public static final int OFFSET_SLICE_MASK = 12; + public static final int OFFSET_POSTS = 16; + public static final int OFFSET_FIRST_INDEX_BASE = 48; + + private final Long2IntOpenHashMap keyToSlot = new Long2IntOpenHashMap(); + private final IntArrayList freeSlots = new IntArrayList(); + private ByteBuffer mirror; + private ByteBuffer mirrorView; + private int capacity; + private int highWaterMark; + private boolean dirty; + + public SectionMetaBuffer() { + this.keyToSlot.defaultReturnValue(-1); + } + + private static long sectionKey(int passIndex, int sectionOriginX, int sectionOriginY, int sectionOriginZ) { + final long p = ((long) passIndex) & 0x7L; + final long sx = ((long)(sectionOriginX >> 4)) & 0x3FFFFFL; + final long sy = ((long)(sectionOriginY >> 4)) & 0xFFFFL; + final long sz = ((long)(sectionOriginZ >> 4)) & 0x7FFFFFL; + return (p << 61) | (sx << 39) | (sy << 23) | sz; + } + + public synchronized int update(int passIndex, int regionOriginX, int regionOriginY, int regionOriginZ, int localSectionIndex, + long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) { + if (dataPtr == 0L) return -1; + final int sectionOriginX = regionOriginX + (((localSectionIndex >> 5) & 0x07) << 4); + final int sectionOriginY = regionOriginY + (((localSectionIndex ) & 0x03) << 4); + final int sectionOriginZ = regionOriginZ + (((localSectionIndex >> 2) & 0x07) << 4); + final long key = sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ); + int slot = keyToSlot.get(key); + if (slot < 0) { + slot = allocateSlot(); + keyToSlot.put(key, slot); + } + writeSlot(slot, sectionOriginX, sectionOriginY, sectionOriginZ, dataPtr, layout, primitiveType); + dirty = true; + return slot; + } + + public synchronized void remove(int passIndex, int regionOriginX, int regionOriginY, int regionOriginZ, int localSectionIndex) { + if (mirror == null) return; + final int sectionOriginX = regionOriginX + (((localSectionIndex >> 5) & 0x07) << 4); + final int sectionOriginY = regionOriginY + (((localSectionIndex ) & 0x03) << 4); + final int sectionOriginZ = regionOriginZ + (((localSectionIndex >> 2) & 0x07) << 4); + final long key = sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ); + final int slot = keyToSlot.remove(key); + if (slot < 0) return; + zeroSlot(slot); + freeSlots.add(slot); + dirty = true; + } + + private int allocateSlot() { + if (!freeSlots.isEmpty()) { + return freeSlots.removeInt(freeSlots.size() - 1); + } + if (mirror == null) { + grow(INITIAL_CAPACITY); + } else if (highWaterMark >= capacity) { + grow(capacity * 2); + } + return highWaterMark++; + } + + private void grow(int newCapacity) { + final int newSize = newCapacity * BYTES_PER_SECTION; + final ByteBuffer next = MemoryUtilities.memAlloc(newSize).order(ByteOrder.nativeOrder()); + if (mirror != null) { + mirror.position(0).limit(highWaterMark * BYTES_PER_SECTION); + next.put(mirror); + mirrorView = null; + MemoryUtilities.memFree(mirror); + } + next.position(0); + next.limit(newSize); + mirror = next; + mirrorView = mirror.duplicate().order(ByteOrder.nativeOrder()); + capacity = newCapacity; + } + + private void writeSlot(int slot, int sectionOriginX, int sectionOriginY, int sectionOriginZ, long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) { + final int base = slot * BYTES_PER_SECTION; + mirror.putInt(base + 0, sectionOriginX); + mirror.putInt(base + 4, sectionOriginY); + mirror.putInt(base + 8, sectionOriginZ); + mirror.putInt(base + OFFSET_SLICE_MASK, SectionRenderDataUnsafe.getSliceMask(dataPtr)); + for (int facing = 0; facing < FACING_COUNT; facing++) { + mirror.putInt(base + OFFSET_POSTS + facing * 4, layout.getVertexOffset(dataPtr, facing)); + } + mirror.putInt(base + OFFSET_POSTS + FACING_COUNT * 4, layout.getRunVertexEnd(dataPtr, FACING_COUNT - 1, primitiveType)); + mirror.putInt(base + OFFSET_FIRST_INDEX_BASE, layout.getIndexOffset(dataPtr, 0) / 4); + mirror.putInt(base + 52, 0); + mirror.putInt(base + 56, 0); + mirror.putInt(base + 60, 0); + } + + private void zeroSlot(int slot) { + final int base = slot * BYTES_PER_SECTION; + for (int i = 0; i < BYTES_PER_SECTION; i += 4) { + mirror.putInt(base + i, 0); + } + } + + synchronized int lookupSlot(int passIndex, int sectionOriginX, int sectionOriginY, int sectionOriginZ) { + return keyToSlot.get(sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ)); + } + + synchronized boolean isDirty() { return dirty; } + synchronized void clearDirty() { dirty = false; } + synchronized int getCapacity() { return capacity; } + public synchronized int getHighWaterMark() { return highWaterMark; } + + public synchronized ByteBuffer getMirrorForReadOnly() { return mirrorView; } + + @FunctionalInterface + public interface Sink { + boolean accept(ByteBuffer mirror); + } + + public synchronized boolean syncIfDirty(Sink sink) { + if (!dirty) return false; + if (mirror == null || highWaterMark == 0 || mirrorView == null) { + dirty = false; + return false; + } + final int activeBytes = highWaterMark * BYTES_PER_SECTION; + mirrorView.position(0).limit(activeBytes); + if (!sink.accept(mirrorView)) return false; + dirty = false; + return true; + } + + public synchronized void reset() { + mirrorView = null; + if (mirror != null) { + MemoryUtilities.memFree(mirror); + mirror = null; + } + keyToSlot.clear(); + freeSlots.clear(); + capacity = 0; + highWaterMark = 0; + dirty = false; + } + + public synchronized void shutdown() { reset(); } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java new file mode 100644 index 000000000..216607c32 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java @@ -0,0 +1,260 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; +import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.event.TextureStitchEvent; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.function.LongSupplier; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; + +public final class AngelicaTesrMeshCache { + + public static final long LRU_TIMEOUT_MS = 60_000L; + + public static final AngelicaTesrMeshCache INSTANCE = new AngelicaTesrMeshCache(new GtnhMeshBackend(), System::currentTimeMillis); + private static final Logger LOG = LogManager.getLogger("AngelicaTesrMeshCache"); + + public static long cacheHits; + public static long cacheMisses; + + private final MeshBackend backend; + private final LongSupplier clock; + private final ReplaySink replaySink; + private final Reference2ObjectOpenHashMap entries = new Reference2ObjectOpenHashMap<>(); + private boolean warnedEmptyCapture; + + + public interface MeshBackend { + Tessellator beginCapture(VertexFormat format); + + TemplateBuffer endCaptureToTemplate(); + } + + public interface ReplaySink { + void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material); + } + + private static final class Bucket { + final ResourceLocation texture; + final TesrMaterial material; + final TemplateBuffer template; + + Bucket(ResourceLocation texture, TesrMaterial material, TemplateBuffer template) { + this.texture = texture; + this.material = material; + this.template = template; + } + } + + private static final class Entry { + final List buckets = new ArrayList<>(); + long version; + long lastUsedMs; + } + + private static final Tracy.ZoneId Z_TESR_CAPTURE = Tracy.zoneId("tesrCapture", Tracy.COLOR_CLIENT); + + AngelicaTesrMeshCache(MeshBackend backend, LongSupplier clock) { + this(backend, clock, (template, texture, material) -> TesrBatchRenderer.INSTANCE.queue(template, texture, material)); + } + + AngelicaTesrMeshCache(MeshBackend backend, LongSupplier clock, ReplaySink replaySink) { + this.backend = backend; + this.clock = clock; + this.replaySink = replaySink; + } + + public void renderCached(Object key, boolean dirty, TesrMeshProvider provider, TileEntity te) { + Entry entry = entries.get(key); + if (entry == null || dirty) { + if (Tracy.ENABLED) cacheMisses++; + entry = capture(key, entry, sink -> provider.angelica$build(sink, te)); + } else { + if (Tracy.ENABLED) cacheHits++; + } + replay(entry); + entry.lastUsedMs = clock.getAsLong(); + } + + public void renderCached(Object key, TesrMeshBuilder builder) { + Entry entry = entries.get(key); + if (entry == null) { + if (Tracy.ENABLED) cacheMisses++; + entry = capture(key, null, builder); + } else { + if (Tracy.ENABLED) cacheHits++; + } + replay(entry); + entry.lastUsedMs = clock.getAsLong(); + } + + public void invalidate(Object key) { + final Entry entry = entries.remove(key); + if (entry != null) { + entry.buckets.clear(); + } + } + + private Entry capture(Object key, Entry existing, TesrMeshBuilder builder) { + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_CAPTURE); + try { + return captureInner(key, existing, builder); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private Entry captureInner(Object key, Entry existing, TesrMeshBuilder builder) { + Entry entry = existing; + if (entry == null) { + entry = new Entry(); + entries.put(key, entry); + } else { + entry.buckets.clear(); + } + final CaptureSink sink = new CaptureSink(entry); + builder.angelica$build(sink); + sink.close(); + if (entry.buckets.isEmpty() && sink.openedAnyBucket && !warnedEmptyCapture) { + warnedEmptyCapture = true; + LOG.debug("Capture produced 0 vertices across all buckets for {}", key.getClass().getName()); + } + entry.version++; + return entry; + } + + private final class CaptureSink implements TesrMeshSink { + private final Entry entry; + private ResourceLocation openTexture; + private TesrMaterial openMaterial; + private boolean open; + boolean openedAnyBucket; + + CaptureSink(Entry entry) { + this.entry = entry; + } + + @Override + public Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture, TesrMaterial material) { + close(); + openTexture = texture; + openMaterial = material != null ? material : TesrMaterial.CURRENT_STATE; + open = true; + openedAnyBucket = true; + return backend.beginCapture(format); + } + + void close() { + if (open) { + final TemplateBuffer template = backend.endCaptureToTemplate(); + if (template != null) { + entry.buckets.add(new Bucket(openTexture, openMaterial, template)); + } + open = false; + openTexture = null; + openMaterial = null; + } + } + } + + private void replay(Entry entry) { + final List buckets = entry.buckets; + for (int i = 0, n = buckets.size(); i < n; i++) { + final Bucket b = buckets.get(i); + replaySink.queue(b.template, b.texture, b.material); + } + } + + public static final class ReloadListener { + @SubscribeEvent + public void onTextureStitchPost(TextureStitchEvent.Post event) { + INSTANCE.clear(); + } + } + + public void tick() { + evict(clock.getAsLong()); + } + + public void clear() { + entries.clear(); + } + + public int size() { + return entries.size(); + } + + void evict(long nowMs) { + if (entries.isEmpty()) return; + final ObjectIterator> it = entries.reference2ObjectEntrySet().fastIterator(); + while (it.hasNext()) { + final Entry entry = it.next().getValue(); + if (entry.lastUsedMs + LRU_TIMEOUT_MS < nowMs) { + entry.buckets.clear(); + it.remove(); + } + } + } + + long version(Object key) { + final Entry entry = entries.get(key); + return entry == null ? -1 : entry.version; + } + + boolean hasEntry(Object key) { + return entries.containsKey(key); + } + + static final class GtnhMeshBackend implements MeshBackend { + private DirectTessellator direct; + + @Override + public Tessellator beginCapture(VertexFormat format) { + direct = TessellatorManager.startCapturingDirect(format); + direct.startDrawingQuads(); + direct.draw(); + return direct; + } + + @Override + public TemplateBuffer endCaptureToTemplate() { + final int vertexCount = direct.getVertexCount(); + if (vertexCount == 0) { + TessellatorManager.stopCapturingDirect(); + direct = null; + return null; + } + final int drawMode = direct.getDrawMode(); + final VertexFormat format = direct.getVertexFormat(); + final ByteBuffer copy = direct.allocateBufferCopy(); + final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode); + memFree(copy); + TessellatorManager.stopCapturingDirect(); + direct = null; + return new TemplateBuffer(data, vertexCount, drawMode); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BeaconBeamMeshes.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BeaconBeamMeshes.java new file mode 100644 index 000000000..5cd6cbcb5 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BeaconBeamMeshes.java @@ -0,0 +1,108 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.tileentity.TileEntityBeacon; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; + +public final class BeaconBeamMeshes { + + private static final ResourceLocation BEACON_TEXTURE = new ResourceLocation("textures/entity/beacon_beam.png"); + + private static final TesrMaterial INNER = TesrMaterial.builder() + .color(1f, 1f, 1f, 1f).lightmap(240f, 240f).unlit().noCull().cutout(0.1f).stream() + .special(TesrMaterial.SpecialRender.BEACON_BEAM).build(); + private static final TesrMaterial OUTER = TesrMaterial.builder() + .color(1f, 1f, 1f, 32f / 255f).lightmap(240f, 240f).unlit().noCull().cutout(0.1f) + .translucent().noDepthWrite().stream() + .special(TesrMaterial.SpecialRender.BEACON_BEAM).build(); + + private static final Object INNER_KEY = new Object(); + private static final Object OUTER_KEY = new Object(); + + private static final double INNER_RADIUS = 0.2; + private static final double BEAM_HEIGHT = 256.0; + private static final double INNER_V_TOP = BEAM_HEIGHT * (0.5 / INNER_RADIUS); + + private static final TesrMeshBuilder INNER_BUILDER = sink -> { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE, BEACON_TEXTURE, INNER); + final double[] cx = new double[4]; + final double[] cz = new double[4]; + + final double[] angles = {3 * Math.PI / 4, Math.PI / 4, 5 * Math.PI / 4, 7 * Math.PI / 4}; + for (int i = 0; i < 4; i++) { + cx[i] = Math.cos(angles[i]) * INNER_RADIUS; + cz[i] = Math.sin(angles[i]) * INNER_RADIUS; + } + sideQuad(t, cx[0], cz[0], cx[1], cz[1], INNER_V_TOP); + sideQuad(t, cx[3], cz[3], cx[2], cz[2], INNER_V_TOP); + sideQuad(t, cx[1], cz[1], cx[3], cz[3], INNER_V_TOP); + sideQuad(t, cx[2], cz[2], cx[0], cz[0], INNER_V_TOP); + }; + + private static final TesrMeshBuilder OUTER_BUILDER = sink -> { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE, BEACON_TEXTURE, OUTER); + final double r = 0.3; + sideQuad(t, -r, -r, r, -r, BEAM_HEIGHT); + sideQuad(t, r, r, -r, r, BEAM_HEIGHT); + sideQuad(t, r, -r, r, r, BEAM_HEIGHT); + sideQuad(t, -r, r, -r, -r, BEAM_HEIGHT); + }; + + private static void sideQuad(Tessellator t, double x0, double z0, double x1, double z1, double vTop) { + t.addVertexWithUV(x0, BEAM_HEIGHT, z0, 1.0, vTop); + t.addVertexWithUV(x0, 0.0, z0, 1.0, 0.0); + t.addVertexWithUV(x1, 0.0, z1, 0.0, 0.0); + t.addVertexWithUV(x1, BEAM_HEIGHT, z1, 0.0, vTop); + } + + private BeaconBeamMeshes() {} + + public static boolean render(TileEntityBeacon beacon, double x, double y, double z, float partialTicks) { + final float f1 = beacon.func_146002_i(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1f); + if (f1 <= 0.0f) { + return true; + } + if (f1 < 1.0f) { + return false; + } + + Minecraft.getMinecraft().getTextureManager().bindTexture(BEACON_TEXTURE); + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); + + final float f2 = (float) beacon.getWorldObj().getTotalWorldTime() + partialTicks; + final float f3 = -f2 * 0.2f - MathHelper.floor_float(-f2 * 0.1f); + final double d3 = f2 * 0.025 * -1.5; + + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glTranslatef(0f, f3 - 1f, 0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + try { + GLStateManager.glPushMatrix(); + GLStateManager.glTranslated(x + 0.5, y, z + 0.5); + GLStateManager.glRotatef((float) -Math.toDegrees(d3), 0f, 1f, 0f); + AngelicaTesrMeshCache.INSTANCE.renderCached(INNER_KEY, INNER_BUILDER); + GLStateManager.glPopMatrix(); + + GLStateManager.glPushMatrix(); + GLStateManager.glTranslated(x + 0.5, y, z + 0.5); + AngelicaTesrMeshCache.INSTANCE.renderCached(OUTER_KEY, OUTER_BUILDER); + GLStateManager.glPopMatrix(); + } finally { + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + return true; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java new file mode 100644 index 000000000..f53fa682f --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java @@ -0,0 +1,82 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.BlendState; +import org.lwjgl.opengl.GL11; + +public final class EntityMaterials { + + static final TesrMaterial CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().build(); + static final TesrMaterial CUTOUT_HALF = TesrMaterial.builder().cutout(0.5f).stream().build(); + static final TesrMaterial SOLID = TesrMaterial.builder().stream().build(); + static final TesrMaterial TRANSLUCENT = TesrMaterial.builder().translucent().cutout(1f / 255f).noDepthWrite().stream().build(); + static final TesrMaterial TRANSLUCENT_DEPTH_WRITE = TesrMaterial.builder().translucent().cutout(1f / 255f).stream().build(); + static final TesrMaterial ADDITIVE = TesrMaterial.builder().additive().stream().build(); + static final TesrMaterial ADDITIVE_NO_DEPTH_WRITE = TesrMaterial.builder().additive().noDepthWrite().stream().build(); + static final TesrMaterial ADDITIVE_ALPHA = TesrMaterial.builder().additiveAlpha().stream().build(); + static final TesrMaterial ADDITIVE_ALPHA_NO_DEPTH_WRITE = TesrMaterial.builder().additiveAlpha().noDepthWrite().stream().build(); + static final TesrMaterial OVERLAY = TesrMaterial.builder().translucent().depthEqual().stream().build(); + static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream() + .special(TesrMaterial.SpecialRender.GLINT).build(); + + private EntityMaterials() {} + + static TesrMaterial fromCurrentState() { + final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled(); + final boolean texAnimated = textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)); + final BlendState blend = GLStateManager.getBlendState(); + return fromState(textured, texAnimated, + GLStateManager.getBlendMode().isEnabled(), blend.getSrcRgb(), blend.getDstRgb(), + GLStateManager.getAlphaTest().isEnabled(), + GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(), + GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled()); + } + + static TesrMaterial fromState(boolean textured, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) { + return fromState(textured, false, blend, srcRgb, dstRgb, alphaTest, alphaFunc, alphaRef, depthFunc, depthMask); + } + + static TesrMaterial fromState(boolean textured, boolean texAnimated, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) { + if (!textured) { + if (blend && depthFunc == GL11.GL_EQUAL && srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE_MINUS_SRC_ALPHA) { + return OVERLAY; + } + return null; + } + if (texAnimated) { + if (blend && !depthMask && depthFunc == GL11.GL_EQUAL && srcRgb == GL11.GL_SRC_COLOR && dstRgb == GL11.GL_ONE) { + return GLINT; + } + if (blend && (depthFunc == GL11.GL_LEQUAL || depthFunc == GL11.GL_LESS)) { + if (srcRgb == GL11.GL_ONE && dstRgb == GL11.GL_ONE) { + return depthMask ? ADDITIVE : ADDITIVE_NO_DEPTH_WRITE; + } + if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE) { + return depthMask ? ADDITIVE_ALPHA : ADDITIVE_ALPHA_NO_DEPTH_WRITE; + } + } + return null; + } + if (depthFunc != GL11.GL_LEQUAL && depthFunc != GL11.GL_LESS) { + return null; + } + if (!blend) { + if (!alphaTest) return SOLID; + if (alphaFunc == GL11.GL_GREATER && Math.abs(alphaRef - 0.1f) < 1e-4f) return CUTOUT; + if (alphaFunc == GL11.GL_GREATER && Math.abs(alphaRef - 0.5f) < 1e-4f) return CUTOUT_HALF; + return null; + } + if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE_MINUS_SRC_ALPHA) { + return depthMask ? TRANSLUCENT_DEPTH_WRITE : TRANSLUCENT; + } + if (srcRgb == GL11.GL_ONE && dstRgb == GL11.GL_ONE) { + return depthMask ? ADDITIVE : ADDITIVE_NO_DEPTH_WRITE; + } + if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE) { + return depthMask ? ADDITIVE_ALPHA : ADDITIVE_ALPHA_NO_DEPTH_WRITE; + } + return null; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java new file mode 100644 index 000000000..7e0ca2d19 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java @@ -0,0 +1,232 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer; +import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; + +final class InstancedTemplateRenderer { + + static final long TEMPLATE_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS; + + private static final int TEMPLATE_STRIDE = VERTEX_SIZE * 4; + private static final int TEMPLATE_FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT; + + private static final class TemplateMesh { + int vao; + int vbo; + int vertexCount; + int drawMode; + long lastUsedMs; + } + + private static final class Bucket { + TemplateMesh mesh; + final IntArrayList indices = new IntArrayList(); + } + + private final Reference2ObjectOpenHashMap meshes = new Reference2ObjectOpenHashMap<>(); + private final Reference2ObjectOpenHashMap buckets = new Reference2ObjectOpenHashMap<>(); + private final ObjectArrayList bucketPool = new ObjectArrayList<>(); + private final ObjectArrayList liveBuckets = new ObjectArrayList<>(); + private final float[] matScratch = new float[16]; + + private PersistentStreamingBuffer persistentRing; + private OrphanStreamingBuffer orphanRing; + private boolean ringInitialized; + private boolean ringUsedThisFrame; + private int uploadBufferId; + private ByteBuffer staging; + + int drawGroup(ObjectArrayList templates, FloatArrayList matrices, IntArrayList lights, IntArrayList colors, int count, long nowMs) { + for (int i = 0; i < count; i++) { + final TemplateBuffer template = templates.get(i); + Bucket bucket = buckets.get(template); + if (bucket == null) { + bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop(); + bucket.mesh = meshFor(template, nowMs); + buckets.put(template, bucket); + liveBuckets.add(bucket); + } + bucket.indices.add(i); + } + + staging = MeshBuffer.ensureCapacity(staging, count * InstancedAttribs.STRIDE, false); + final long base = memAddress0(staging); + long ptr = base; + for (int b = 0, n = liveBuckets.size(); b < n; b++) { + final IntArrayList indices = liveBuckets.get(b).indices; + for (int j = 0, m = indices.size(); j < m; j++) { + final int i = indices.getInt(j); + matrices.getElements(i * 16, matScratch, 0, 16); + for (int k = 0; k < 16; k++) { + memPutFloat(ptr + k * 4L, matScratch[k]); + } + memPutInt(ptr + InstancedAttribs.OFFSET_COLOR, colors.getInt(i)); + final int light = lights.getInt(i); + memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP, light & 0xFFFF); + memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP + 4, (light >>> 16) & 0xFFFF); + ptr += InstancedAttribs.STRIDE; + } + } + staging.position(0); + staging.limit((int) (ptr - base)); + final long ringBase = uploadInstances(staging); + staging.clear(); + + int draws = 0; + long recordOffset = ringBase; + final int ringId = uploadBufferId; + GLStateManager.instancedFfpDrawActive = true; + for (int b = 0, n = liveBuckets.size(); b < n; b++) { + final Bucket bucket = liveBuckets.get(b); + final TemplateMesh mesh = bucket.mesh; + GLStateManager.glBindVertexArray(mesh.vao); + VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ringId); + pointInstanceAttribs(recordOffset); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, bucket.indices.size()); + draws++; + recordOffset += (long) bucket.indices.size() * InstancedAttribs.STRIDE; + bucket.indices.clear(); + bucket.mesh = null; + bucketPool.add(bucket); + } + GLStateManager.instancedFfpDrawActive = false; + GLStateManager.glBindVertexArray(0); + liveBuckets.clear(); + buckets.clear(); + return draws; + } + + private static void pointInstanceAttribs(long base) { + for (int c = 0; c < 4; c++) { + GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_MATRIX_COL0 + c, 4, GL11.GL_FLOAT, false, + InstancedAttribs.STRIDE, base + c * 16L); + } + GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, + InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_COLOR); + GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, + InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_LIGHTMAP); + } + + private long uploadInstances(ByteBuffer data) { + if (!ringInitialized) { + ringInitialized = true; + persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY); + } + ringUsedThisFrame = true; + if (persistentRing != null) { + final int index = persistentRing.upload(data, InstancedAttribs.STRIDE); + if (index >= 0) { + uploadBufferId = persistentRing.getBufferId(); + return (long) index * InstancedAttribs.STRIDE; + } + } + if (orphanRing == null) orphanRing = new OrphanStreamingBuffer(); + orphanRing.upload(data); + uploadBufferId = orphanRing.getBufferId(); + return 0; + } + + private TemplateMesh meshFor(TemplateBuffer template, long nowMs) { + TemplateMesh mesh = meshes.get(template); + if (mesh == null) { + mesh = build(template); + meshes.put(template, mesh); + } + mesh.lastUsedMs = nowMs; + return mesh; + } + + private static TemplateMesh build(TemplateBuffer template) { + final TemplateMesh mesh = new TemplateMesh(); + mesh.vertexCount = template.vertexCount; + mesh.drawMode = template.drawMode; + mesh.vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(mesh.vao); + mesh.vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, mesh.vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, template.data, GL15.GL_STATIC_DRAW); + + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, TEMPLATE_STRIDE, 0L); + GLStateManager.glEnableVertexAttribArray(1); + GLStateManager.glVertexAttribPointer(1, 4, GL11.GL_UNSIGNED_BYTE, true, TEMPLATE_STRIDE, COLOR_INDEX * 4L); + GLStateManager.glEnableVertexAttribArray(2); + GLStateManager.glVertexAttribPointer(2, 2, GL11.GL_FLOAT, false, TEMPLATE_STRIDE, TEX_X_INDEX * 4L); + GLStateManager.glEnableVertexAttribArray(4); + GLStateManager.glVertexAttribPointer(4, 3, GL11.GL_BYTE, true, TEMPLATE_STRIDE, NORMAL_INDEX * 4L); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + for (int loc = InstancedAttribs.LOC_MATRIX_COL0; loc <= InstancedAttribs.LOC_LIGHTMAP; loc++) { + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribDivisor(loc, 1); + } + VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS); + GLStateManager.glBindVertexArray(0); + return mesh; + } + + void endFrame() { + if (ringUsedThisFrame && persistentRing != null) { + persistentRing.postDraw(); + } + ringUsedThisFrame = false; + } + + void sweep(long now) { + if (meshes.isEmpty()) return; + final ObjectIterator it = meshes.values().iterator(); + while (it.hasNext()) { + final TemplateMesh mesh = it.next(); + if (now - mesh.lastUsedMs <= TEMPLATE_TTL_MS) continue; + delete(mesh); + it.remove(); + } + } + + void clear() { + for (final TemplateMesh mesh : meshes.values()) { + delete(mesh); + } + meshes.clear(); + } + + private static void delete(TemplateMesh mesh) { + GLStateManager.glDeleteBuffers(mesh.vbo); + GLStateManager.glDeleteVertexArrays(mesh.vao); + } + + int meshCount() { + return meshes.size(); + } + + long meshBytes() { + long bytes = 0; + for (final TemplateMesh mesh : meshes.values()) { + bytes += (long) mesh.vertexCount * TEMPLATE_STRIDE; + } + return bytes; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/MeshBuffer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/MeshBuffer.java new file mode 100644 index 000000000..d1a01641e --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/MeshBuffer.java @@ -0,0 +1,86 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.BufferUtils; + +import java.nio.ByteBuffer; + +/** Equivalent of modern's VertexBuffer: a mesh uploaded once and drawn many times */ +public final class MeshBuffer { + + private VertexBuffer vbo; + private int vao; + + public void upload(VertexFormat format, int drawMode, ByteBuffer data, int vertexCount) { + upload(format, drawMode, data, vertexCount, false); + } + + public void upload(VertexFormat format, int drawMode, ByteBuffer data, int vertexCount, boolean dynamic) { + if (vbo == null || vbo.getDrawMode() != drawMode) { + if (vbo != null) vbo.delete(); + vbo = new VertexBuffer(format, drawMode); + } + if (dynamic) { + vbo.uploadDynamic(data, vertexCount); + } else { + vbo.uploadStream(data, vertexCount); + } + } + + public boolean isUploaded() { + return vbo != null; + } + + public void bind() { + if (vao == 0) { + vao = GLStateManager.glGenVertexArrays(); + } + GLStateManager.glBindVertexArray(vao); + vbo.setupState(); + } + + public void draw(int first, int count) { + vbo.draw(first, count); + } + + public void unbind() { + vbo.cleanupState(); + GLStateManager.glBindVertexArray(0); + } + + public void render() { + bind(); + vbo.draw(); + unbind(); + } + + public void delete() { + if (vbo != null) { + vbo.delete(); + vbo = null; + } + if (vao != 0) { + GLStateManager.glDeleteVertexArrays(vao); + vao = 0; + } + } + + public static ByteBuffer ensureCapacity(ByteBuffer buffer, int bytes, boolean preserve) { + if (buffer == null) { + return BufferUtils.createByteBuffer(Integer.highestOneBit(Math.max(bytes - 1, 1)) << 1); + } + if (preserve) { + if (buffer.remaining() >= bytes) return buffer; + int newCapacity = buffer.capacity() * 2; + while (newCapacity - buffer.position() < bytes) newCapacity *= 2; + final ByteBuffer grown = BufferUtils.createByteBuffer(newCapacity); + buffer.flip(); + grown.put(buffer); + return grown; + } + if (buffer.capacity() >= bytes) return buffer; + return BufferUtils.createByteBuffer(Integer.highestOneBit(Math.max(bytes - 1, 1)) << 1); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java new file mode 100644 index 000000000..7b47f4f3a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java @@ -0,0 +1,385 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.api.tesr.ModelPartMeshBuilder; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.states.BlendState; +import com.gtnewhorizons.angelica.glsm.states.Color4; +import com.gtnewhorizons.angelica.profiling.BailClassCounts; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.coderbot.iris.Iris; +import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.model.ModelBox; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; + +import java.util.List; +import java.util.Objects; + +public final class ModelPartBatcher { + + public static final ModelPartBatcher INSTANCE = new ModelPartBatcher(); + + public enum Mode { ENTITIES, BLOCK_ENTITIES } + + public enum BailReason { + INACTIVE("tesr.bail.inactive"), + RECORDING("tesr.bail.recording"), + MATERIAL("tesr.bail.material"), + TEXTURE("tesr.bail.texture"), + TEMPLATE("tesr.bail.template"), + HURT_FLASH("tesr.bail.hurtFlash"), + FOREIGN_PROGRAM("tesr.bail.foreignProgram"); + + public static final BailReason[] VALUES = values(); + public final String plotName; + + BailReason(String plotName) { + this.plotName = plotName; + } + } + + private static final long SWEEP_INTERVAL_MS = 5_000L; + + private final AngelicaBufferSource bufferSource = new AngelicaBufferSource(); + private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource); + private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource); + private RetainedTesrGroups activeGroups = groups; + private boolean shadow; + private final AngelicaTesrMeshCache.GtnhMeshBackend captureBackend = new AngelicaTesrMeshCache.GtnhMeshBackend(); + private final Matrix4f identity = new Matrix4f(); + private final Matrix4f modelView = new Matrix4f(); + private final Matrix4f texMatrixScratch = new Matrix4f(); + private int lastMvGeneration; + private boolean mvCaptured; + private boolean active; + private Mode mode = Mode.BLOCK_ENTITIES; + private boolean instancedThisCycle; + private DeferredWorldRenderingPipeline shaderPipeline; + private long lastSweepMs; + + long parts; + long liveFallbacks; + private final long[] bails = new long[BailReason.VALUES.length]; + private long lastParts, lastLiveFallbacks; + + public long statParts() { return parts; } + public long statLiveFallbacks() { return liveFallbacks; } + public long statBail(BailReason reason) { return bails[reason.ordinal()]; } + + private void bail(BailReason reason) { + bails[reason.ordinal()]++; + } + + private static final class PartTemplate { + TemplateBuffer template; + float scale; + long lastUsedMs; + boolean emptyVanillaPart; + boolean forceStream; + } + + private final Reference2ObjectOpenHashMap templates = new Reference2ObjectOpenHashMap<>(); + + private static final class LayerKey { + ResourceLocation texture; + TesrMaterial material; + + LayerKey set(ResourceLocation texture, TesrMaterial material) { + this.texture = texture; + this.material = material; + return this; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LayerKey other)) return false; + return Objects.equals(texture, other.texture) && Objects.equals(material, other.material); + } + + @Override + public int hashCode() { + return Objects.hashCode(texture) * 31 + Objects.hashCode(material); + } + } + + private final Object2ObjectOpenHashMap layers = new Object2ObjectOpenHashMap<>(); + private final LayerKey scratchKey = new LayerKey(); + private ResourceLocation lastLayerTexture; + private TesrMaterial lastLayerMaterial; + private RenderLayer lastLayer; + + private static ResourceLocation lastBoundLocation; + private static int lastBoundGlId = -1; + + private ModelPartBatcher() {} + + public static void onTextureBind(ResourceLocation location, int glId) { + lastBoundLocation = location; + lastBoundGlId = glId; + } + + public void begin(Mode mode) { + begin(mode, false); + } + + public void begin(Mode mode, boolean shadow) { + this.mode = mode; + this.shadow = shadow; + instancedThisCycle = TesrBatchRenderer.instancedCapable(); + shaderPipeline = TesrBatchRenderer.deferredPipeline(); + if (!AngelicaConfig.enableEntityBatching || !(instancedThisCycle || shaderPipeline != null)) { + active = false; + shaderPipeline = null; + return; + } + active = true; + mvCaptured = false; + activeGroups = shadow ? shadowGroups : groups; + bufferSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY); + activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline); + final long now = System.currentTimeMillis(); + if (now - lastSweepMs >= SWEEP_INTERVAL_MS) { + lastSweepMs = now; + groups.sweep(now); + shadowGroups.sweep(now); + sweepTemplates(now); + } + } + + public void flush() { + if (!active) return; + active = false; + if (shadow) { + bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups); + bufferSource.endBatch(activeGroups); + if (instancedThisCycle) { + TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame(); + } + BatchingFontRenderer.flushDeferredText(); + return; + } + final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive(); + final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop; + if (wrapEntities) GbufferPrograms.beginEntities(); + else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary(); + try { + bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups); + bufferSource.endBatch(activeGroups); + } finally { + if (wrapEntities) GbufferPrograms.endEntities(); + } + if (instancedThisCycle) { + TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame(); + } + } + + public boolean isActive() { + return active; + } + + public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { + final ModelPartBatcher r = INSTANCE; + if (!r.active) { + r.bail(BailReason.INACTIVE); + return false; + } + if (DisplayListManager.isRecording()) { + r.bail(BailReason.RECORDING); + return false; + } + if (!r.queuePart(part, scale, builder)) { + r.liveFallbacks++; + return false; + } + return true; + } + + private boolean queuePart(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { + if (shaderPipeline != null) { + if (GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) { + bail(BailReason.FOREIGN_PROGRAM); + return false; + } + } else if (GLStateManager.getOverlayA() != 0.0f) { + bail(BailReason.HURT_FLASH); + return false; + } + final PartTemplate entry = templateFor(part, scale, builder); + if (entry.emptyVanillaPart) { + return true; + } + if (shadow && isDepthEqualDecalState()) { + return true; + } + final TesrMaterial material = EntityMaterials.fromCurrentState(); + if (material == null) { + bail(BailReason.MATERIAL); + if (Tracy.ENABLED) { + BailClassCounts.MATERIAL.add(TesrAttribution.currentRenderable); + logMaterialBail(); + } + return false; + } + final ResourceLocation texture; + if (material == EntityMaterials.OVERLAY) { + texture = null; + } else { + if (GLStateManager.getBoundTextureForServerState() != lastBoundGlId) { + bail(BailReason.TEXTURE); + return false; + } + texture = lastBoundLocation; + if (texture == null) { + bail(BailReason.TEXTURE); + return false; + } + } + final TemplateBuffer template = entry.template; + if (template == null) { + bail(BailReason.TEMPLATE); + if (Tracy.ENABLED) BailClassCounts.TEMPLATE.add(TesrAttribution.currentRenderable); + return false; + } + + Matrix4f texMatrix = null; + if (texture != null) { + final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0); + if (!MatrixHelper.isIdentity(unitMatrix)) { + texMatrix = texMatrixScratch.set(unitMatrix); + if (material.isDepthEqual()) { + entry.forceStream = true; + } + } + } + final RenderLayer layer = layerFor(texture, material); + final int entityId = mode == Mode.ENTITIES ? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()) : CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); + final Color4 color = GLStateManager.getColor(); + final int colorABGR = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + final int packedLight = ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF); + final int mvGen = GLStateManager.getMvGeneration(); + if (!mvCaptured || mvGen != lastMvGeneration) { + modelView.set(GLStateManager.getModelViewMatrix()); + lastMvGeneration = mvGen; + mvCaptured = true; + } + activeGroups.queue(template, layer, material, modelView, packedLight, colorABGR, entityId, texMatrix, entry.forceStream); + parts++; + return true; + } + + private final ReferenceOpenHashSet> loggedMaterialBails = new ReferenceOpenHashSet<>(); + + private void logMaterialBail() { + final Class cls = TesrAttribution.currentRenderable; + if (cls == null || !loggedMaterialBails.add(cls)) return; + final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled(); + final BlendState blendState = GLStateManager.getBlendState(); + AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}", + cls.getName(), shadow, textured, + textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)), + GLStateManager.getBlendMode().isEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(), + GLStateManager.getAlphaTest().isEnabled(), + GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(), + GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled()); + } + + private static boolean isDepthEqualDecalState() { + return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.getDepthState().isEnabled(); + } + + private PartTemplate templateFor(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { + PartTemplate entry = templates.get(part); + if (entry == null || entry.scale != scale) { + entry = capture(part, scale, entry, builder); + } + entry.lastUsedMs = lastSweepMs; + return entry; + } + + private PartTemplate capture(ModelRenderer part, float scale, PartTemplate reuse, ModelPartMeshBuilder builder) { + final PartTemplate entry = reuse != null ? reuse : new PartTemplate(); + entry.scale = scale; + entry.template = null; + entry.emptyVanillaPart = false; + final List boxes = part.cubeList; + if (builder != null) { + final Tessellator tess = captureBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL); + try { + builder.angelica$buildPart(tess, part, scale); + } finally { + entry.template = captureBackend.endCaptureToTemplate(); + } + } else if (boxes != null && !boxes.isEmpty()) { + final Tessellator tess = captureBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL); + for (int i = 0, n = boxes.size(); i < n; i++) { + boxes.get(i).render(tess, scale); + } + entry.template = captureBackend.endCaptureToTemplate(); + } else { + entry.emptyVanillaPart = part.getClass() == ModelRenderer.class; + } + templates.put(part, entry); + return entry; + } + + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material) { + if (texture == lastLayerTexture && material == lastLayerMaterial) { + return lastLayer; + } + RenderLayer layer = layers.get(scratchKey.set(texture, material)); + if (layer == null) { + layer = RenderLayer.tesr(texture, material); + layers.put(new LayerKey().set(texture, material), layer); + } + lastLayerTexture = texture; + lastLayerMaterial = material; + lastLayer = layer; + return layer; + } + + private void sweepTemplates(long now) { + if (templates.isEmpty()) return; + final ObjectIterator it = templates.values().iterator(); + while (it.hasNext()) { + if (now - it.next().lastUsedMs > AngelicaTesrMeshCache.LRU_TIMEOUT_MS) { + it.remove(); + } + } + } + + public void clear() { + groups.clear(); + shadowGroups.clear(); + templates.clear(); + bufferSource.freeBuffers(); + active = false; + } + + public String getDebugString() { + final String line = String.format("Parts: %d grp, inst %d, live %d", groups.groupCount() + shadowGroups.groupCount(), parts - lastParts, liveFallbacks - lastLiveFallbacks); + lastParts = parts; + lastLiveFallbacks = liveFallbacks; + return line; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartMesher.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartMesher.java new file mode 100644 index 000000000..60e95dd87 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartMesher.java @@ -0,0 +1,28 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import net.minecraft.client.model.ModelBox; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.renderer.Tessellator; + +import java.util.List; + +public final class ModelPartMesher { + + private ModelPartMesher() {} + + public static void emitPart(Tessellator t, ModelRenderer part, float scale) { + t.setTranslation( + part.offsetX + part.rotationPointX * scale, + part.offsetY + part.rotationPointY * scale, + part.offsetZ + part.rotationPointZ * scale); + emitPartLocal(t, part, scale); + t.setTranslation(0, 0, 0); + } + + public static void emitPartLocal(Tessellator t, ModelRenderer part, float scale) { + final List boxes = part.cubeList; + for (int i = 0, n = boxes.size(); i < n; i++) { + boxes.get(i).render(t, scale); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PassRebindGate.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PassRebindGate.java new file mode 100644 index 000000000..56afd0218 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PassRebindGate.java @@ -0,0 +1,27 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; + +public final class PassRebindGate { + + private static int lastProgramGen = -1; + private static int lastFbGen = -1; + + private PassRebindGate() {} + + public static void rebindIfDirty() { + if (!Iris.enabled) return; + if (GLStateManager.getProgramGeneration() == lastProgramGen + && GLStateManager.getDrawFramebufferGeneration() == lastFbGen) { + return; + } + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (pipeline != null) { + pipeline.rebindCurrentPass(); + } + lastProgramGen = GLStateManager.getProgramGeneration(); + lastFbGen = GLStateManager.getDrawFramebufferGeneration(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java new file mode 100644 index 000000000..daf6efdcd --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java @@ -0,0 +1,535 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.joml.Vector3f; + +import java.nio.ByteBuffer; +import java.util.function.LongSupplier; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; + +final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { + + static final int PROMOTE_AFTER_REBUILDS = 3; + static final int DEMOTE_AFTER_STABLE_FRAMES = 4; + static final long IDLE_RESET_FRAMES = 100; + static final long GROUP_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS; + + private static final Tracy.ZoneId Z_TESR_REBUILD = Tracy.zoneId("tesrRebuild", Tracy.COLOR_CLIENT); + + private final AngelicaBufferSource source; + private final LongSupplier clock; + private long nowMs; + private final Matrix4f baseMV = new Matrix4f(); + private final Matrix4f baseMVInv = new Matrix4f(); + private final Matrix4f scratchMat = new Matrix4f(); + private final Vector3f scratchVec = new Vector3f(); + private final Matrix4f drawMV = new Matrix4f(); + private final Matrix4f savedMV = new Matrix4f(); + private boolean mvSaved; + private final float[] matScratch = new float[16]; + private double camX, camY, camZ; + private long frameMark; + + long rebuilds; + long retainedDraws; + long streamPromotions; + long streamedInstances; + long instancedDraws; + long instancedInstances; + + private InstancedTemplateRenderer instanced; + private boolean instancedActive; + private DeferredWorldRenderingPipeline deferred; + private final MeshBuffer fallbackMesh = new MeshBuffer(); + private ByteBuffer fallbackScratch; + + static final class Group { + final RenderLayer layer; + final TesrMaterial material; + final int blockEntityId; + final boolean opaque; + final boolean stream; + Class renderableClass; + int rebuildsWindow; + long anchorX, anchorY, anchorZ; + boolean anchored; + long frameMark = -1; + long lastUsedMs; + int entityColor; + + final ObjectArrayList instTemplates = new ObjectArrayList<>(); + final FloatArrayList instMatrices = new FloatArrayList(); + final IntArrayList instLights = new IntArrayList(); + final IntArrayList instColors = new IntArrayList(); + final ObjectArrayList instTexMatrices = new ObjectArrayList<>(); + private final ObjectArrayList texMatrixPool = new ObjectArrayList<>(); + private int texMatrixPoolUsed; + long hashAcc; + int count; + + long builtHash; + int builtCount = -1; + int builtVertexCount; + boolean streaming; + int consecutiveRebuilds; + long frameHash; + long prevFrameHash; + int stableFrames; + final MeshBuffer mesh = new MeshBuffer(); + ByteBuffer scratch; + int meshBytes; + + void addTexMatrix(Matrix4f src) { + if (src == null) { + instTexMatrices.add(null); + return; + } + if (texMatrixPoolUsed == texMatrixPool.size()) { + texMatrixPool.add(new Matrix4f()); + } + instTexMatrices.add(texMatrixPool.get(texMatrixPoolUsed++).set(src)); + } + + void clearInstances() { + instTemplates.clear(); + instMatrices.clear(); + instLights.clear(); + instColors.clear(); + instTexMatrices.clear(); + texMatrixPoolUsed = 0; + } + + Group(RenderLayer layer, TesrMaterial material, int blockEntityId) { + this.layer = layer; + this.material = material; + this.blockEntityId = blockEntityId; + this.opaque = material.transparency() == TesrMaterial.Transparency.OPAQUE; + this.stream = material.isStream(); + this.streaming = stream; + } + } + + private final Reference2ObjectOpenHashMap>> groups = new Reference2ObjectOpenHashMap<>(); + private final Reference2ObjectOpenHashMap> byLayer = new Reference2ObjectOpenHashMap<>(); + + RetainedTesrGroups(AngelicaBufferSource source) { + this(source, System::currentTimeMillis); + } + + RetainedTesrGroups(AngelicaBufferSource source, LongSupplier clock) { + this.source = source; + this.clock = clock; + } + + void beginPass(Matrix4f base, double camX, double camY, double camZ) { + beginPass(base, camX, camY, camZ, null, null); + } + + void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer) { + beginPass(base, camX, camY, camZ, instancedRenderer, null); + } + + void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, DeferredWorldRenderingPipeline deferred) { + baseMV.set(base); + baseMVInv.set(base).invert(); + this.camX = camX; + this.camY = camY; + this.camZ = camZ; + this.instanced = instancedRenderer; + this.instancedActive = instancedRenderer != null; + this.deferred = instancedRenderer != null ? deferred : null; + frameMark++; + nowMs = clock.getAsLong(); + } + + private Group groupFor(RenderLayer layer, TesrMaterial material, int blockEntityId) { + Reference2ObjectOpenHashMap> byMaterial = groups.get(layer); + if (byMaterial == null) { + byMaterial = new Reference2ObjectOpenHashMap<>(); + groups.put(layer, byMaterial); + } + Int2ObjectOpenHashMap byId = byMaterial.get(material); + if (byId == null) { + byId = new Int2ObjectOpenHashMap<>(); + byMaterial.put(material, byId); + } + Group group = byId.get(blockEntityId); + if (group == null) { + group = new Group(layer, material, blockEntityId); + group.lastUsedMs = nowMs; + byId.put(blockEntityId, group); + byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group); + } + if (group.renderableClass == null) { + group.renderableClass = TesrAttribution.currentRenderable; + } + return group; + } + + void forceStreaming(RenderLayer layer, TesrMaterial material, int blockEntityId) { + promote(groupFor(layer, material, blockEntityId)); + } + + void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int blockEntityId, Matrix4f texMatrix, boolean forceStream) { + final Group group = groupFor(layer, material, blockEntityId); + if (group.frameMark != frameMark) { + if (frameMark - group.frameMark > IDLE_RESET_FRAMES) { + group.streaming = group.stream; + group.consecutiveRebuilds = 0; + group.stableFrames = 0; + group.builtCount = -1; + } else if (group.streaming && group.opaque && !group.stream) { + if (group.frameHash == group.prevFrameHash) { + if (++group.stableFrames >= DEMOTE_AFTER_STABLE_FRAMES) { + group.streaming = false; + group.consecutiveRebuilds = 0; + group.stableFrames = 0; + group.builtCount = -1; + } + } else { + group.stableFrames = 0; + } + group.prevFrameHash = group.frameHash; + group.frameHash = 0; + } + group.frameMark = frameMark; + group.lastUsedMs = nowMs; + group.entityColor = SegmentedBufferBuilder.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); + group.count = 0; + group.hashAcc = 0; + group.clearInstances(); + if (!group.anchored || TesrAnchorMath.shouldReanchor(camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ)) { + group.anchorX = TesrAnchorMath.anchorCoord(camX); + group.anchorY = TesrAnchorMath.anchorCoord(camY); + group.anchorZ = TesrAnchorMath.anchorCoord(camZ); + group.anchored = true; + group.builtCount = -1; + } + source.declareUse(layer); + } + if (group.stream) { + final boolean instanceable = !forceStream && instancedActive && (deferred == null || material.shader() == null); + if (instanceable && (texMatrix == null || template.drawMode != layer.getDrawMode())) { + group.count++; + group.instTemplates.add(template); + currentMV.get(matScratch); + group.instMatrices.addElements(group.instMatrices.size(), matScratch); + group.instLights.add(packedLight); + group.instColors.add(colorABGR); + return; + } + if (template.drawMode == layer.getDrawMode()) { + source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); + streamedInstances++; + return; + } + } + scratchMat.set(baseMVInv).mul(currentMV); + TesrAnchorMath.toAnchorRelative(scratchMat, camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ); + long hash = TesrAnchorMath.instanceHash(System.identityHashCode(template), scratchMat, packedLight, colorABGR); + if (texMatrix != null) { + hash += TesrAnchorMath.texMatrixHash(texMatrix); + } + if (group.streaming && template.drawMode == layer.getDrawMode()) { + group.frameHash += hash; + source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); + streamedInstances++; + return; + } + group.hashAcc += hash; + group.count++; + group.instTemplates.add(template); + scratchMat.get(matScratch); + group.instMatrices.addElements(group.instMatrices.size(), matScratch); + group.instLights.add(packedLight); + group.instColors.add(colorABGR); + group.addTexMatrix(texMatrix); + } + + @Override + public boolean hasDraws(RenderLayer layer) { + final ObjectArrayList list = byLayer.get(layer); + if (list == null) return false; + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (group.frameMark == frameMark && group.count > 0) return true; + } + return false; + } + + @Override + public void drawLayer(RenderLayer layer) { + final ObjectArrayList list = byLayer.get(layer); + if (list == null) return; + boolean variantResolved = false; + boolean variantAvailable = false; + boolean variantBound = false; + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (group.frameMark != frameMark || group.count == 0) continue; + if (group.stream && instancedActive && (deferred == null || group.material.shader() == null)) { + restoreMV(); + if (deferred == null) { + instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs); + instancedInstances += group.count; + continue; + } + if (!variantResolved) { + variantResolved = true; + variantAvailable = deferred.hasTesrInstancedVariant(); + } + if (variantAvailable) { + applyGroupRenderState(group); + if (!variantBound) { + variantBound = true; + deferred.rebindCurrentPass(); + deferred.bindTesrInstancedVariant(); + } + instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs); + instancedInstances += group.count; + } else { + drawGroupCpuFallback(group); + } + continue; + } + variantBound = false; + if (group.builtCount != group.count || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) { + if (group.mesh.isUploaded()) { + group.consecutiveRebuilds++; + } + rebuild(group); + } else { + group.consecutiveRebuilds = 0; + } + draw(group); + if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) { + promote(group); + } + } + restoreMV(); + if (variantBound) { + deferred.rebindCurrentPass(); + } + } + + private void applyGroupRenderState(Group group) { + AngelicaBufferSource.setEntityColor(group.entityColor); + source.applyIdNoRebind(group.blockEntityId); + } + + private static final Matrix4f IDENTITY = new Matrix4f(); + + private void drawGroupCpuFallback(Group group) { + AngelicaBufferSource.setEntityColor(group.entityColor); + source.applyIdAndRebind(group.blockEntityId); + saveMV(); + GLStateManager.setModelViewMatrix(IDENTITY); + final VertexFormat format = group.layer.getVertexFormat(); + int start = 0; + while (start < group.count) { + final int drawMode = group.instTemplates.get(start).drawMode; + int end = start; + int totalVerts = 0; + while (end < group.count && group.instTemplates.get(end).drawMode == drawMode) { + totalVerts += group.instTemplates.get(end).vertexCount; + end++; + } + fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false); + fallbackScratch.clear(); + final long base = memAddress0(fallbackScratch); + long ptr = base; + for (int i = start; i < end; i++) { + group.instMatrices.getElements(i * 16, matScratch, 0, 16); + scratchMat.set(matScratch); + ptr = VertexTransform.writeInstance(ptr, format, group.instTemplates.get(i), scratchMat, scratchVec, group.instColors.getInt(i), group.instLights.getInt(i), null); + } + fallbackScratch.position((int) (ptr - base)); + fallbackScratch.flip(); + fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts); + fallbackMesh.render(); + streamedInstances += end - start; + start = end; + } + } + + private void promote(Group group) { + group.streaming = true; + streamPromotions++; + group.count = 0; + group.hashAcc = 0; + group.frameHash = 0; + group.prevFrameHash = 0; + group.stableFrames = 0; + group.builtCount = -1; + group.clearInstances(); + group.mesh.delete(); + group.meshBytes = 0; + } + + void sweep(long now) { + for (final ObjectArrayList list : byLayer.values()) { + for (int i = list.size() - 1; i >= 0; i--) { + final Group group = list.get(i); + if (now - group.lastUsedMs <= GROUP_TTL_MS) continue; + group.mesh.delete(); + list.remove(i); + final Reference2ObjectOpenHashMap> byMaterial = groups.get(group.layer); + if (byMaterial != null) { + final Int2ObjectOpenHashMap byId = byMaterial.get(group.material); + if (byId != null) { + byId.remove(group.blockEntityId); + } + } + } + } + } + + void clear() { + for (final ObjectArrayList list : byLayer.values()) { + for (int i = 0, n = list.size(); i < n; i++) { + list.get(i).mesh.delete(); + } + } + byLayer.clear(); + groups.clear(); + fallbackMesh.delete(); + fallbackScratch = null; + } + + int groupCount() { + int count = 0; + for (final ObjectArrayList list : byLayer.values()) { + count += list.size(); + } + return count; + } + + int streamingGroupCount() { + int count = 0; + for (final ObjectArrayList list : byLayer.values()) { + for (int i = 0, n = list.size(); i < n; i++) { + if (list.get(i).streaming) count++; + } + } + return count; + } + + long retainedBytes() { + long bytes = 0; + for (final ObjectArrayList list : byLayer.values()) { + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + bytes += group.meshBytes; + if (group.scratch != null) bytes += group.scratch.capacity(); + } + } + return bytes; + } + + private void rebuild(Group group) { + rebuilds++; + group.rebuildsWindow++; + if (Tracy.ENABLED) { + Tracy.beginZone(Z_TESR_REBUILD); + Tracy.zoneText(attribution(group)); + } + try { + rebuildInner(group); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + void collectRebuilders(ObjectArrayList out) { + for (final ObjectArrayList list : byLayer.values()) { + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (group.rebuildsWindow > 0) out.add(group); + } + } + } + + static String attribution(Group group) { + final StringBuilder sb = new StringBuilder(); + if (group.renderableClass != null) { + sb.append(group.renderableClass.getSimpleName()); + } else { + sb.append("id").append(group.blockEntityId); + } + final ResourceLocation tex = group.layer.getTextureId(); + if (tex != null) { + final String path = tex.getResourcePath(); + sb.append(' ').append(path, path.lastIndexOf('/') + 1, path.length()); + } + sb.append('/').append(group.material.transparency()); + return sb.toString(); + } + + private void rebuildInner(Group group) { + final VertexFormat format = group.layer.getVertexFormat(); + int totalVerts = 0; + for (int i = 0, n = group.instTemplates.size(); i < n; i++) { + totalVerts += group.instTemplates.get(i).vertexCount; + } + final int bytes = format.getVertexSize() * totalVerts; + group.scratch = MeshBuffer.ensureCapacity(group.scratch, bytes, false); + group.scratch.clear(); + final long base = memAddress0(group.scratch); + long ptr = base; + for (int i = 0, n = group.count; i < n; i++) { + group.instMatrices.getElements(i * 16, matScratch, 0, 16); + scratchMat.set(matScratch); + final int light = group.instLights.getInt(i); + final int color = group.instColors.getInt(i); + final TemplateBuffer template = group.instTemplates.get(i); + ptr = VertexTransform.writeInstance(ptr, format, template, scratchMat, scratchVec, color, light, group.instTexMatrices.get(i)); + } + group.scratch.position((int) (ptr - base)); + group.scratch.flip(); + group.builtVertexCount = totalVerts; + group.mesh.upload(format, group.layer.getDrawMode(), group.scratch, group.builtVertexCount, true); + group.meshBytes = bytes; + group.builtHash = group.hashAcc; + group.builtCount = group.count; + } + + private void draw(Group group) { + retainedDraws++; + AngelicaBufferSource.setEntityColor(group.entityColor); + source.applyIdAndRebind(group.blockEntityId); + drawMV.set(baseMV).translate((float) (group.anchorX - camX), (float) (group.anchorY - camY), (float) (group.anchorZ - camZ)); + saveMV(); + GLStateManager.setModelViewMatrix(drawMV); + group.mesh.render(); + } + + private void saveMV() { + if (!mvSaved) { + mvSaved = true; + savedMV.set(GLStateManager.getModelViewMatrix()); + } + } + + private void restoreMV() { + if (mvSaved) { + mvSaved = false; + GLStateManager.setModelViewMatrix(savedMV); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java new file mode 100644 index 000000000..59673e0a8 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java @@ -0,0 +1,16 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +public final class TemplateBuffer { + + public final int[] data; + final int[] work; + public final int vertexCount; + public final int drawMode; + + public TemplateBuffer(int[] data, int vertexCount, int drawMode) { + this.data = data; + this.work = data.clone(); + this.vertexCount = vertexCount; + this.drawMode = drawMode; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMath.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMath.java new file mode 100644 index 000000000..d3b8721e5 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMath.java @@ -0,0 +1,78 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import org.joml.Matrix4f; + +public final class TesrAnchorMath { + + public static final int ANCHOR_GRID = 16; + public static final double REANCHOR_DISTANCE = 512.0; + private static final float HASH_QUANT = 4096f; + + private TesrAnchorMath() {} + + public static long anchorCoord(double cam) { + return (long) Math.floor(cam / ANCHOR_GRID) * ANCHOR_GRID; + } + + public static boolean shouldReanchor(double camX, double camY, double camZ, long anchorX, long anchorY, long anchorZ) { + final double dx = camX - anchorX; + final double dy = camY - anchorY; + final double dz = camZ - anchorZ; + return dx * dx + dy * dy + dz * dz > REANCHOR_DISTANCE * REANCHOR_DISTANCE; + } + + public static void toAnchorRelative(Matrix4f m, double camX, double camY, double camZ, long anchorX, long anchorY, long anchorZ) { + m.m30(m.m30() + (float) (camX - anchorX)); + m.m31(m.m31() + (float) (camY - anchorY)); + m.m32(m.m32() + (float) (camZ - anchorZ)); + } + + public static long instanceHash(int templateIdentity, Matrix4f mA, int packedLight, int colorABGR) { + long h = templateIdentity * 0x9E3779B97F4A7C15L; + h = mix(h, quantize(mA.m00())); + h = mix(h, quantize(mA.m01())); + h = mix(h, quantize(mA.m02())); + h = mix(h, quantize(mA.m10())); + h = mix(h, quantize(mA.m11())); + h = mix(h, quantize(mA.m12())); + h = mix(h, quantize(mA.m20())); + h = mix(h, quantize(mA.m21())); + h = mix(h, quantize(mA.m22())); + h = mix(h, quantize(mA.m30())); + h = mix(h, quantize(mA.m31())); + h = mix(h, quantize(mA.m32())); + h = mix(h, packedLight); + h = mix(h, colorABGR); + return avalanche(h); + } + + public static long texMatrixHash(Matrix4f t) { + long h = 0x2545F4914F6CDD1DL; + h = mix(h, quantize(t.m00())); + h = mix(h, quantize(t.m01())); + h = mix(h, quantize(t.m10())); + h = mix(h, quantize(t.m11())); + h = mix(h, quantize(t.m30())); + h = mix(h, quantize(t.m31())); + return avalanche(h); + } + + private static int quantize(float v) { + return Math.round(v * HASH_QUANT); + } + + private static long mix(long h, int v) { + h ^= v; + h *= 0xFF51AFD7ED558CCDL; + return Long.rotateLeft(h, 31); + } + + private static long avalanche(long h) { + h ^= h >>> 33; + h *= 0xFF51AFD7ED558CCDL; + h ^= h >>> 29; + h *= 0xC4CEB9FE1A85EC53L; + h ^= h >>> 32; + return h; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAttribution.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAttribution.java new file mode 100644 index 000000000..a8085bfe5 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAttribution.java @@ -0,0 +1,7 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +public final class TesrAttribution { + private TesrAttribution() {} + + public static Class currentRenderable; +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java new file mode 100644 index 000000000..af538b3e3 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java @@ -0,0 +1,481 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrShader; +import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.states.Color4; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder; +import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.coderbot.iris.Iris; +import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; +import net.coderbot.iris.pipeline.WorldRenderingPhase; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.EntityRenderer; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; + +public final class TesrBatchRenderer { + + public static final TesrBatchRenderer INSTANCE = new TesrBatchRenderer(); + + public static final int PASS_MAIN_0 = 0; + public static final int PASS_MAIN_1 = 1; + public static final int PASS_SHADOW = 2; + private static final int PASS_COUNT = 3; + + private static final long SWEEP_INTERVAL_MS = 5_000L; + + private static final Tracy.ZoneId Z_TESR_OPAQUE = Tracy.zoneId("tesrOpaque", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_BATCH = Tracy.zoneId("tesrBatch", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_INSTANCED = Tracy.zoneId("tesrInstanced", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_TEXT = Tracy.zoneId("tesrText", Tracy.COLOR_CLIENT); + private static final Tracy.ZoneId Z_TESR_DEFERRED = Tracy.zoneId("tesrDeferred", Tracy.COLOR_CLIENT); + + private final AngelicaBufferSource bufferSource = new AngelicaBufferSource(); + private final RetainedTesrGroups[] retained = new RetainedTesrGroups[PASS_COUNT]; + final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer(); + private int activePass = -1; + private long lastSweepMs; + private boolean deferredFlushPending; + private RetainedTesrGroups pendingDeferredHook; + + private final Matrix4f modelView = new Matrix4f(); + private final Matrix4f identity = new Matrix4f(); + private final Vector3f scratchVec = new Vector3f(); + + private TesrBatchRenderer() { + for (int i = 0; i < PASS_COUNT; i++) { + retained[i] = new RetainedTesrGroups(bufferSource); + } + } + + public void beginPass(int passKey, Matrix4f baseMV, double camX, double camY, double camZ) { + if (deferredFlushPending) { + discardDeferred(); + } + activePass = passKey; + retained[passKey].beginPass(baseMV, camX, camY, camZ, instancedCapable() ? instancedRenderer : null, deferredPipeline()); + if (passKey == PASS_MAIN_0) { + final long now = System.currentTimeMillis(); + if (now - lastSweepMs >= SWEEP_INTERVAL_MS) { + lastSweepMs = now; + for (int i = 0; i < PASS_COUNT; i++) { + retained[i].sweep(now); + } + instancedRenderer.sweep(now); + } + } + } + + static boolean instancedCapable() { + if (!ShaderManager.getInstance().isEnabled()) return false; + if (!Iris.enabled) return true; + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (pipeline == null || pipeline instanceof FixedFunctionWorldRenderingPipeline) return true; + return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsTesrInstancing(); + } + + static DeferredWorldRenderingPipeline deferredPipeline() { + if (!Iris.enabled) return null; + return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline deferred + ? deferred : null; + } + + private void discardDeferred() { + deferredFlushPending = false; + pendingDeferredHook = null; + bufferSource.discard(); + BatchingFontRenderer.discardDeferredText(); + } + + public void clearRetained() { + discardDeferred(); + for (int i = 0; i < PASS_COUNT; i++) { + retained[i].clear(); + } + instancedRenderer.clear(); + immediateMesh.delete(); + immediateScratch = null; + bufferSource.freeBuffers(); + AngelicaTesrMeshCache.INSTANCE.clear(); + } + + public boolean hasActivePass() { + return activePass >= 0; + } + + public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) { + modelView.set(GLStateManager.getModelViewMatrix()); + final int packedLight = currentPackedLight(material); + final int colorABGR = resolveColor(material); + if (activePass >= 0) { + final RenderLayer layer = layerFor(texture, material); + final int blockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); + retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, blockEntityId, captureTextureMatrix(), false); + } else { + drawImmediate(template, texture, material, packedLight, colorABGR); + } + } + + private static Matrix4f captureTextureMatrix() { + final Matrix4f texMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0); + return MatrixHelper.isIdentity(texMatrix) ? null : texMatrix; + } + + static final class LayerKey { + ResourceLocation texture; + TesrMaterial.Transparency transparency; + boolean noCull; + boolean unlit; + boolean noDepthWrite; + boolean depthOnly; + float cutoutAlpha; + boolean depthEqual; + TesrMaterial.SpecialRender special; + TesrShader shader; + boolean noPass; + + LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass) { + this.texture = texture; + this.transparency = transparency; + this.noCull = noCull; + this.unlit = unlit; + this.noDepthWrite = noDepthWrite; + this.depthOnly = depthOnly; + this.cutoutAlpha = cutoutAlpha; + this.depthEqual = depthEqual; + this.special = special; + this.shader = shader; + this.noPass = noPass; + return this; + } + + LayerKey copy() { + return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LayerKey other)) return false; + return Objects.equals(texture, other.texture) && transparency == other.transparency + && noCull == other.noCull && unlit == other.unlit && noDepthWrite == other.noDepthWrite + && depthOnly == other.depthOnly + && Float.floatToIntBits(cutoutAlpha) == Float.floatToIntBits(other.cutoutAlpha) + && depthEqual == other.depthEqual && special == other.special && shader == other.shader && noPass == other.noPass; + } + + @Override + public int hashCode() { + int h = Objects.hashCode(texture); + h = h * 31 + Objects.hashCode(transparency); + h = h * 31 + (noCull ? 1 : 0); + h = h * 31 + (unlit ? 1 : 0); + h = h * 31 + (noDepthWrite ? 1 : 0); + h = h * 31 + (depthOnly ? 1 : 0); + h = h * 31 + Float.floatToIntBits(cutoutAlpha); + h = h * 31 + (depthEqual ? 1 : 0); + h = h * 31 + Objects.hashCode(special); + h = h * 31 + System.identityHashCode(shader); + h = h * 31 + (noPass ? 1 : 0); + return h; + } + } + + private final Object2ObjectOpenHashMap layers = new Object2ObjectOpenHashMap<>(); + private final LayerKey scratchKey = new LayerKey(); + private ResourceLocation lastLayerTexture; + private TesrMaterial lastLayerMaterial; + private RenderLayer lastLayer; + private ResourceLocation lastImmediateTexture; + private TesrMaterial lastImmediateMaterial; + private RenderLayer lastImmediateLayer; + + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material) { + if (texture == lastLayerTexture && material == lastLayerMaterial) { + return lastLayer; + } + final RenderLayer layer = layerLookup(texture, material, false); + lastLayerTexture = texture; + lastLayerMaterial = material; + lastLayer = layer; + return layer; + } + + private RenderLayer noPassLayerFor(ResourceLocation texture, TesrMaterial material) { + if (texture == lastImmediateTexture && material == lastImmediateMaterial) { + return lastImmediateLayer; + } + final RenderLayer layer = layerLookup(texture, material, true); + lastImmediateTexture = texture; + lastImmediateMaterial = material; + lastImmediateLayer = layer; + return layer; + } + + private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass) { + final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass); + RenderLayer layer = layers.get(key); + if (layer == null) { + layer = noPass ? RenderLayer.tesrNoPass(texture, material) : RenderLayer.tesr(texture, material); + layers.put(key.copy(), layer); + } + return layer; + } + + private static int currentPackedLight(TesrMaterial material) { + if (material.hasLightmap()) { + return ((int) material.lightmapY() << 16) | ((int) material.lightmapX() & 0xFFFF); + } + return ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF); + } + + private static int resolveColor(TesrMaterial material) { + if (material.hasColor()) { + return ColorABGR.pack(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha()); + } + final Color4 color = GLStateManager.getColor(); + return ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + } + + public void flush() { + final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null; + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE); + try { + bufferSource.endBatchWithType(TransparencyType.OPAQUE, hook); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + if (activePass == PASS_MAIN_0 && deferredPipeline() != null) { + bufferSource.pauseBatch(); + pendingDeferredHook = hook; + deferredFlushPending = true; + activePass = -1; + return; + } + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_BATCH); + try { + bufferSource.endBatch(hook); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_INSTANCED); + try { + instancedRenderer.endFrame(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_TEXT); + try { + BatchingFontRenderer.flushDeferredText(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + activePass = -1; + } + + public void flushAfterDeferred() { + if (!deferredFlushPending) return; + deferredFlushPending = false; + final RetainedTesrGroups hook = pendingDeferredHook; + pendingDeferredHook = null; + if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DEFERRED); + try { + final EntityRenderer entityRenderer = Minecraft.getMinecraft().entityRenderer; + final boolean savedDepthMask = GLStateManager.getDepthState().isEnabled(); + final boolean savedBlend = GLStateManager.getBlendMode().isEnabled(); + final int savedSrcRgb = GLStateManager.getBlendState().getSrcRgb(); + final int savedDstRgb = GLStateManager.getBlendState().getDstRgb(); + final int savedSrcAlpha = GLStateManager.getBlendState().getSrcAlpha(); + final int savedDstAlpha = GLStateManager.getBlendState().getDstAlpha(); + final boolean savedAlphaTest = GLStateManager.getAlphaTest().isEnabled(); + final int savedAlphaFunc = GLStateManager.getAlphaState().getFunction(); + final float savedAlphaRef = GLStateManager.getAlphaState().getReference(); + + GLStateManager.glDepthMask(true); + GLStateManager.enableDepthTest(); + GLStateManager.enableBlend(); + GLStateManager.defaultBlendFunc(); + entityRenderer.enableLightmap(0); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + final boolean wrap = Iris.enabled && GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.NONE; + if (wrap) GbufferPrograms.beginBlockEntities(); + try { + bufferSource.endBatch(hook); + instancedRenderer.endFrame(); + AngelicaBufferSource.rebindPass(); + BatchingFontRenderer.flushDeferredText(); + } finally { + if (wrap) GbufferPrograms.endBlockEntities(); + entityRenderer.disableLightmap(0); + GLStateManager.glDepthMask(savedDepthMask); + if (savedBlend) GLStateManager.enableBlend(); else GLStateManager.disableBlend(); + GLStateManager.tryBlendFuncSeparate(savedSrcRgb, savedDstRgb, savedSrcAlpha, savedDstAlpha); + if (savedAlphaTest) GLStateManager.enableAlphaTest(); else GLStateManager.disableAlphaTest(); + GLStateManager.glAlphaFunc(savedAlphaFunc, savedAlphaRef); + } + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private long lastRebuilds, lastRetainedDraws, lastStreamed, lastInstInstances; + private long lastSummaryNanos; + + public String getDebugSummaryLine() { + long rebuilds = 0, retainedDraws = 0, streamed = 0, instInstances = 0, retainedBytes = 0; + int groupCount = 0, streamingCount = 0; + for (int i = 0; i < PASS_COUNT; i++) { + final RetainedTesrGroups r = retained[i]; + rebuilds += r.rebuilds; + retainedDraws += r.retainedDraws; + streamed += r.streamedInstances; + instInstances += r.instancedInstances; + retainedBytes += r.retainedBytes(); + groupCount += r.groupCount(); + streamingCount += r.streamingGroupCount(); + } + final long now = System.nanoTime(); + final long elapsed = now - lastSummaryNanos; + final String line = String.format("TESR: %d grp (%d strm), reb %d/s, drw %d/s, inst %d/s, stream %d/s, mem %.1fMB", + groupCount, streamingCount, + perSecond(rebuilds - lastRebuilds, elapsed), + perSecond(retainedDraws - lastRetainedDraws, elapsed), + perSecond(instInstances - lastInstInstances, elapsed), + perSecond(streamed - lastStreamed, elapsed), + (retainedBytes + bufferSource.allocatedBytes() + instancedRenderer.meshBytes()) / 1048576.0); + lastSummaryNanos = now; + lastRebuilds = rebuilds; + lastRetainedDraws = retainedDraws; + lastStreamed = streamed; + lastInstInstances = instInstances; + return line; + } + + private static long perSecond(long delta, long elapsedNanos) { + return elapsedNanos <= 0 ? 0 : delta * 1_000_000_000L / elapsedNanos; + } + + public List getDebugDetailStrings() { + long retainedBytes = 0; + for (int i = 0; i < PASS_COUNT; i++) { + retainedBytes += retained[i].retainedBytes(); + } + final String mem = String.format("TESR mem: ret %.1fMB, seg %.1fMB, tmpl %d/%.1fMB, cache %d", + retainedBytes / 1048576.0, bufferSource.allocatedBytes() / 1048576.0, + instancedRenderer.meshCount(), instancedRenderer.meshBytes() / 1048576.0, + AngelicaTesrMeshCache.INSTANCE.size()); + final String attribution = rebuildAttributionLine(); + return attribution == null ? Arrays.asList(mem) : Arrays.asList(mem, attribution); + } + + private final ObjectArrayList rebuilders = new ObjectArrayList<>(); + + private String rebuildAttributionLine() { + rebuilders.clear(); + for (int i = 0; i < PASS_COUNT; i++) { + retained[i].collectRebuilders(rebuilders); + } + if (rebuilders.isEmpty()) return null; + rebuilders.sort((a, b) -> Integer.compare(b.rebuildsWindow, a.rebuildsWindow)); + final StringBuilder sb = new StringBuilder("TESR reb:"); + final int shown = Math.min(3, rebuilders.size()); + for (int i = 0; i < shown; i++) { + final RetainedTesrGroups.Group group = rebuilders.get(i); + if (i > 0) sb.append(','); + sb.append(' ').append(group.rebuildsWindow).append("x ").append(RetainedTesrGroups.attribution(group)).append(' ').append(group.builtVertexCount).append('v'); + } + if (rebuilders.size() > shown) { + sb.append(" +").append(rebuilders.size() - shown); + } + for (int i = 0, n = rebuilders.size(); i < n; i++) { + rebuilders.get(i).rebuildsWindow = 0; + } + rebuilders.clear(); + return sb.toString(); + } + + public long statRebuilds() { return sumStat(0); } + public long statRetainedDraws() { return sumStat(1); } + public long statInstancedDraws() { return sumStat(2); } + public long statInstancedInstances() { return sumStat(3); } + public long statStreamedInstances() { return sumStat(4); } + public long statVolatilePromotions() { return sumStat(5); } + + private long sumStat(int which) { + long v = 0; + for (int i = 0; i < PASS_COUNT; i++) { + final RetainedTesrGroups r = retained[i]; + v += switch (which) { + case 0 -> r.rebuilds; + case 1 -> r.retainedDraws; + case 2 -> r.instancedDraws; + case 3 -> r.instancedInstances; + case 4 -> r.streamedInstances; + default -> r.streamPromotions; + }; + } + return v; + } + + public long statRetainedBytes() { + long v = 0; + for (int i = 0; i < PASS_COUNT; i++) { + v += retained[i].retainedBytes(); + } + return v; + } + + public long statBufferSourceBytes() { + return bufferSource.allocatedBytes(); + } + + private final MeshBuffer immediateMesh = new MeshBuffer(); + private ByteBuffer immediateScratch; + + private void drawImmediate(TemplateBuffer template, ResourceLocation texture, TesrMaterial material, int packedLight, int colorABGR) { + final int vertexCount = template.vertexCount; + if (vertexCount == 0) return; + final VertexFormat format = SegmentedBufferBuilder.FORMAT; + final int bytes = format.getVertexSize() * vertexCount; + immediateScratch = MeshBuffer.ensureCapacity(immediateScratch, bytes, false); + immediateScratch.clear(); + final long addr = memAddress0(immediateScratch); + final long end = VertexTransform.writeInstance(addr, format, template, identity, scratchVec, colorABGR, packedLight, null); + immediateScratch.position((int) (end - addr)); + immediateScratch.flip(); + final RenderLayer layer = noPassLayerFor(texture, material); + GLStateManager.glPushAttrib(AngelicaBufferSource.SAVED_STATE_BITS); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + layer.startDrawing(); + immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount); + immediateMesh.render(); + layer.endDrawing(); + GLStateManager.glPopAttrib(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatch.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatch.java new file mode 100644 index 000000000..a8639f0ad --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatch.java @@ -0,0 +1,40 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; + +public final class TesrProviderDispatch { + + private TesrProviderDispatch() {} + + public static int resolveBlockEntityId(TileEntity te) { + if (te == null) return 0; + final Block block = te.getBlockType(); + if (block == null) return 0; + final Reference2ObjectMap matches = BlockRenderingSettings.INSTANCE.getBlockMetaMatches(); + if (matches == null) return 0; + final Int2IntMap metaMap = matches.get(block); + if (metaMap == null) return 0; + return Math.max(0, metaMap.get(te.getBlockMetadata())); + } + + public static boolean tryRender(Object renderer, TileEntity te, double x, double y, double z) { + if (!(renderer instanceof TesrMeshProvider provider)) return false; + final Object key = provider.angelica$meshKey(te); + if (key == null) return false; + + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(resolveBlockEntityId(te)); + GLStateManager.glPushMatrix(); + provider.angelica$transform(te, x, y, z); + AngelicaTesrMeshCache.INSTANCE.renderCached(key, provider.angelica$meshDirty(te), provider, te); + GLStateManager.glPopMatrix(); + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); + return true; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VanillaModelMeshes.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VanillaModelMeshes.java new file mode 100644 index 000000000..756f7bb8a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VanillaModelMeshes.java @@ -0,0 +1,136 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.minecraft.client.model.ModelChest; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.model.ModelSign; +import net.minecraft.client.model.ModelSkeletonHead; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; + +import java.util.HashMap; +import java.util.Map; + +/** Cached-mesh entry points for the vanilla chest/sign/skull TESR mixins. */ +public final class VanillaModelMeshes { + + private static final float MODEL_SCALE = 0.0625f; + private static final float LID_CLOSED_EPS = 1.0e-4f; + private static final TesrMaterial WHITE = TesrMaterial.builder().color(1f, 1f, 1f, 1f).build(); + private static final ResourceLocation SIGN_TEXTURE = new ResourceLocation("textures/entity/sign.png"); + + private static final class ChestKeys { + final Object closed = new Object(); + final Object base = new Object(); + final Object lid = new Object(); + final Object knob = new Object(); + } + + private static final Reference2ObjectOpenHashMap SINGLE_CHEST_KEYS = new Reference2ObjectOpenHashMap<>(); + private static final Reference2ObjectOpenHashMap DOUBLE_CHEST_KEYS = new Reference2ObjectOpenHashMap<>(); + private static final Object KEY_SIGN_STANDING = new Object(); + private static final Object KEY_SIGN_WALL = new Object(); + + private record SkullKey(ModelSkeletonHead model, ResourceLocation texture) {} + + private static final Map SKULL_KEYS = new HashMap<>(); + + private static final Builder BUILDER = new Builder(); + + private VanillaModelMeshes() {} + + public static void renderChest(ModelChest model, ResourceLocation texture, boolean isDouble) { + final float lidAngle = model.chestLid.rotateAngleX; + final ChestKeys keys = chestKeys(texture, isDouble); + if (Math.abs(lidAngle) <= LID_CLOSED_EPS) { + BUILDER.set(texture, MODEL_SCALE, model.chestLid, model.chestKnob, model.chestBelow); + AngelicaTesrMeshCache.INSTANCE.renderCached(keys.closed, BUILDER); + return; + } + BUILDER.set(texture, MODEL_SCALE, model.chestBelow, null, null); + AngelicaTesrMeshCache.INSTANCE.renderCached(keys.base, BUILDER); + renderRotatedPart(keys.lid, texture, model.chestLid, lidAngle); + renderRotatedPart(keys.knob, texture, model.chestKnob, lidAngle); + } + + private static ChestKeys chestKeys(ResourceLocation texture, boolean isDouble) { + final Reference2ObjectOpenHashMap keys = isDouble ? DOUBLE_CHEST_KEYS : SINGLE_CHEST_KEYS; + ChestKeys k = keys.get(texture); + if (k == null) { + k = new ChestKeys(); + keys.put(texture, k); + } + return k; + } + + private static void renderRotatedPart(Object key, ResourceLocation texture, ModelRenderer part, float angleX) { + GLStateManager.glPushMatrix(); + GLStateManager.glTranslatef(part.offsetX + part.rotationPointX * MODEL_SCALE, part.offsetY + part.rotationPointY * MODEL_SCALE, part.offsetZ + part.rotationPointZ * MODEL_SCALE); + GLStateManager.glRotatef(angleX * (180f / (float) Math.PI), 1.0f, 0.0f, 0.0f); + BUILDER.setLocal(texture, MODEL_SCALE, part); + AngelicaTesrMeshCache.INSTANCE.renderCached(key, BUILDER); + GLStateManager.glPopMatrix(); + } + + public static void renderSign(ModelSign model) { + final boolean standing = model.signStick.showModel; + BUILDER.set(SIGN_TEXTURE, MODEL_SCALE, model.signBoard, standing ? model.signStick : null, null); + AngelicaTesrMeshCache.INSTANCE.renderCached(standing ? KEY_SIGN_STANDING : KEY_SIGN_WALL, BUILDER); + } + + public static boolean renderSkull(ModelSkeletonHead model, ResourceLocation texture, float yawDegrees, float pitchDegrees, float scale) { + if (texture == null) { + return false; + } + final Object key = SKULL_KEYS.computeIfAbsent(new SkullKey(model, texture), k -> new Object()); + GLStateManager.glPushMatrix(); + if (yawDegrees != 0.0f) { + GLStateManager.glRotatef(yawDegrees, 0.0f, 1.0f, 0.0f); + } + if (pitchDegrees != 0.0f) { + GLStateManager.glRotatef(pitchDegrees, 1.0f, 0.0f, 0.0f); + } + BUILDER.set(texture, scale, model.skeletonHead, null, null); + AngelicaTesrMeshCache.INSTANCE.renderCached(key, BUILDER); + GLStateManager.glPopMatrix(); + return true; + } + + private static final class Builder implements TesrMeshBuilder { + private ResourceLocation texture; + private float scale; + private ModelRenderer part0, part1, part2; + private boolean partLocal; + + void set(ResourceLocation texture, float scale, ModelRenderer part0, ModelRenderer part1, ModelRenderer part2) { + this.texture = texture; + this.scale = scale; + this.part0 = part0; + this.part1 = part1; + this.part2 = part2; + this.partLocal = false; + } + + void setLocal(ResourceLocation texture, float scale, ModelRenderer part) { + set(texture, scale, part, null, null); + this.partLocal = true; + } + + @Override + public void angelica$build(TesrMeshSink sink) { + final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, texture, WHITE); + if (partLocal) { + ModelPartMesher.emitPartLocal(t, part0, scale); + return; + } + ModelPartMesher.emitPart(t, part0, scale); + if (part1 != null) ModelPartMesher.emitPart(t, part1, scale); + if (part2 != null) ModelPartMesher.emitPart(t, part2, scale); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransform.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransform.java new file mode 100644 index 000000000..8d9a4264a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransform.java @@ -0,0 +1,162 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import net.coderbot.iris.vertices.NormI8; +import org.joml.Matrix4fc; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL11; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_LIGHTMAP; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX; + +public final class VertexTransform { + + private VertexTransform() {} + + private static final int PACKED_UP = NormI8.pack(0f, 1f, 0f, 0f); + + public static int[] decode(long srcAddr, VertexFormat srcFormat, int vertexCount, int drawMode) { + final int[] out = decode(srcAddr, srcFormat, vertexCount); + seedMissingNormals(out, vertexCount, drawMode); + return out; + } + + static void seedMissingNormals(int[] out, int vertexCount, int drawMode) { + final int prim = switch (drawMode) { + case GL11.GL_QUADS -> 4; + case GL11.GL_TRIANGLES -> 3; + default -> 0; + }; + if (prim != 0) { + outer: + for (int p = 0; p + prim <= vertexCount; p += prim) { + for (int v = p; v < p + prim; v++) { + if (out[v * VERTEX_SIZE | NORMAL_INDEX] != 0) continue outer; + } + final int packed = packedFaceNormal(out, p, prim); + for (int v = p; v < p + prim; v++) { + out[v * VERTEX_SIZE | NORMAL_INDEX] = packed; + } + } + } + for (int v = 0; v < vertexCount; v++) { + if (out[v * VERTEX_SIZE | NORMAL_INDEX] == 0) { + out[v * VERTEX_SIZE | NORMAL_INDEX] = PACKED_UP; + } + } + } + + private static int packedFaceNormal(int[] out, int firstVertex, int prim) { + final int b0 = firstVertex * VERTEX_SIZE; + final int b1 = (firstVertex + 1) * VERTEX_SIZE; + final int b2 = (firstVertex + 2) * VERTEX_SIZE; + final float e1x, e1y, e1z, e2x, e2y, e2z; + if (prim == 4) { + final int b3 = (firstVertex + 3) * VERTEX_SIZE; + e1x = Float.intBitsToFloat(out[b2 | X_INDEX]) - Float.intBitsToFloat(out[b0 | X_INDEX]); + e1y = Float.intBitsToFloat(out[b2 | Y_INDEX]) - Float.intBitsToFloat(out[b0 | Y_INDEX]); + e1z = Float.intBitsToFloat(out[b2 | Z_INDEX]) - Float.intBitsToFloat(out[b0 | Z_INDEX]); + e2x = Float.intBitsToFloat(out[b3 | X_INDEX]) - Float.intBitsToFloat(out[b1 | X_INDEX]); + e2y = Float.intBitsToFloat(out[b3 | Y_INDEX]) - Float.intBitsToFloat(out[b1 | Y_INDEX]); + e2z = Float.intBitsToFloat(out[b3 | Z_INDEX]) - Float.intBitsToFloat(out[b1 | Z_INDEX]); + } else { + final float x0 = Float.intBitsToFloat(out[b0 | X_INDEX]); + final float y0 = Float.intBitsToFloat(out[b0 | Y_INDEX]); + final float z0 = Float.intBitsToFloat(out[b0 | Z_INDEX]); + e1x = Float.intBitsToFloat(out[b1 | X_INDEX]) - x0; + e1y = Float.intBitsToFloat(out[b1 | Y_INDEX]) - y0; + e1z = Float.intBitsToFloat(out[b1 | Z_INDEX]) - z0; + e2x = Float.intBitsToFloat(out[b2 | X_INDEX]) - x0; + e2y = Float.intBitsToFloat(out[b2 | Y_INDEX]) - y0; + e2z = Float.intBitsToFloat(out[b2 | Z_INDEX]) - z0; + } + final float nx = e1y * e2z - e1z * e2y; + final float ny = e1z * e2x - e1x * e2z; + final float nz = e1x * e2y - e1y * e2x; + final float lenSq = nx * nx + ny * ny + nz * nz; + if (lenSq < 1.0e-12f) return PACKED_UP; + final float invLen = (float) (1.0 / Math.sqrt(lenSq)); + return NormI8.pack(nx * invLen, ny * invLen, nz * invLen, 0f); + } + + public static int[] decode(long srcAddr, VertexFormat srcFormat, int vertexCount) { + final VertexFormatElement[] elems = srcFormat.elementsArray; + final int n = elems.length; + final int[] offsets = new int[n]; + int off = 0; + for (int i = 0; i < n; i++) { + offsets[i] = off; + off += elems[i].getByteSize(); + } + final int stride = srcFormat.getVertexSize(); + final int[] out = new int[vertexCount * VERTEX_SIZE]; + for (int v = 0; v < vertexCount; v++) { + final long base = srcAddr + (long) v * stride; + final int vbase = v * VERTEX_SIZE; + out[vbase | COLOR_INDEX] = DEFAULT_COLOR; + out[vbase | LIGHT_INDEX] = DEFAULT_LIGHTMAP; + for (int i = 0; i < n; i++) { + final long p = base + offsets[i]; + switch (elems[i].getUsage()) { + case POSITION -> { + out[vbase | X_INDEX] = memGetInt(p); + out[vbase | Y_INDEX] = memGetInt(p + 4); + out[vbase | Z_INDEX] = memGetInt(p + 8); + } + case PRIMARY_UV -> { + out[vbase | TEX_X_INDEX] = memGetInt(p); + out[vbase | TEX_Y_INDEX] = memGetInt(p + 4); + } + case NORMAL -> out[vbase | NORMAL_INDEX] = memGetInt(p); + case COLOR -> out[vbase | COLOR_INDEX] = memGetInt(p); + case SECONDARY_UV -> out[vbase | LIGHT_INDEX] = memGetInt(p); + default -> {} + } + } + } + return out; + } + + public static long writeInstance(long destPtr, VertexFormat destFormat, TemplateBuffer template, Matrix4fc mv, Vector3f scratch, int colorABGR, int packedLight, Matrix4fc texMatrix) { + final int[] src = template.data; + final int[] work = template.work; + final int vertexCount = template.vertexCount; + for (int v = 0; v < vertexCount; v++) { + final int vbase = v * VERTEX_SIZE; + work[vbase | COLOR_INDEX] = mulColor(src[vbase | COLOR_INDEX], colorABGR); + work[vbase | LIGHT_INDEX] = packedLight; + if (texMatrix != null) { + final float u = Float.intBitsToFloat(src[vbase | TEX_X_INDEX]); + final float t = Float.intBitsToFloat(src[vbase | TEX_Y_INDEX]); + work[vbase | TEX_X_INDEX] = Float.floatToRawIntBits(texMatrix.m00() * u + texMatrix.m10() * t + texMatrix.m30()); + work[vbase | TEX_Y_INDEX] = Float.floatToRawIntBits(texMatrix.m01() * u + texMatrix.m11() * t + texMatrix.m31()); + } else { + work[vbase | TEX_X_INDEX] = src[vbase | TEX_X_INDEX]; + work[vbase | TEX_Y_INDEX] = src[vbase | TEX_Y_INDEX]; + } + } + return destFormat.writeToBuffer0(destPtr, work, vertexCount * VERTEX_SIZE, mv, scratch); + } + + static int mulColor(int a, int b) { + if (a == -1) return b; + if (b == -1) return a; + return mul8(a, b, 0) | mul8(a, b, 8) | mul8(a, b, 16) | mul8(a, b, 24); + } + + private static int mul8(int a, int b, int shift) { + final int t = ((a >>> shift) & 0xFF) * ((b >>> shift) & 0xFF) + 0x80; + return (((t + (t >> 8)) >> 8) & 0xFF) << shift; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/SdlShadowVoxelizationSink.java b/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/SdlShadowVoxelizationSink.java new file mode 100644 index 000000000..854765b8e --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/SdlShadowVoxelizationSink.java @@ -0,0 +1,89 @@ +package com.gtnewhorizons.angelica.rendering.voxelization; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; +import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor; +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; +import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; + +public final class SdlShadowVoxelizationSink implements ShadowVoxelizer.Sink { + + private static final Logger LOG = LogManager.getLogger("Angelica"); + private static final int SSBO_BINDING = RwImageStoreExtractor.VG_VBUF_SSBO_BINDING; + + private static int encodersThisFrame; + private static int dispatchesThisFrame; + private static int regionsThisFrame; + + private boolean warnedBindFailure; + private boolean warnedBeginFailure; + private long pass; + private int pendingVertexBuffer; + private float pendingX; + private float pendingY; + private float pendingZ; + + private static SDLGPURenderBackend sdl() { + return (SDLGPURenderBackend) BackendManager.RENDER_BACKEND; + } + + @Override + public boolean region(RenderRegion region, GlVertexFormat format, float offsetX, float offsetY, float offsetZ) { + final RenderRegion.DeviceResources resources = region.getResources(format); + if (resources == null) return false; + final GlBuffer vertexBuffer = resources.getVertexBuffer(); + if (vertexBuffer == null || vertexBuffer.handle() == 0) return false; + pendingVertexBuffer = vertexBuffer.handle(); + pendingX = offsetX; + pendingY = offsetY; + pendingZ = offsetZ; + regionsThisFrame++; + return true; + } + + @Override + public boolean range(int vertexOffset, int vertexCount) { + if (pendingVertexBuffer != 0) { + if (!sdl().bindVoxelizationRegion(SSBO_BINDING, pendingVertexBuffer, pass, pendingX, pendingY, pendingZ)) { + if (!warnedBindFailure) { + warnedBindFailure = true; + LOG.warn("shadow voxelization: could not bind region vertex buffer {} at SSBO slot {}", pendingVertexBuffer, SSBO_BINDING); + } + return false; + } + pendingVertexBuffer = 0; + } + if (pass == 0) { + pass = sdl().beginVoxelizationBatch(SSBO_BINDING); + if (pass != 0) encodersThisFrame++; + if (pass == 0) { + if (!warnedBeginFailure) { + warnedBeginFailure = true; + LOG.warn("shadow voxelization: compute encoder refused; no voxel writes this pass"); + } + return false; + } + } + sdl().voxelizeRange(pass, vertexOffset, vertexCount); + dispatchesThisFrame++; + return true; + } + + public static int takeEncoders() { final int n = encodersThisFrame; encodersThisFrame = 0; return n; } + + public static int takeDispatches() { final int n = dispatchesThisFrame; dispatchesThisFrame = 0; return n; } + + public static int takeRegions() { final int n = regionsThisFrame; regionsThisFrame = 0; return n; } + + @Override + public void finish() { + if (pass != 0) { + sdl().endVoxelizationBatch(pass); + pass = 0; + } + pendingVertexBuffer = 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizer.java new file mode 100644 index 000000000..c73fead06 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizer.java @@ -0,0 +1,95 @@ +package com.gtnewhorizons.angelica.rendering.voxelization; + +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; + +import java.util.Iterator; + +public final class ShadowVoxelizer { + + public interface Sink { + /** @return false to skip this region */ + boolean region(RenderRegion region, GlVertexFormat format, float offsetX, float offsetY, float offsetZ); + + /** @return false to skip the rest of this region; later regions are still attempted */ + boolean range(int vertexOffset, int vertexCount); + + void finish(); + } + + public void walkPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, GlVertexFormat format, CameraTransform camera, CameraTransform occlusionCamera, boolean useBlockFaceCulling, Sink sink) { + try { + final Iterator it = renderLists.iterator(renderPass.isReverseOrder()); + while (it.hasNext()) { + walkRegion(it.next(), renderPass, format, camera, occlusionCamera, useBlockFaceCulling, sink); + } + } finally { + sink.finish(); + } + } + + private static void walkRegion(ChunkRenderList list, TerrainRenderPass renderPass, GlVertexFormat format, CameraTransform camera, CameraTransform occlusionCamera, boolean useBlockFaceCulling, Sink sink) { + final RenderRegion region = list.getRegion(); + final SectionRenderDataStorage storage = region.getStorage(renderPass); + if (storage == null) return; + + final int sectionCount = list.getSectionsWithGeometryCount(); + if (sectionCount == 0) return; + + final byte[] sections = list.getSectionsWithGeometry(); + final SectionRenderDataUnsafe.Strategy layout = storage.getStorageStrategy(); + final ChunkPrimitiveType primitiveType = storage.getPrimitiveType(); + final int regionChunkX = region.getChunkX(); + final int regionChunkY = region.getChunkY(); + final int regionChunkZ = region.getChunkZ(); + boolean bound = false; + + for (int i = 0; i < sectionCount; i++) { + final int sectionIndex = sections[i] & 0xFF; + final long pMeshData = storage.getDataPointer(sectionIndex); + int slices = useBlockFaceCulling + ? BatchAssembler.getVisibleFaces(occlusionCamera.intX, occlusionCamera.intY, occlusionCamera.intZ, + regionChunkX + LocalSectionIndex.unpackX(sectionIndex), + regionChunkY + LocalSectionIndex.unpackY(sectionIndex), + regionChunkZ + LocalSectionIndex.unpackZ(sectionIndex)) + : ModelQuadFacing.ALL; + slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData); + slices &= 0x7F; + if (slices == 0) continue; + + final long runs = BatchAssembler.packRuns(slices); + final int runCount = BatchAssembler.runCount(runs); + for (int run = 0; run < runCount; run++) { + final int startVertex = layout.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run)); + final int endVertex = layout.getRunVertexEnd(pMeshData, BatchAssembler.runLast(runs, run), primitiveType); + final int vertexCount = endVertex - startVertex; + if (vertexCount <= 0) continue; + + if (!bound) { + if (!sink.region(region, format, + cameraRelative(region.getOriginX(), camera.intX, camera.fracX), + cameraRelative(region.getOriginY(), camera.intY, camera.fracY), + cameraRelative(region.getOriginZ(), camera.intZ, camera.fracZ))) { + return; + } + bound = true; + } + if (!sink.range(startVertex, vertexCount)) return; + } + } + } + + private static float cameraRelative(int originBlock, int cameraBlock, float cameraFrac) { + return (originBlock - cameraBlock) - cameraFrac; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java index e00393a56..5716fd0be 100644 --- a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java +++ b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java @@ -16,6 +16,8 @@ import java.awt.image.BufferedImage; import java.io.InputStream; import java.nio.ByteBuffer; +import static org.joml.Math.clamp; + /** * Maybe overcomplicated, but it's required to bridge the gap between the modern glint texture and white texture 1.7.10 * has. Some shaders are able to render the glint just fine as they seem to have some amount of support for older @@ -159,8 +161,6 @@ public final class ShaderGlint { } private static int clamp8(float v) { - final int i = Math.round(v * 255.0F); - if (i < 0) return 0; - return Math.min(i, 255); + return clamp(0, 255, Math.round(v * 255.0F)); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java index 93345fc3e..8d32e1512 100644 --- a/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java +++ b/src/main/java/com/gtnewhorizons/angelica/utils/MipmapGenerator.java @@ -4,6 +4,8 @@ import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import org.embeddedt.embeddium.api.util.ColorARGB; import org.embeddedt.embeddium.impl.texture.MipmapHelper; +import static org.joml.Math.clamp; + /** * Mipmap downsampling for atlas sprites, replacing vanilla's {@code TextureUtil.generateMipmapData}. */ @@ -185,11 +187,7 @@ public final class MipmapGenerator { } private static float scaledAlpha(int color, float alphaFactor) { - return clamp01(ColorARGB.unpackAlpha(color) * alphaFactor); - } - - private static float clamp01(float value) { - return value < 0.0f ? 0.0f : Math.min(value, 1.0f); + return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor); } static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef, int border) { @@ -221,7 +219,7 @@ public final class MipmapGenerator { final int color = image[i]; final int rawAlpha = ColorARGB.unpackAlpha(color); final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f; - final int alpha = (int) Math.floor(clamp01(rawAlpha / 255.0f * bestScale + bias) * 255.0f); + final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f); image[i] = ColorARGB.withAlpha(color, alpha); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/Mipmaps.java b/src/main/java/com/gtnewhorizons/angelica/utils/Mipmaps.java deleted file mode 100644 index c7df94c19..000000000 --- a/src/main/java/com/gtnewhorizons/angelica/utils/Mipmaps.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gtnewhorizons.angelica.utils; - -public class Mipmaps { - - private static final float[] VALS = new float[256]; - - public static float get(int i) { - return VALS[i & 0xFF]; - } - - public static int getColorComponent(int one, int two, int three, int four, int bits) { - final float f = Mipmaps.get(one >> bits); - final float g = Mipmaps.get(two >> bits); - final float h = Mipmaps.get(three >> bits); - final float i = Mipmaps.get(four >> bits); - final float j = (float) Math.pow((f + g + h + i) * 0.25, 0.45454545454545453); - return (int) (j * 255.0); - } - - static { - for (int i = 0; i < VALS.length; ++i) { - VALS[i] = (float) Math.pow((float) i / 255.0F, 2.2); - } - } -} diff --git a/src/main/java/com/prupe/mcpatcher/cc/ColorizeWorld.java b/src/main/java/com/prupe/mcpatcher/cc/ColorizeWorld.java index 152f895eb..e4321828b 100644 --- a/src/main/java/com/prupe/mcpatcher/cc/ColorizeWorld.java +++ b/src/main/java/com/prupe/mcpatcher/cc/ColorizeWorld.java @@ -101,7 +101,7 @@ public class ColorizeWorld { return null; } else { if (fogBlendRadius > 0) { - map = new ColorMapBase.Blended(map, fogBlendRadius); + map = new ColorMapBase.Blended(new ColorMapBase.BlockCached(map), fogBlendRadius); } map = new ColorMapBase.Cached(map); map = new ColorMapBase.Smoothed(map, 3000.0f); diff --git a/src/main/java/com/prupe/mcpatcher/mal/biome/ColorMapBase.java b/src/main/java/com/prupe/mcpatcher/mal/biome/ColorMapBase.java index 359872436..e589c24d1 100644 --- a/src/main/java/com/prupe/mcpatcher/mal/biome/ColorMapBase.java +++ b/src/main/java/com/prupe/mcpatcher/mal/biome/ColorMapBase.java @@ -1,5 +1,7 @@ package com.prupe.mcpatcher.mal.biome; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -199,6 +201,66 @@ abstract public class ColorMapBase { } } + public static final class BlockCached implements IColorMap { + + private static final int MAX_ENTRIES = 4096; + + private final IColorMap parent; + private final Long2ObjectOpenHashMap cache = new Long2ObjectOpenHashMap<>(); + private IBlockAccess lastBlockAccess; + + public BlockCached(IColorMap parent) { + this.parent = parent; + } + + @Override + public String toString() { + return parent.toString(); + } + + @Override + public boolean isHeightDependent() { + return parent.isHeightDependent(); + } + + @Override + public int getColorMultiplier() { + return parent.getColorMultiplier(); + } + + @Override + public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { + return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k)); + } + + @Override + public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { + if (blockAccess != lastBlockAccess) { + cache.clear(); + lastBlockAccess = blockAccess; + } + final long key = (((long) i & 0x3FFFFFFL) << 38) | (((long) k & 0x3FFFFFFL) << 12) | ((long) j & 0xFFFL); + float[] color = cache.get(key); + if (color == null) { + final float[] src = parent.getColorMultiplierF(blockAccess, i, j, k); + color = new float[] { src[0], src[1], src[2] }; + if (cache.size() >= MAX_ENTRIES) cache.clear(); + cache.put(key, color); + } + return color; + } + + @Override + public void claimResources(Collection resources) { + parent.claimResources(resources); + } + + @Override + public IColorMap copy() { + return new BlockCached(parent.copy()); + } + } + public static final class Smoothed implements IColorMap { private final IColorMap parent; diff --git a/src/main/java/com/prupe/mcpatcher/mal/biome/ColorUtils.java b/src/main/java/com/prupe/mcpatcher/mal/biome/ColorUtils.java index d83bdfb9b..9b1c68321 100644 --- a/src/main/java/com/prupe/mcpatcher/mal/biome/ColorUtils.java +++ b/src/main/java/com/prupe/mcpatcher/mal/biome/ColorUtils.java @@ -1,6 +1,6 @@ package com.prupe.mcpatcher.mal.biome; -import net.minecraft.util.MathHelper; +import org.joml.Math; public class ColorUtils { @@ -28,6 +28,6 @@ public class ColorUtils { } public static float clamp(float f) { - return MathHelper.clamp_float(f, 0.0f, 1.0f); + return Math.clamp(0.0f, 1.0f, f); } } diff --git a/src/main/java/jss/notfine/gui/NotFineGameOptionPages.java b/src/main/java/jss/notfine/gui/NotFineGameOptionPages.java index 4dd21f4d3..db2e581fc 100644 --- a/src/main/java/jss/notfine/gui/NotFineGameOptionPages.java +++ b/src/main/java/jss/notfine/gui/NotFineGameOptionPages.java @@ -2,6 +2,7 @@ package jss.notfine.gui; import com.google.common.collect.ImmutableList; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.GLStateManager; import jss.notfine.config.NotFineConfig; import jss.notfine.core.Settings; @@ -68,7 +69,7 @@ public class NotFineGameOptionPages { .setControl(TickBoxControl::new) .setBinding((opts, value) -> { opts.enableVsync = value; - Display.setVSyncEnabled(opts.enableVsync); + GLStateManager.setVSyncEnabled(opts.enableVsync); }, opts -> opts.enableVsync) .setImpact(OptionImpact.VARIES) .build()) @@ -413,14 +414,6 @@ public class NotFineGameOptionPages { .setBinding((opts, value) -> opts.performance.useNoErrorGLContext = value, opts -> opts.performance.useNoErrorGLContext) .setFlags(OptionFlag.REQUIRES_GAME_RESTART) .build()) - .add(OptionImpl.createBuilder(boolean.class, sodiumOpts) - .setName(I18n.format("sodium.options.use_gl_state_cache.name")) - .setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip")) - .setControl(TickBoxControl::new) - .setImpact(OptionImpact.EXTREME) - .setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE) - .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) - .build()) .build()); return new OptionPage(I18n.format("options.button.other"), ImmutableList.copyOf(groups)); diff --git a/src/main/java/kroppeb/stareval/function/Type.java b/src/main/java/kroppeb/stareval/function/Type.java index d5eed1e20..5d355de0f 100644 --- a/src/main/java/kroppeb/stareval/function/Type.java +++ b/src/main/java/kroppeb/stareval/function/Type.java @@ -2,7 +2,7 @@ package kroppeb.stareval.function; import kroppeb.stareval.expression.ConstantExpression; import kroppeb.stareval.function.TypedFunction.Parameter; -import net.coderbot.iris.gl.uniform.UniformType; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; import net.coderbot.iris.parsing.MatrixType; import net.coderbot.iris.parsing.VectorType; diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java index 411ded1f7..c871310db 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java @@ -17,7 +17,11 @@ import com.cardinalstar.cubicchunks.api.compat.CubicChunksVideoSettings; import com.google.common.collect.ImmutableList; import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.rendering.celeritas.MultiDrawModeResolver; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.config.GpuCullingMode; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import cpw.mods.fml.common.Optional.Method; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; import jss.notfine.core.Settings; @@ -140,7 +144,7 @@ public class SodiumGameOptionPages { .setControl(TickBoxControl::new) .setBinding((opts, value) -> { opts.enableVsync = value; - Display.setVSyncEnabled(opts.enableVsync); + GLStateManager.setVSyncEnabled(opts.enableVsync); }, opts -> opts.enableVsync) .setImpact(OptionImpact.VARIES) .build()) @@ -300,8 +304,7 @@ public class SodiumGameOptionPages { .setName(I18n.format("sodium.options.multidraw_mode.name")) .setTooltip(I18n.format("sodium.options.multidraw_mode.tooltip")) .setControl(o -> { - boolean indirectSupported = GLStateManager.capabilities != null && (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_multi_draw_indirect); - MultiDrawMode[] allowed = indirectSupported ? MultiDrawMode.values() : new MultiDrawMode[]{MultiDrawMode.DIRECT, MultiDrawMode.INDIVIDUAL}; + MultiDrawMode[] allowed = MultiDrawModeResolver.indirectSupported() ? MultiDrawMode.values() : new MultiDrawMode[]{MultiDrawMode.DIRECT, MultiDrawMode.INDIVIDUAL}; return new CyclingControl<>(o, MultiDrawMode.class, allowed); }) .setBinding((opts, value) -> opts.advanced.multiDrawMode = value, opts -> opts.advanced.multiDrawMode) @@ -373,6 +376,14 @@ public class SodiumGameOptionPages { .setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling) .build() ) + .add(OptionImpl.createBuilder(boolean.class, sodiumOpts) + .setName(I18n.format("sodium.options.section_gated_tesr_culling.name")) + .setTooltip(I18n.format("sodium.options.section_gated_tesr_culling.tooltip")) + .setControl(TickBoxControl::new) + .setImpact(OptionImpact.MEDIUM) + .setBinding((opts, value) -> opts.performance.sectionGatedTesrCulling = value, opts -> opts.performance.sectionGatedTesrCulling) + .build() + ) .add(OptionImpl.createBuilder(boolean.class, sodiumOpts) .setName(I18n.format("sodium.options.use_particle_culling.name")) .setTooltip(I18n.format("sodium.options.use_particle_culling.tooltip")) @@ -439,6 +450,25 @@ public class SodiumGameOptionPages { ) .build()); + final OptionImpl gpuCullingMode = + OptionImpl.createBuilder(GpuCullingMode.class, angelicaOpts) + .setName(I18n.format("options.angelica.gpuCullingMode")) + .setTooltip(I18n.format("options.angelica.gpuCullingMode.tooltip")) + .setControl(o -> new CyclingControl<>(o, GpuCullingMode.class, new GpuCullingMode[]{ + GpuCullingMode.CPU_ONLY, GpuCullingMode.COMPUTE})) + .setBinding((opts, value) -> { + AngelicaConfig.gpuCullingMode = value; + AngelicaConfig.applyGpuCullingMode(); + }, opts -> AngelicaConfig.gpuCullingMode) + .setImpact(OptionImpact.HIGH) + .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) + .setEnabled(true) + .build(); + gpuCullingMode.iris$dynamicallyEnable(GpuCulling::isAvailable); + groups.add(OptionGroup.createBuilder() + .add(gpuCullingMode) + .build()); + return new OptionPage(I18n.format("sodium.options.pages.advanced"), ImmutableList.copyOf(groups)); } diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java index cee483e4a..9aae01fd4 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptions.java @@ -5,7 +5,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.gtnewhorizons.angelica.AngelicaMod; -import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; import com.gtnewhorizons.angelica.proxy.ClientProxy; @@ -72,9 +71,6 @@ public class SodiumGameOptions { } public static boolean needsForcedSpritePadding() { - if (!AngelicaConfig.enableCeleritas) { - return false; - } final TextureFilterMode mode = filteringPossible() ? resolveFilterMode(ClientProxy.options().quality.textureFilterMode) : TextureFilterMode.NONE; @@ -148,14 +144,14 @@ public class SodiumGameOptions { config.quality.textureFilterMode = TextureFilterMode.RGSS; } - // Clamp render-ahead to 0 if GL 3.2 fences aren't available - if (GLStateManager.capabilities == null || !GLStateManager.capabilities.OpenGL32) { - config.performance.cpuRenderAheadLimit = 0; - } - - // Downgrade INDIRECT if hardware doesn't support it - if (config.advanced.multiDrawMode == MultiDrawMode.INDIRECT && (GLStateManager.capabilities == null || (!GLStateManager.capabilities.OpenGL43 && !GLStateManager.capabilities.GL_ARB_multi_draw_indirect))) { - config.advanced.multiDrawMode = MultiDrawMode.DIRECT; + if (GLStateManager.capabilities != null) { + if (!GLStateManager.capabilities.OpenGL32) { + config.performance.cpuRenderAheadLimit = 0; + } + if (config.advanced.multiDrawMode == MultiDrawMode.INDIRECT + && !GLStateManager.capabilities.OpenGL43 && !GLStateManager.capabilities.GL_ARB_multi_draw_indirect) { + config.advanced.multiDrawMode = MultiDrawMode.DIRECT; + } } try { @@ -218,6 +214,7 @@ public class SodiumGameOptions { public boolean animateOnlyVisibleTextures = true; public boolean useEntityCulling = true; + public boolean sectionGatedTesrCulling = true; public boolean useFogOcclusion = true; public boolean useBlockFaceCulling = true; public boolean useCompactVertexFormat = true; diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java new file mode 100644 index 000000000..5c3bf80ea --- /dev/null +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java @@ -0,0 +1,335 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +/** Collects geometry into per-RenderLayer buffers during a pass and draws it all at endBatch, one state bracket per layer. Based on Iris's FullyBufferedMultiBufferSource */ +public class AngelicaBufferSource implements Groupable { + public static final int SAVED_STATE_BITS = GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_LIGHTING_BIT | GL11.GL_TEXTURE_BIT; + + private static final int NUM_BUFFERS = 32; + + public enum GroupIdKind { BLOCK_ENTITY, ENTITY } + + public interface LayerDrawHook { + boolean hasDraws(RenderLayer layer); + void drawLayer(RenderLayer layer); + } + + private static final Comparator OPAQUE_ORDER = Comparator.comparingInt(BufferSegment::getBlockEntityId); + + private final SimpleRenderOrderManager renderOrderManager = new SimpleRenderOrderManager(); + private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS]; + private final Object2IntLinkedOpenHashMap affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS); + private final Map> typeToSegment = new Object2ObjectOpenHashMap<>(); + + private boolean prepared; + private final List order = new ArrayList<>(); + private boolean stateSaved; + private boolean anyIdSet; + private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY; + + public AngelicaBufferSource() { + for (int i = 0; i < builders.length; i++) { + builders[i] = new SegmentedBufferBuilder(); + } + affinities.defaultReturnValue(-1); + } + + public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) { + renderOrderManager.begin(type); + int affinity = affinities.getAndMoveToLast(type); + if (affinity == -1) { + if (affinities.size() < builders.length) { + affinity = affinities.size(); + } else { + affinity = affinities.removeFirstInt(); + } + affinities.put(type, affinity); + } + final SegmentedBufferBuilder builder = builders[affinity]; + builder.begin(type, blockEntityId); + return builder; + } + + public void declareUse(RenderLayer type) { + renderOrderManager.begin(type); + } + + public boolean isEmpty() { + for (SegmentedBufferBuilder builder : builders) { + if (!builder.isEmpty()) return false; + } + return true; + } + + private void ensurePrepared() { + if (prepared) return; + prepared = true; + clearSegmentLists(); + for (SegmentedBufferBuilder builder : builders) { + final List builderSegments = builder.getSegments(); + for (int i = 0, n = builderSegments.size(); i < n; i++) { + final BufferSegment segment = builderSegments.get(i); + typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment); + } + } + order.clear(); + final List renderOrder = renderOrderManager.getRenderOrder(); + for (int i = 0, n = renderOrder.size(); i < n; i++) { + order.add(renderOrder.get(i)); + } + renderOrderManager.reset(); + for (int i = 0, n = order.size(); i < n; i++) { + final RenderLayer layer = order.get(i); + if (getTransparencyType(layer) != TransparencyType.OPAQUE) continue; + final List segments = typeToSegment.get(layer); + if (segments != null) { + segments.sort(OPAQUE_ORDER); + } + } + affinities.clear(); + stateSaved = false; + anyIdSet = false; + } + + List prepare() { + ensurePrepared(); + return new ArrayList<>(order); + } + + List segmentsFor(RenderLayer layer) { + return typeToSegment.get(layer); + } + + public void endBatchWithType(TransparencyType type, LayerDrawHook hook) { + ensurePrepared(); + int keep = 0; + for (int i = 0, n = order.size(); i < n; i++) { + final RenderLayer layer = order.get(i); + if (getTransparencyType(layer) != type) { + order.set(keep++, layer); + continue; + } + drawLayer(layer, hook); + } + for (int i = order.size() - 1; i >= keep; i--) { + order.remove(i); + } + } + + public void endBatch(LayerDrawHook hook) { + ensurePrepared(); + for (int i = 0, n = order.size(); i < n; i++) { + drawLayer(order.get(i), hook); + } + order.clear(); + finish(); + } + + public void pauseBatch() { + releaseAttribState(); + clearCurrentId(); + } + + public void discard() { + order.clear(); + finish(); + } + + private void releaseAttribState() { + if (stateSaved) { + GLStateManager.glPopAttrib(); + stateSaved = false; + } + } + + private void clearCurrentId() { + if (!anyIdSet) return; + if (idKind == GroupIdKind.ENTITY) { + CapturedRenderingState.INSTANCE.setCurrentEntity(-1); + CapturedRenderingState.INSTANCE.setCurrentEntityColor(0f, 0f, 0f, 0f); + } else { + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); + } + anyIdSet = false; + } + + private void drawLayer(RenderLayer layer, LayerDrawHook hook) { + final List segments = typeToSegment.get(layer); + final boolean hasDynamic = segments != null && !segments.isEmpty(); + final boolean hasRetained = hook != null && hook.hasDraws(layer); + if (!hasDynamic && !hasRetained) return; + if (!stateSaved) { + stateSaved = true; + GLStateManager.glPushAttrib(SAVED_STATE_BITS); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + layer.startDrawing(); + if (hasDynamic) { + anyIdSet = true; + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + SegmentedBufferBuilder.LayerBuffer bound = null; + final boolean entityKind = idKind == GroupIdKind.ENTITY; + int currentId = Integer.MIN_VALUE; + int currentColor = 0; + boolean colorSet = false; + for (int i = 0, n = segments.size(); i < n; i++) { + final BufferSegment segment = segments.get(i); + if (entityKind && (!colorSet || segment.getEntityColor() != currentColor)) { + colorSet = true; + currentColor = segment.getEntityColor(); + setEntityColor(currentColor); + } + if (segment.getBlockEntityId() != currentId) { + currentId = segment.getBlockEntityId(); + applyIdAndRebind(currentId); + } + final SegmentedBufferBuilder.LayerBuffer owner = segment.getOwner(); + if (owner != bound) { + if (bound != null) bound.finishDraw(); + bound = owner; + bound.uploadForDraw(); + bound.setupDraw(); + } + bound.draw(segment.getFirstVertex(), segment.getVertexCount()); + } + if (bound != null) bound.finishDraw(); + GLStateManager.glPopMatrix(); + } + if (hasRetained) { + anyIdSet = true; + hook.drawLayer(layer); + } + layer.endDrawing(); + } + + private void clearSegmentLists() { + for (List segments : typeToSegment.values()) { + segments.clear(); + } + } + + private void finish() { + releaseAttribState(); + clearCurrentId(); + clearSegmentLists(); + final long now = System.currentTimeMillis(); + final long maxIdle = getTargetClearTime(); + for (SegmentedBufferBuilder builder : builders) { + builder.resetAndReclaim(now, maxIdle); + } + prepared = false; + } + + public void freeBuffers() { + for (SegmentedBufferBuilder builder : builders) { + builder.freeAll(); + } + typeToSegment.clear(); + order.clear(); + affinities.clear(); + renderOrderManager.reset(); + prepared = false; + } + + public long allocatedBytes() { + long bytes = 0; + for (SegmentedBufferBuilder builder : builders) { + bytes += builder.allocatedBytes(); + } + return bytes; + } + + private long getTargetClearTime() { + final long sizeInMiB = allocatedBytes() / 1024L / 1024L; + if (sizeInMiB > 5000) { + return 1_000; + } else if (sizeInMiB > 1000) { + return 5_000; + } + return 10_000; + } + + public void setIdKind(GroupIdKind kind) { + this.idKind = kind; + } + + public void applyIdAndRebind(int id) { + anyIdSet = true; + if (idKind == GroupIdKind.ENTITY) { + CapturedRenderingState.INSTANCE.setCurrentEntity(id); + rebindPass(); + } else { + setBlockEntityAndRebind(id); + } + } + + public void applyIdNoRebind(int id) { + anyIdSet = true; + if (idKind == GroupIdKind.ENTITY) { + CapturedRenderingState.INSTANCE.setCurrentEntity(id); + } else { + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id); + } + } + + public static void setEntityColor(int packed) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor( + ((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f, + (packed & 0xFF) / 255f, (packed >>> 24) / 255f); + } + + public static void setBlockEntityAndRebind(int blockEntityId) { + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntityId); + rebindPass(); + } + + public static void rebindPass() { + if (Iris.enabled) { + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (pipeline != null) { + pipeline.rebindCurrentPass(); + } + } + } + + static TransparencyType getTransparencyType(RenderLayer type) { + while (type instanceof WrappableRenderType wrappable) { + type = wrappable.unwrap(); + } + if (type instanceof BlendingStateHolder holder) { + return holder.getTransparencyType(); + } + return TransparencyType.GENERAL_TRANSPARENT; + } + + @Override + public void startGroup() { + renderOrderManager.startGroup(); + } + + @Override + public boolean maybeStartGroup() { + return renderOrderManager.maybeStartGroup(); + } + + @Override + public void endGroup() { + renderOrderManager.endGroup(); + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BatchVertexFormats.java b/src/main/java/net/coderbot/batchedentityrendering/impl/BatchVertexFormats.java new file mode 100644 index 000000000..b620ec46e --- /dev/null +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/BatchVertexFormats.java @@ -0,0 +1,43 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.writers.IVertexAttributeWriter; +import net.minecraft.client.renderer.Tessellator; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; + +public final class BatchVertexFormats { + public static final VertexFormatElement LIGHT_FLOAT_ELEMENT = new VertexFormatElement(1, VertexFormatElement.Type.FLOAT, VertexFormatElement.Usage.SECONDARY_UV, 2, VertexFlags.BRIGHTNESS_BIT, new FloatLightVertexAttributeWriter()); + public static final VertexFormat POSITION_COLOR_TEXTURE_LIGHTF_NORMAL = new VertexFormat(DefaultVertexFormat.POSITION_ELEMENT, DefaultVertexFormat.COLOR_ELEMENT, DefaultVertexFormat.TEXTURE_ELEMENT, LIGHT_FLOAT_ELEMENT, DefaultVertexFormat.NORMAL_ELEMENT); + + private BatchVertexFormats() {} + + private static final class FloatLightVertexAttributeWriter implements IVertexAttributeWriter { + @Override + public int writeAttribute(long pointer, int[] data, int index) { + final int light = data[index | LIGHT_INDEX]; + memPutFloat(pointer, light & 0xFFFF); + memPutFloat(pointer + 4, light >>> 16); + return 8; + } + + @Override + public int writeAttribute(long pointer, Tessellator tessellator) { + final int light = tessellator.brightness; + memPutFloat(pointer, light & 0xFFFF); + memPutFloat(pointer + 4, light >>> 16); + return 8; + } + + @Override + public int readAttribute(long pointer, Tessellator tessellator) { + tessellator.brightness = (((int) memGetFloat(pointer + 4)) << 16) | (((int) memGetFloat(pointer)) & 0xFFFF); + return 8; + } + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java b/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java index f46bbe951..7d4993560 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java @@ -1,25 +1,45 @@ package net.coderbot.batchedentityrendering.impl; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; -import lombok.Getter; - -import java.nio.ByteBuffer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; public class BufferSegment { - private final ByteBuffer slice; - @Getter private final RenderLayer type; + private final int blockEntityId; + private final int entityColor; + private final int firstVertex; + private final int vertexCount; + private final SegmentedBufferBuilder.LayerBuffer owner; - public BufferSegment(ByteBuffer slice, RenderLayer type) { - this.slice = slice; + public BufferSegment(RenderLayer type, int blockEntityId, int entityColor, int firstVertex, int vertexCount, SegmentedBufferBuilder.LayerBuffer owner) { this.type = type; - } - - public ByteBuffer getSlice() { - return slice; + this.blockEntityId = blockEntityId; + this.entityColor = entityColor; + this.firstVertex = firstVertex; + this.vertexCount = vertexCount; + this.owner = owner; } public RenderLayer getRenderType() { return type; } + + public int getBlockEntityId() { + return blockEntityId; + } + + public int getEntityColor() { + return entityColor; + } + + public int getFirstVertex() { + return firstVertex; + } + + public int getVertexCount() { + return vertexCount; + } + + public SegmentedBufferBuilder.LayerBuffer getOwner() { + return owner; + } } diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java b/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java new file mode 100644 index 000000000..ab02860c3 --- /dev/null +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java @@ -0,0 +1,217 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; +import com.gtnewhorizons.angelica.rendering.tesr.MeshBuffer; +import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import org.joml.Matrix4fc; +import org.joml.Vector3f; +import org.joml.Vector4fc; +import org.lwjgl.BufferUtils; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; + +public class SegmentedBufferBuilder { + + public static final VertexFormat FORMAT = BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL; + + static final class LayerBuffer { + final RenderLayer layer; + ByteBuffer buffer; + final MeshBuffer mesh = new MeshBuffer(); + int vertexCount; + boolean uploaded; + long lastUsedMs; + + LayerBuffer(RenderLayer layer) { + this.layer = layer; + this.buffer = BufferUtils.createByteBuffer(Math.max(layer.getExpectedBufferSize(), 4096)); + } + + void ensureCapacity(int bytes) { + buffer = MeshBuffer.ensureCapacity(buffer, bytes, true); + } + + void uploadForDraw() { + if (uploaded) return; + uploaded = true; + final ByteBuffer view = buffer.duplicate(); + view.flip(); + mesh.upload(layer.getVertexFormat(), layer.getDrawMode(), view, vertexCount); + } + + void setupDraw() { + mesh.bind(); + } + + void draw(int firstVertex, int count) { + mesh.draw(firstVertex, count); + } + + void finishDraw() { + mesh.unbind(); + } + + void reset() { + buffer.clear(); + vertexCount = 0; + uploaded = false; + } + } + + private final Map layerBuffers = new Object2ObjectOpenHashMap<>(); + private final List bufferList = new ArrayList<>(); + private final List segments = new ArrayList<>(); + private LayerBuffer current; + private RenderLayer currentType; + private int currentBlockEntityId; + private int currentEntityColor; + private int segmentStartVertex; + private long allocatedBytes; + + public void begin(RenderLayer type, int blockEntityId) { + final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); + if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) { + return; + } + endSegment(); + LayerBuffer buffer = layerBuffers.get(type); + if (buffer == null) { + buffer = new LayerBuffer(type); + layerBuffers.put(type, buffer); + bufferList.add(buffer); + allocatedBytes += buffer.buffer.capacity(); + } + current = buffer; + currentType = type; + currentBlockEntityId = blockEntityId; + currentEntityColor = entityColor; + segmentStartVertex = current.vertexCount; + } + + public static int packEntityColor(Vector4fc c) { + return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f); + } + + public void addQuad(ModelQuadView quad) { + if (current == null) { + throw new IllegalStateException("addQuad() without begin()"); + } + final VertexFormat format = currentType.getVertexFormat(); + ensureCurrentCapacity(format.getVertexSize() * 4); + format.writeQuad(quad, current.buffer); + current.vertexCount += 4; + } + + public void addTemplateInstance(TemplateBuffer template, Matrix4fc mv, Vector3f scratch, int colorABGR, int packedLight, Matrix4fc texMatrix) { + if (current == null) { + throw new IllegalStateException("addTemplateInstance() without begin()"); + } + final VertexFormat format = currentType.getVertexFormat(); + ensureCurrentCapacity(format.getVertexSize() * template.vertexCount); + final ByteBuffer buffer = current.buffer; + final long ptr = memAddress0(buffer) + buffer.position(); + final long end = VertexTransform.writeInstance(ptr, format, template, mv, scratch, colorABGR, packedLight, texMatrix); + buffer.position(buffer.position() + (int) (end - ptr)); + current.vertexCount += template.vertexCount; + } + + private void ensureCurrentCapacity(int bytes) { + final int before = current.buffer.capacity(); + current.ensureCapacity(bytes); + allocatedBytes += current.buffer.capacity() - before; + } + + private void endSegment() { + if (current != null && current.vertexCount > segmentStartVertex) { + segments.add(new BufferSegment(currentType, currentBlockEntityId, currentEntityColor, segmentStartVertex, + current.vertexCount - segmentStartVertex, current)); + } + segmentStartVertex = current == null ? 0 : current.vertexCount; + } + + public List getSegments() { + endSegment(); + currentType = null; + current = null; + return segments; + } + + public boolean isEmpty() { + for (int i = 0, n = bufferList.size(); i < n; i++) { + if (bufferList.get(i).vertexCount != 0) return false; + } + return true; + } + + public int getVertexCount() { + int total = 0; + for (int i = 0, n = bufferList.size(); i < n; i++) { + total += bufferList.get(i).vertexCount; + } + return total; + } + + public void reset() { + for (int i = 0, n = bufferList.size(); i < n; i++) { + bufferList.get(i).reset(); + } + segments.clear(); + currentType = null; + current = null; + currentBlockEntityId = 0; + segmentStartVertex = 0; + } + + public void resetAndReclaim(long nowMs, long maxIdleMs) { + for (int i = bufferList.size() - 1; i >= 0; i--) { + final LayerBuffer lb = bufferList.get(i); + if (lb.vertexCount > 0) { + lb.lastUsedMs = nowMs; + } + lb.reset(); + if (nowMs - lb.lastUsedMs > maxIdleMs) { + allocatedBytes -= lb.buffer.capacity(); + lb.mesh.delete(); + layerBuffers.remove(lb.layer); + bufferList.remove(i); + } + } + segments.clear(); + currentType = null; + current = null; + currentBlockEntityId = 0; + segmentStartVertex = 0; + } + + public void freeAll() { + for (int i = 0, n = bufferList.size(); i < n; i++) { + bufferList.get(i).mesh.delete(); + } + layerBuffers.clear(); + bufferList.clear(); + segments.clear(); + currentType = null; + current = null; + currentBlockEntityId = 0; + segmentStartVertex = 0; + allocatedBytes = 0; + } + + public long allocatedBytes() { + return allocatedBytes; + } + + public int bufferCount() { + return layerBuffers.size(); + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java b/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java index 999986295..026ea5ad8 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java @@ -1,6 +1,6 @@ package net.coderbot.batchedentityrendering.impl; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; public interface WrappableRenderType { /** diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java index 9d6d18db3..fbdda0129 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java @@ -10,7 +10,7 @@ import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider; import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import java.util.ArrayList; import java.util.EnumMap; diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java index d04a89bd0..b3067c008 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java @@ -1,6 +1,6 @@ package net.coderbot.batchedentityrendering.impl.ordering; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; public interface RenderOrderManager { void begin(RenderLayer type); diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java index ff31730a1..f397c9bcc 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java @@ -1,18 +1,19 @@ package net.coderbot.batchedentityrendering.impl.ordering; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import java.util.LinkedHashSet; +import java.util.ArrayList; +import java.util.List; public class SimpleRenderOrderManager implements RenderOrderManager { - private final LinkedHashSet renderTypes; - - public SimpleRenderOrderManager() { - renderTypes = new LinkedHashSet<>(); - } + private final ObjectOpenHashSet seen = new ObjectOpenHashSet<>(); + private final ArrayList ordered = new ArrayList<>(); public void begin(RenderLayer type) { - renderTypes.add(type); + if (seen.add(type)) { + ordered.add(type); + } } public void startGroup() { @@ -30,10 +31,11 @@ public class SimpleRenderOrderManager implements RenderOrderManager { @Override public void reset() { - renderTypes.clear(); + seen.clear(); + ordered.clear(); } - public Iterable getRenderOrder() { - return renderTypes; + public List getRenderOrder() { + return ordered; } } diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java index d0ff81d81..6a210b775 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java @@ -3,7 +3,7 @@ package net.coderbot.batchedentityrendering.impl.ordering; import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import java.util.ArrayList; import java.util.EnumMap; diff --git a/src/main/java/net/coderbot/iris/Iris.java b/src/main/java/net/coderbot/iris/Iris.java index f3561779f..4ea6fb0ea 100644 --- a/src/main/java/net/coderbot/iris/Iris.java +++ b/src/main/java/net/coderbot/iris/Iris.java @@ -4,9 +4,12 @@ import com.google.common.base.Throwables; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizons.angelica.Tags; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.StateAwareTessellator; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; +import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; @@ -37,6 +40,7 @@ import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; import net.coderbot.iris.shaderpack.option.values.OptionValues; import net.coderbot.iris.texture.pbr.PBRTextureManager; import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.coderbot.iris.uniforms.PerFrameUniformBlockHarvester; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; @@ -67,9 +71,10 @@ import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinWorkerThread; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -89,6 +94,7 @@ public class Iris { // Cached at class load - config must be loaded before Iris. Do not change at runtime. public static final boolean enabled = AngelicaConfig.enableIris; + public static final boolean hardcodedCustomUniforms = AngelicaConfig.enableHardcodedCustomUniforms; private static Path shaderpacksDirectory; private static ShaderpackDirectoryManager shaderpacksDirectoryManager; @@ -151,9 +157,14 @@ public class Iris { private static volatile long lastActivityTime; private static final AtomicInteger inFlight = new AtomicInteger(0); private static boolean idleCheckScheduled; + private static final ThreadLocal ON_WORKER = ThreadLocal.withInitial(() -> Boolean.FALSE); private ShaderTransformExecutor() {} + public static boolean isOnWorker() { + return ON_WORKER.get(); + } + private static void noteActivity() { lastActivityTime = System.nanoTime(); } @@ -166,18 +177,21 @@ public class Iris { return executor; } - executor = new ForkJoinPool( + final AtomicInteger threadCounter = new AtomicInteger(); + final ThreadFactory factory = r -> { + final Thread t = new Thread(r, "Shader-Transform-" + threadCounter.getAndIncrement()); + t.setDaemon(true); + return t; + }; + final ThreadPoolExecutor tpe = new ThreadPoolExecutor( THREAD_COUNT, - pool -> { - ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - t.setName("Shader-Transform-" + t.getPoolIndex()); - t.setDaemon(true); - return t; - }, - null, // UncaughtExceptionHandler - true // asyncMode - FIFO, better for independent tasks - ); - logger.debug("Created shader transform executor with " + THREAD_COUNT + " threads"); + THREAD_COUNT, + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), + factory); + tpe.prestartAllCoreThreads(); + executor = tpe; + logger.debug("Created shader transform executor with " + THREAD_COUNT + " prestarted threads"); if (scheduler == null || scheduler.isShutdown()) { scheduler = Executors.newSingleThreadScheduledExecutor(r -> { @@ -205,15 +219,9 @@ public class Iris { } } - /** - * Ensures the executor exists and begins spinning up worker threads. - * Intended for UI entrypoints (eg. shader settings screen open). - */ + /** Idempotent: ensures the pool is created. {@link #get()} prestarts all workers. */ public static void prepare() { - // Submit empty tasks to warm up all worker threads without blocking the UI thread. - for (int i = 0; i < THREAD_COUNT; i++) { - submitTracked(() -> { }); - } + get(); } /** @@ -238,9 +246,11 @@ public class Iris { inFlight.incrementAndGet(); try { return CompletableFuture.supplyAsync(() -> { + ON_WORKER.set(Boolean.TRUE); try { return supplier.get(); } finally { + ON_WORKER.set(Boolean.FALSE); noteActivity(); inFlight.decrementAndGet(); } @@ -257,9 +267,11 @@ public class Iris { inFlight.incrementAndGet(); try { return CompletableFuture.runAsync(() -> { + ON_WORKER.set(Boolean.TRUE); try { runnable.run(); } finally { + ON_WORKER.set(Boolean.FALSE); noteActivity(); inFlight.decrementAndGet(); } @@ -297,6 +309,9 @@ public class Iris { // Clear transformation caches - no longer needed after loading TransformPatcher.clearCache(); ShaderTransformer.clearCache(); + SpirvCompiler.clearCache(); + GlslVulkanPreprocess.clearCache(); + ShaderManager.clearPrewarmCache(); } else { // Still active (or in-flight), schedule another check. final long remainingSeconds = Math.max(1, IDLE_TIMEOUT_SECONDS - idleSeconds + 1); @@ -402,10 +417,7 @@ public class Iris { return; } - // Register the Celeritas shader provider for Iris integration (only when Celeritas is enabled) - if (AngelicaConfig.enableCeleritas) { - IrisShaderProviderHolder.setProvider(new IrisCeleritasShaderProvider()); - } + IrisShaderProviderHolder.setProvider(new IrisCeleritasShaderProvider()); // Warm up the threadpool so shader transformations are faster when we need them ShaderTransformExecutor.warmup(); @@ -856,6 +868,7 @@ public class Iris { private static WorldRenderingPipeline createPipeline(String dimensionName) { if (currentPack == null) { // Completely disables shader-based rendering + PerFrameUniformBlockHarvester.clear(); return new FixedFunctionWorldRenderingPipeline(); } @@ -863,6 +876,8 @@ public class Iris { try { shaderPackLoadId++; + ShaderTransformExecutor.prepare(); + PerFrameUniformBlockHarvester.harvest(programs); long startTime = System.nanoTime(); WorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs); long endTime = System.nanoTime(); @@ -872,6 +887,7 @@ public class Iris { logger.error("Failed to create shader rendering pipeline, disabling shaders!", e); // TODO: This should be reverted if a dimension change causes shaders to compile again fallback = true; + PerFrameUniformBlockHarvester.clear(); return new FixedFunctionWorldRenderingPipeline(); } diff --git a/src/main/java/net/coderbot/iris/celeritas/CeleritasTerrainPipeline.java b/src/main/java/net/coderbot/iris/celeritas/CeleritasTerrainPipeline.java index f6fc428b3..763ee6b04 100644 --- a/src/main/java/net/coderbot/iris/celeritas/CeleritasTerrainPipeline.java +++ b/src/main/java/net/coderbot/iris/celeritas/CeleritasTerrainPipeline.java @@ -163,6 +163,7 @@ public class CeleritasTerrainPipeline { target.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX)); target.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY)); target.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT)); + target.setSource(PatchShaderType.COMPUTE, result.get(PatchShaderType.COMPUTE)); } PatchedShaderPrinter.debugPatchedShaders(sourceName + "_celeritas", result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT)); @@ -205,4 +206,10 @@ public class CeleritasTerrainPipeline { public ProgramImages initShadowImages(int programId) { return createShadowImages.apply(programId); } + + public Optional getShadowVoxelizationComputeSource() { + final PassInfo shadow = passInfoMap.get(IrisTerrainPass.SHADOW); + if (shadow == null) return Optional.empty(); + return shadow.sources.get(PatchShaderType.COMPUTE); + } } diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java index 756fed49f..c38c1fc91 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java @@ -1,6 +1,7 @@ package net.coderbot.iris.celeritas; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.blending.BlendModeOverride; @@ -34,6 +35,12 @@ import java.util.List; public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { @Nullable + private static final Tracy.ZoneId Z_IRIS_SETUP_FBO = Tracy.zoneId("iris_setup_fbo", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_IRIS_SETUP_UNIFORMS = Tracy.zoneId("iris_setup_uniforms", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_IRIS_SETUP_SAMPLERS = Tracy.zoneId("iris_setup_samplers", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_IRIS_SETUP_IMAGES = Tracy.zoneId("iris_setup_images", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_IRIS_SETUP_CUSTOM = Tracy.zoneId("iris_setup_custom", Tracy.COLOR_IRIS); + private final GlUniformMatrix4f uniformModelViewMatrix; @Nullable private final GlUniformMatrix4f uniformModelViewMatrixInverse; @@ -45,6 +52,8 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { private final GlUniformMatrix3f uniformNormalMatrix; @Nullable private final GlUniformFloat3v uniformRegionOffset; + @Nullable + private final GlUniformMatrix4f uniformLightmapTextureMatrix; // Iris program state private final ProgramUniforms irisProgramUniforms; @@ -57,10 +66,18 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { private final List bufferBlendOverrides; private final boolean hasOverrides; - // Stored matrices for inverse and normal matrix computation - private final Matrix4f projectionMatrixInverse = new Matrix4f(); - private final Matrix4f modelViewMatrixInverse = new Matrix4f(); - private final Matrix3f normalMatrix = new Matrix3f(); + private final Matrix4f lastProjection = new Matrix4f(); + private final Matrix4f lastModelView = new Matrix4f(); + private boolean hasLastProjection; + private boolean hasLastModelView; + + private static final Matrix4f sharedProjKey = new Matrix4f(); + private static final Matrix4f sharedProjInverse = new Matrix4f(); + private static boolean sharedProjValid; + private static final Matrix4f sharedMvKey = new Matrix4f(); + private static final Matrix4f sharedMvInverse = new Matrix4f(); + private static final Matrix3f sharedNormal = new Matrix3f(); + private static boolean sharedMvValid; public IrisCeleritasChunkShaderInterface(int handle, ShaderBindingContext context, CeleritasTerrainPipeline pipeline, boolean isShadowPass, BlendModeOverride blendModeOverride, List bufferBlendOverrides, CustomUniforms customUniforms) { this.uniformModelViewMatrix = context.bindUniformIfPresent("iris_ModelViewMatrix", GlUniformMatrix4f::new); @@ -69,6 +86,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { this.uniformProjectionMatrixInverse = context.bindUniformIfPresent("iris_ProjectionMatrixInverse", GlUniformMatrix4f::new); this.uniformNormalMatrix = context.bindUniformIfPresent("iris_NormalMatrix", GlUniformMatrix3f::new); this.uniformRegionOffset = context.bindUniformIfPresent("u_RegionOffset", GlUniformFloat3v::new); + this.uniformLightmapTextureMatrix = context.bindUniformIfPresent("iris_LightmapTextureMatrix", GlUniformMatrix4f::new); this.blendModeOverride = blendModeOverride; this.bufferBlendOverrides = bufferBlendOverrides; @@ -84,12 +102,20 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { @Override public void setupState(TerrainRenderPass pass) { + if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_FBO); bindFramebuffer(pass); if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { GLStateManager.disableCull(); } + // Explicitly set iris_LightmapTextureMatrix rather than relying on CompatUniformManager. + // At high uniform locations in large UBOs, the compat manager's writes may not persist + // through the per-program dirtyUniforms swap in non-GL backends. + if (uniformLightmapTextureMatrix != null) { + uniformLightmapTextureMatrix.set(GLStateManager.getTextures().getTextureUnitMatrix(1)); + } + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + IrisSamplers.ALBEDO_TEXTURE_UNIT); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().getTextureMapBlocks().getGlTextureId()); @@ -104,18 +130,27 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { if (hasOverrides) { bufferBlendOverrides.forEach(BufferBlendOverride::apply); } + if (Tracy.ENABLED) Tracy.endZone(); if (irisProgramUniforms != null) { + if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_UNIFORMS); irisProgramUniforms.update(); + if (Tracy.ENABLED) Tracy.endZone(); } if (irisProgramSamplers != null) { + if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_SAMPLERS); irisProgramSamplers.update(); + if (Tracy.ENABLED) Tracy.endZone(); } if (irisProgramImages != null) { + if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_IMAGES); irisProgramImages.update(); + if (Tracy.ENABLED) Tracy.endZone(); } + if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_CUSTOM); customUniforms.push(this); + if (Tracy.ENABLED) Tracy.endZone(); } @Override @@ -135,34 +170,55 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { @Override public void setProjectionMatrix(Matrix4fc matrix) { + if (hasLastProjection && lastProjection.equals(matrix, 0.0f)) { + return; + } + hasLastProjection = true; + lastProjection.set(matrix); + if (uniformProjectionMatrix != null) { uniformProjectionMatrix.set(matrix); } if (uniformProjectionMatrixInverse != null) { - projectionMatrixInverse.set(matrix); - projectionMatrixInverse.invert(); - uniformProjectionMatrixInverse.set(projectionMatrixInverse); + if (!sharedProjValid || !sharedProjKey.equals(matrix, 0.0f)) { + sharedProjValid = true; + sharedProjKey.set(matrix); + sharedProjInverse.set(matrix); + sharedProjInverse.invert(); + } + uniformProjectionMatrixInverse.set(sharedProjInverse); } } @Override public void setModelViewMatrix(Matrix4fc modelView) { + if (hasLastModelView && lastModelView.equals(modelView, 0.0f)) { + return; + } + hasLastModelView = true; + lastModelView.set(modelView); + if (uniformModelViewMatrix != null) { uniformModelViewMatrix.set(modelView); } - if (uniformModelViewMatrixInverse != null) { - modelViewMatrixInverse.set(modelView); - modelViewMatrixInverse.invert(); - uniformModelViewMatrixInverse.set(modelViewMatrixInverse); - } - - if (uniformNormalMatrix != null) { - normalMatrix.set(modelView); - normalMatrix.invert(); - normalMatrix.transpose(); - uniformNormalMatrix.set(normalMatrix); + if (uniformModelViewMatrixInverse != null || uniformNormalMatrix != null) { + if (!sharedMvValid || !sharedMvKey.equals(modelView, 0.0f)) { + sharedMvValid = true; + sharedMvKey.set(modelView); + sharedMvInverse.set(modelView); + sharedMvInverse.invert(); + sharedNormal.set(modelView); + sharedNormal.invert(); + sharedNormal.transpose(); + } + if (uniformModelViewMatrixInverse != null) { + uniformModelViewMatrixInverse.set(sharedMvInverse); + } + if (uniformNormalMatrix != null) { + uniformNormalMatrix.set(sharedNormal); + } } } @@ -206,7 +262,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { } } - @org.jetbrains.annotations.Nullable + @Nullable private CeleritasTerrainPipeline getCeleritasTerrainPipeline() { final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); return pipeline != null ? pipeline.getCeleritasTerrainPipeline() : null; diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java index 2ce3e7e09..647326d97 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasShaderProvider.java @@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType; import net.coderbot.iris.Iris; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.shadows.ShadowRenderingState; import net.minecraft.block.Block; import org.embeddedt.embeddium.impl.gl.shader.GlProgram; @@ -65,6 +66,12 @@ public class IrisCeleritasShaderProvider implements IrisShaderProvider { return BlockRenderingSettings.INSTANCE.getBlockTypeIds(); } + @Override + public void preSubmitShadowGraph(int frame, boolean spectator) { + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (pipeline != null) pipeline.preSubmitShadowGraph(frame, spectator); + } + public void deleteShaders() { overrides.deleteShaders(); } diff --git a/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java b/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java index f215514e2..cda8314cb 100644 --- a/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java +++ b/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java @@ -73,6 +73,10 @@ public class DHCompat { return dhPresent && hasRenderingEnabled() && lastIncompatible; } + public static boolean isPresent() { + return dhPresent; + } + public static float getFarPlane() { if (!dhPresent) return 0.01f; return DHCompatInternal.getFarPlane(); diff --git a/src/main/java/net/coderbot/iris/compat/dh/DHCompatInternal.java b/src/main/java/net/coderbot/iris/compat/dh/DHCompatInternal.java index 4b14c70f3..ca97a8ded 100644 --- a/src/main/java/net/coderbot/iris/compat/dh/DHCompatInternal.java +++ b/src/main/java/net/coderbot/iris/compat/dh/DHCompatInternal.java @@ -8,7 +8,7 @@ import com.seibel.distanthorizons.api.objects.math.DhApiVec3f; import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; import net.coderbot.iris.gl.texture.DepthCopyStrategy; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.rendertarget.DepthTexture; diff --git a/src/main/java/net/coderbot/iris/compat/dh/IrisGenericRenderProgram.java b/src/main/java/net/coderbot/iris/compat/dh/IrisGenericRenderProgram.java index eadb43666..6f348969e 100644 --- a/src/main/java/net/coderbot/iris/compat/dh/IrisGenericRenderProgram.java +++ b/src/main/java/net/coderbot/iris/compat/dh/IrisGenericRenderProgram.java @@ -3,7 +3,7 @@ package net.coderbot.iris.compat.dh; import com.google.common.primitives.Ints; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; -import com.mitchej123.lwjgl.MemoryStack; +import org.lwjgl.BufferUtils; import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiGenericObjectShaderProgram; import com.seibel.distanthorizons.api.interfaces.render.IDhApiRenderableBoxGroup; import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiRenderParam; @@ -17,7 +17,7 @@ import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.gl.shader.GlShader; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.PatchedShaderPrinter; @@ -70,6 +70,11 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra id = GLStateManager.glCreateProgram(); GLStateManager.glBindAttribLocation(this.id, 0, "vPosition"); + GLStateManager.glBindAttribLocation(this.id, 1, "iris_color"); + GLStateManager.glBindAttribLocation(this.id, 2, "aScale"); + GLStateManager.glBindAttribLocation(this.id, 3, "aTranslateChunk"); + GLStateManager.glBindAttribLocation(this.id, 4, "aTranslateSubChunk"); + GLStateManager.glBindAttribLocation(this.id, 5, "aMaterial"); this.bufferBlendOverrides = bufferBlendOverrides; @@ -187,16 +192,12 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra return GLStateManager.glGetUniformLocation(this.id, name); } + private final FloatBuffer matrixScratch = BufferUtils.createFloatBuffer(16); + public void setUniform(int index, Matrix4f matrix) { if (index == -1 || matrix == null) return; - - try (MemoryStack stack = MemoryStack.stackPush()) { - FloatBuffer buffer = stack.callocFloat(16); - matrix.get(buffer); - buffer.rewind(); - - GLStateManager.glUniformMatrix4(index, false, buffer); - } + matrix.get(matrixScratch); + GLStateManager.glUniformMatrix4(index, false, matrixScratch); } // Override ShaderProgram.bind() diff --git a/src/main/java/net/coderbot/iris/compat/dh/IrisLodRenderProgram.java b/src/main/java/net/coderbot/iris/compat/dh/IrisLodRenderProgram.java index 07fc2bdad..7fba9f17f 100644 --- a/src/main/java/net/coderbot/iris/compat/dh/IrisLodRenderProgram.java +++ b/src/main/java/net/coderbot/iris/compat/dh/IrisLodRenderProgram.java @@ -11,9 +11,9 @@ import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.gl.shader.GlShader; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.gl.state.FogMode; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.transform.PatchShaderType; diff --git a/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java b/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java index 076d3a0b9..b5d9c3de3 100644 --- a/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java +++ b/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java @@ -1,6 +1,6 @@ package net.coderbot.iris.fantastic; -import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import java.util.function.Function; public interface WrappingMultiBufferSource { diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java b/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java index 535047942..61aa6407f 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java +++ b/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.blending; +import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction; + public class AlphaTest { public static final AlphaTest ALWAYS = new AlphaTest(AlphaTestFunction.ALWAYS, 0.0f); diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java b/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java index b6ed6bdd9..cac45750d 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java +++ b/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.blending; +import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction; + import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.AlphaState; import lombok.Getter; diff --git a/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java b/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java index d2ff7fcf6..02ada8c3e 100644 --- a/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java +++ b/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java @@ -10,7 +10,7 @@ import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; import it.unimi.dsi.fastutil.ints.Int2IntMap; import java.nio.IntBuffer; import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; diff --git a/src/main/java/net/coderbot/iris/gl/framebuffer/ParityFramebuffer.java b/src/main/java/net/coderbot/iris/gl/framebuffer/ParityFramebuffer.java new file mode 100644 index 000000000..972e48a0c --- /dev/null +++ b/src/main/java/net/coderbot/iris/gl/framebuffer/ParityFramebuffer.java @@ -0,0 +1,90 @@ +package net.coderbot.iris.gl.framebuffer; + +import net.coderbot.iris.rendertarget.ParityFlipState; +import org.jetbrains.annotations.Nullable; + +public class ParityFramebuffer extends GlFramebuffer { + + private final ParityFlipState parity; + @Nullable + private GlFramebuffer odd; + + public ParityFramebuffer(ParityFlipState parity) { + this.parity = parity; + } + + public void setOdd(GlFramebuffer odd) { + this.odd = odd; + } + + @Nullable + public GlFramebuffer getOdd() { + return odd; + } + + private boolean useOdd() { + return odd != null && parity.isOdd(); + } + + @Override + public void bind() { + if (useOdd()) { + odd.bind(); + } else { + super.bind(); + } + } + + @Override + public void bindAsReadBuffer() { + if (useOdd()) { + odd.bindAsReadBuffer(); + } else { + super.bindAsReadBuffer(); + } + } + + @Override + public void bindAsDrawBuffer() { + if (useOdd()) { + odd.bindAsDrawBuffer(); + } else { + super.bindAsDrawBuffer(); + } + } + + @Override + public int getId() { + return useOdd() ? odd.getId() : super.getId(); + } + + @Override + public int getColorAttachment(int index) { + return useOdd() ? odd.getColorAttachment(index) : super.getColorAttachment(index); + } + + @Override + public void addDepthAttachment(int texture) { + super.addDepthAttachment(texture); + if (odd != null) { + odd.addDepthAttachment(texture); + } + } + + @Override + public void addDepthAttachmentBypass(int texture) { + super.addDepthAttachmentBypass(texture); + if (odd != null) { + odd.addDepthAttachmentBypass(texture); + } + } + + @Override + protected void destroyInternal() { + super.destroyInternal(); + if (odd != null) { + odd.destroy(); + odd = null; + } + } +} diff --git a/src/main/java/net/coderbot/iris/gl/image/GlImage.java b/src/main/java/net/coderbot/iris/gl/image/GlImage.java index b82dd663a..145a970a3 100644 --- a/src/main/java/net/coderbot/iris/gl/image/GlImage.java +++ b/src/main/java/net/coderbot/iris/gl/image/GlImage.java @@ -2,10 +2,10 @@ package net.coderbot.iris.gl.image; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import org.embeddedt.embeddium.impl.gl.GlObject; import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.lwjgl.opengl.GL11; diff --git a/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java b/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java index 9b9f66d8a..40309cbc5 100644 --- a/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java +++ b/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java @@ -1,6 +1,6 @@ package net.coderbot.iris.gl.image; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/image/ImageInformation.java b/src/main/java/net/coderbot/iris/gl/image/ImageInformation.java index 4640261f6..5591a81cc 100644 --- a/src/main/java/net/coderbot/iris/gl/image/ImageInformation.java +++ b/src/main/java/net/coderbot/iris/gl/image/ImageInformation.java @@ -1,9 +1,9 @@ package net.coderbot.iris.gl.image; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; public record ImageInformation(String name, String samplerName, TextureType target, PixelFormat format, InternalTextureFormat internalTextureFormat, diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java b/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java index 31c15e456..9f061706c 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java @@ -7,10 +7,10 @@ import net.coderbot.iris.gl.sampler.GlSampler; import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.shader.GlShader; import net.coderbot.iris.gl.shader.ProgramCreator; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import org.jetbrains.annotations.Nullable; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java b/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java index 64433c9a0..60a7e4c76 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java @@ -5,7 +5,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.image.ImageBinding; import net.coderbot.iris.gl.image.ImageHolder; import net.coderbot.iris.gl.image.ImageLimits; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; import com.gtnewhorizons.angelica.glsm.GLStateManager; import java.util.ArrayList; diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java b/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java index d8daacfb8..4f19b9281 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java @@ -11,7 +11,7 @@ import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.sampler.SamplerLimits; import net.coderbot.iris.gl.state.ValueUpdateNotifier; import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; import org.lwjgl.opengl.GL13; @@ -51,8 +51,8 @@ public class ProgramSamplers { // in the middle of RenderType setup, bad things will happen. int activeTexture = GLStateManager.getActiveTextureUnit(); - for (SamplerBinding samplerBinding : samplerBindings) { - samplerBinding.update(); + for (int i = 0, n = samplerBindings.size(); i < n; i++) { + samplerBindings.get(i).update(); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture); @@ -61,8 +61,8 @@ public class ProgramSamplers { public void removeListeners() { active = null; - for (ValueUpdateNotifier notifier : notifiersToReset) { - notifier.setListener(null); + for (int i = 0, n = notifiersToReset.size(); i < n; i++) { + notifiersToReset.get(i).setListener(null); } } diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java b/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java index 6fe02f185..23c9dc724 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java +++ b/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java @@ -18,7 +18,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier; import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder; import net.coderbot.iris.gl.uniform.Uniform; import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.coderbot.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; @@ -51,8 +51,8 @@ public class ProgramUniforms { } private void updateStage(ImmutableList uniforms) { - for (Uniform uniform : uniforms) { - uniform.update(); + for (int i = 0, n = uniforms.size(); i < n; i++) { + uniforms.get(i).update(); } } @@ -107,8 +107,8 @@ public class ProgramUniforms { public void removeListeners() { active = null; - for (ValueUpdateNotifier notifier : notifiersToReset) { - notifier.setListener(null); + for (int i = 0, n = notifiersToReset.size(); i < n; i++) { + notifiersToReset.get(i).setListener(null); } } @@ -207,7 +207,7 @@ public class ProgramUniforms { final UniformType provided = uniformNames.get(name); final UniformType expected = getExpectedType(type); - if(AngelicaConfig.enableHardcodedCustomUniforms) { + if(Iris.hardcodedCustomUniforms) { // Legacy Checks from hardcoded custom uniforms if (provided == null && !name.startsWith("gl_")) { final String typeName = getTypeName(type); diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java b/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java index 65772bf3a..e213da29c 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java +++ b/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java @@ -2,11 +2,12 @@ package net.coderbot.iris.gl.sampler; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import java.util.function.IntSupplier; public class SamplerBinding { + private final Runnable updateListener = this::updateSampler; private final TextureType textureType; private final int textureUnit; private final IntSupplier texture; @@ -25,7 +26,7 @@ public class SamplerBinding { updateSampler(); if (notifier != null) { - notifier.setListener(this::updateSampler); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java b/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java index 5f404dadd..696f5ccda 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java +++ b/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java @@ -1,7 +1,7 @@ package net.coderbot.iris.gl.sampler; import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/shader/GlShader.java b/src/main/java/net/coderbot/iris/gl/shader/GlShader.java index f32491891..68b4fa6f4 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/GlShader.java +++ b/src/main/java/net/coderbot/iris/gl/shader/GlShader.java @@ -5,6 +5,7 @@ package net.coderbot.iris.gl.shader; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.gl.GlResource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java b/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java index 90246902d..25f6a26ee 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java +++ b/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java @@ -16,6 +16,8 @@ import net.coderbot.iris.texture.format.TextureFormatLoader; import net.coderbot.iris.uniforms.VanillaBiomeList; import net.minecraft.world.biome.BiomeGenBase; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; import org.lwjgl.LWJGLUtil; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; @@ -29,13 +31,9 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; public class StandardMacros { - private static final Pattern SEMVER_PATTERN = Pattern.compile("(?\\d+)\\.(?\\d+)\\.*(?\\d*)(.*)"); - private static void define(List defines, String key) { defines.add(new StringPair(key, "")); } @@ -87,8 +85,11 @@ public class StandardMacros { define(standardDefines, "IRIS_HAS_TRANSLUCENCY_SORTING"); define(standardDefines, "MAX_COLOR_BUFFERS", String.valueOf(IrisLimits.MAX_COLOR_BUFFERS)); } + if (BackendManager.RENDER_BACKEND.isSDLGPU()) { + define(standardDefines, "IS_ANGELICA_SDLGPU"); + } - if (DHCompat.hasRenderingEnabled()) { + if (DHCompat.isPresent()) { define(standardDefines, "DISTANT_HORIZONS"); } @@ -184,44 +185,7 @@ public class StandardMacros { * @see Optifine Doc for GLSL Version */ public static String getGlVersion(int name) { - final String info = GLStateManager.glGetString(name); - - Matcher matcher = SEMVER_PATTERN.matcher(Objects.requireNonNull(info)); - - if (!matcher.matches()) { - throw new IllegalStateException("Could not parse GL version from \"" + info + "\""); - } - - String major = group(matcher, "major"); - String minor = group(matcher, "minor"); - String bugfix = group(matcher, "bugfix"); - - if (bugfix == null) { - // if bugfix is not there, it is 0 - bugfix = "0"; - } - - if (major == null || minor == null) { - throw new IllegalStateException("Could not parse GL version from \"" + info + "\""); - } - - return major + minor + bugfix; - } - - /** - * Expanded version of {@link Matcher#group(String)} that does not throw an exception. - * If the argument is incorrect (normally resulting in an exception), it returns null - * - * @param matcher matcher to check the group by - * @param name name of the group - * @return the section of the matcher that is a group, or null, if that matcher does not contain said group - */ - public static String group(Matcher matcher, String name) { - try { - return matcher.group(name); - } catch (IllegalArgumentException | IllegalStateException exception) { - return null; - } + return RenderSystem.parseGlVersionString(GLStateManager.glGetString(name)); } /** @@ -231,6 +195,10 @@ public class StandardMacros { * @see Optifine Doc */ public static String getOsString() { + // Force MC_OS_LINUX under SDL_GPU on Mac to avoid shaderpack gates! + if (BackendManager.RENDER_BACKEND.isSDLGPU() && LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX) { + return "MC_OS_LINUX"; + } return switch (LWJGLUtil.getPlatform()) { case LWJGLUtil.PLATFORM_MACOSX -> "MC_OS_MAC"; case LWJGLUtil.PLATFORM_LINUX -> "MC_OS_LINUX"; @@ -330,11 +298,10 @@ public class StandardMacros { * @return List of definitions corresponding to the uniform names prefixed with "MC_" */ public static List getIrisDefines() { - List defines = new ArrayList<>(); - // All Iris-exclusive uniforms should have a corresponding definition here. Example: + // All Iris-exclusive uniforms should have a corresponding definition here. Example: // defines.add("MC_UNIFORM_DRAGON_DEATH_PROGRESS"); - return defines; + return new ArrayList<>(); } /** diff --git a/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java b/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java index 2aa3137b7..44d384d50 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java +++ b/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java @@ -2,12 +2,16 @@ package net.coderbot.iris.gl.texture; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; import org.lwjgl.opengl.GL11; public interface DepthCopyStrategy { // FB -> T class Gl20CopyTexture implements DepthCopyStrategy { + private static final Tracy.ZoneId Z_DEPTH_COPY_BIND = Tracy.zoneId("depthCopyBind", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_DEPTH_COPY_TEX_SUB = Tracy.zoneId("depthCopyTexSub", Tracy.COLOR_IRIS); + private Gl20CopyTexture() { // private } @@ -19,27 +23,39 @@ public interface DepthCopyStrategy { @Override public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) { - sourceFb.bindAsReadBuffer(); + if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_BIND); + try { + sourceFb.bindAsReadBuffer(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } - RenderSystem.copyTexSubImage2D( - destTexture, - // target - GL11.GL_TEXTURE_2D, - // level - 0, - // xoffset, yoffset - 0, 0, - // x, y - 0, 0, - // width - width, - // height - height); + if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_TEX_SUB); + try { + RenderSystem.copyTexSubImage2D( + destTexture, + // target + GL11.GL_TEXTURE_2D, + // level + 0, + // xoffset, yoffset + 0, 0, + // x, y + 0, 0, + // width + width, + // height + height); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } } // FB -> FB class Gl30BlitFbCombinedDepthStencil implements DepthCopyStrategy { + private static final Tracy.ZoneId Z_DEPTH_COPY_BLIT = Tracy.zoneId("depthCopyBlit", Tracy.COLOR_IRIS); + private Gl30BlitFbCombinedDepthStencil() { // private } @@ -51,16 +67,23 @@ public interface DepthCopyStrategy { @Override public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) { - RenderSystem.blitFramebuffer(sourceFb.getId(), destFb.getId(), 0, 0, width, height, - 0, 0, width, height, - GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT, - GL11.GL_NEAREST); + if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_BLIT); + try { + RenderSystem.blitFramebuffer(sourceFb.getId(), destFb.getId(), 0, 0, width, height, + 0, 0, width, height, + GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT, + GL11.GL_NEAREST); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } } // T -> T // Fastest class Gl43CopyImage implements DepthCopyStrategy { + private static final Tracy.ZoneId Z_DEPTH_COPY_IMAGE = Tracy.zoneId("depthCopyImage", Tracy.COLOR_IRIS); + private Gl43CopyImage() { // private } @@ -72,7 +95,12 @@ public interface DepthCopyStrategy { @Override public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) { - GLStateManager.glCopyImageSubData(sourceTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, destTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1); + if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_IMAGE); + try { + GLStateManager.glCopyImageSubData(sourceTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, destTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } } diff --git a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java b/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java index df34f3e37..fcedfab4e 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java +++ b/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.texture; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; + import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.shaderpack.texture.TextureFilteringData; diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java b/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java index 62629355e..5eccfa426 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java +++ b/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.texture; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; + import java.util.function.IntSupplier; public interface TextureAccess { diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java b/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java index fffde1fc5..82868d665 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java +++ b/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java @@ -1,5 +1,10 @@ package net.coderbot.iris.gl.texture; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; + import lombok.Getter; @Getter diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java b/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java index 3621cf8dc..cb6701781 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java +++ b/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.texture; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; + import java.util.function.IntSupplier; public class TextureWrapper implements TextureAccess { diff --git a/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java b/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java index 663a3a48d..e4bb1ef77 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.uniform; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + import net.coderbot.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector2ic; import org.joml.Vector3ic; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java index 59ef27665..9783f6518 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java @@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.state.ValueUpdateNotifier; public class FloatUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private float cachedValue; private final FloatSupplier value; @@ -23,7 +24,7 @@ public class FloatUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java index 438581d89..1e46417ab 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java @@ -6,6 +6,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier; import java.util.function.IntSupplier; public class IntUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private int cachedValue; private final IntSupplier value; @@ -25,7 +26,7 @@ public class IntUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java b/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java index f1471641b..780b190ec 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.uniform; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + import net.minecraft.util.Vec3; import org.joml.Matrix4f; import org.joml.Matrix4fc; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolder.java b/src/main/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolder.java new file mode 100644 index 000000000..6e8163042 --- /dev/null +++ b/src/main/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolder.java @@ -0,0 +1,77 @@ +package net.coderbot.iris.gl.uniform; + +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + +import net.coderbot.iris.gl.state.ValueUpdateNotifier; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.OptionalInt; +import java.util.Set; + +public final class ManifestCollectingHolder implements DynamicLocationalUniformHolder { + + private final List namesById = new ObjectArrayList<>(); + private final Map typesByName = new Object2ObjectOpenHashMap<>(); + private final List entries = new ArrayList<>(); + private final Set dynamicNames = new LinkedHashSet<>(); + private final Set externallyManagedNames = new LinkedHashSet<>(); + + @Override + public OptionalInt location(String name, UniformType type) { + if (typesByName.putIfAbsent(name, type) != null) return OptionalInt.empty(); + final int id = namesById.size(); + namesById.add(name); + return OptionalInt.of(id); + } + + private String nameFor(int location) { + return location >= 0 && location < namesById.size() ? namesById.get(location) : null; + } + + @Override + public ManifestCollectingHolder addUniform(UniformUpdateFrequency updateFrequency, Uniform uniform) { + Objects.requireNonNull(uniform); + final String name = nameFor(uniform.getLocation()); + if (name == null) return this; + switch (updateFrequency) { + case ONCE, PER_TICK, PER_FRAME -> entries.add(new UniformManifest.Entry(name, typesByName.get(name), updateFrequency)); + case CUSTOM -> { } + } + return this; + } + + @Override + public ManifestCollectingHolder addDynamicUniform(Uniform uniform, ValueUpdateNotifier notifier) { + Objects.requireNonNull(uniform); + final String name = nameFor(uniform.getLocation()); + if (name != null) dynamicNames.add(name); + return this; + } + + @Override + public ManifestCollectingHolder externallyManagedUniform(String name, UniformType type) { + externallyManagedNames.add(name); + return this; + } + + public UniformManifest build() { + final List grouped = new ArrayList<>(entries.size()); + for (UniformUpdateFrequency freq : GROUP_ORDER) { + for (UniformManifest.Entry e : entries) { + if (e.frequency() == freq) grouped.add(e); + } + } + return new UniformManifest(grouped, dynamicNames, externallyManagedNames); + } + + private static final UniformUpdateFrequency[] GROUP_ORDER = { + UniformUpdateFrequency.ONCE, UniformUpdateFrequency.PER_TICK, UniformUpdateFrequency.PER_FRAME + }; +} diff --git a/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java index e6dd68a89..fdd629f54 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java @@ -9,13 +9,13 @@ import java.util.function.Supplier; public class MatrixFromFloatArrayUniform extends Uniform { private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); - private float[] cachedValue; + private final float[] cachedValue = new float[16]; + private boolean hasValue; private final Supplier value; MatrixFromFloatArrayUniform(int location, Supplier value) { super(location); - this.cachedValue = null; this.value = value; } @@ -23,8 +23,9 @@ public class MatrixFromFloatArrayUniform extends Uniform { public void update() { float[] newValue = value.get(); - if (!Arrays.equals(newValue, cachedValue)) { - cachedValue = Arrays.copyOf(newValue, 16); + if (!hasValue || !Arrays.equals(newValue, cachedValue)) { + hasValue = true; + System.arraycopy(newValue, 0, cachedValue, 0, 16); buffer.put(cachedValue); buffer.rewind(); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java index 541a5db5c..220da3767 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java @@ -10,13 +10,13 @@ import java.util.function.Supplier; public class MatrixUniform extends Uniform { private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); - private Matrix4f cachedValue; + private final Matrix4f cachedValue = new Matrix4f(); + private boolean hasValue; private final Supplier value; MatrixUniform(int location, Supplier value) { super(location); - this.cachedValue = null; this.value = value; } @@ -26,8 +26,9 @@ public class MatrixUniform extends Uniform { if( newValue == null ){ throw new RuntimeException("MatrixUniform value is null"); } - if (!newValue.equals(cachedValue)) { - cachedValue = new Matrix4f(newValue); + if (!hasValue || !newValue.equals(cachedValue)) { + hasValue = true; + cachedValue.set(newValue); cachedValue.get(buffer); buffer.rewind(); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java b/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java index a8b60cdd0..f0056094d 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java @@ -1,5 +1,7 @@ package net.coderbot.iris.gl.uniform; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + import net.minecraft.util.Vec3; import org.joml.Matrix4fc; import org.joml.Vector2f; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformManifest.java b/src/main/java/net/coderbot/iris/gl/uniform/UniformManifest.java new file mode 100644 index 000000000..0f8763e0d --- /dev/null +++ b/src/main/java/net/coderbot/iris/gl/uniform/UniformManifest.java @@ -0,0 +1,38 @@ +package net.coderbot.iris.gl.uniform; + +import com.gtnewhorizons.angelica.glsm.shader.UniformType; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +public final class UniformManifest { + + public record Entry(String name, UniformType type, UniformUpdateFrequency frequency) {} + + private final List entries; + private final Set dynamicNames; + private final Set externallyManagedNames; + + UniformManifest(List entries, Set dynamicNames, Set externallyManagedNames) { + this.entries = Collections.unmodifiableList(entries); + this.dynamicNames = Collections.unmodifiableSet(dynamicNames); + this.externallyManagedNames = Collections.unmodifiableSet(externallyManagedNames); + } + + public List entries() { + return entries; + } + + public Set dynamicNames() { + return dynamicNames; + } + + public Set externallyManagedNames() { + return externallyManagedNames; + } + + public boolean isEmpty() { + return entries.isEmpty(); + } +} diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java index fa684b418..f302e4c9f 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java @@ -8,6 +8,7 @@ import org.joml.Vector2ic; import java.util.function.Supplier; public class Vector2IntegerJomlUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private final Vector2i cachedValue; private final Supplier value; @@ -27,7 +28,7 @@ public class Vector2IntegerJomlUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerJomlUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerJomlUniform.java index 30437adfb..6d7e12e14 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerJomlUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerJomlUniform.java @@ -8,6 +8,7 @@ import org.joml.Vector3ic; import java.util.function.Supplier; public class Vector3IntegerJomlUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private final Vector3i cachedValue; private final Supplier value; @@ -27,7 +28,7 @@ public class Vector3IntegerJomlUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java index 63029b1d7..84daf0a4a 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.function.Supplier; public class Vector4ArrayUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private final Supplier value; private float[] cachedValue; @@ -26,7 +27,7 @@ public class Vector4ArrayUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java b/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java index 16150d3d3..0fcee96b2 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java @@ -8,6 +8,7 @@ import org.joml.Vector4ic; import java.util.function.Supplier; public class Vector4IntegerJomlUniform extends Uniform { + private final Runnable updateListener = this::updateValue; private final Vector4i cachedValue; private final Supplier value; @@ -27,7 +28,7 @@ public class Vector4IntegerJomlUniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java b/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java index 43fda86c7..af2bc22d2 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java +++ b/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java @@ -8,6 +8,7 @@ import org.joml.Vector4fc; import java.util.function.Supplier; public class Vector4Uniform extends Uniform { + private final Runnable updateListener = this::updateValue; private final Vector4f cachedValue; private final Supplier value; @@ -27,7 +28,7 @@ public class Vector4Uniform extends Uniform { updateValue(); if (notifier != null) { - notifier.setListener(this::updateValue); + notifier.setListener(updateListener); } } diff --git a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java b/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java index 0a29899ac..c323388c6 100644 --- a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java +++ b/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java @@ -12,6 +12,7 @@ public class GbufferPrograms { private static boolean entities; private static boolean blockEntities; private static boolean outline; + private static boolean entityLoop; private static Runnable phaseChangeListener; static { @@ -32,6 +33,29 @@ public class GbufferPrograms { entities = true; } + public static void beginEntityLoop() { + entityLoop = true; + setPhase(WorldRenderingPhase.ENTITIES); + setBlockEntityDefaults(); + } + + public static void endEntityLoop() { + entityLoop = false; + setPhase(WorldRenderingPhase.NONE); + } + + public static boolean isEntityLoopActive() { + return entityLoop; + } + + public static void onEntityRenderBoundary() { + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (pipeline != null) { + pipeline.onEntityRenderBoundary(); + } + } + public static void endEntities() { if (!entities) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call endEntities when entities = false"); diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java b/src/main/java/net/coderbot/iris/pipeline/ClearPass.java index 687e8462d..0d725032b 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java +++ b/src/main/java/net/coderbot/iris/pipeline/ClearPass.java @@ -3,6 +3,7 @@ package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; import net.minecraft.client.Minecraft; +import net.minecraft.profiler.Profiler; import org.joml.Vector4f; import org.lwjgl.opengl.GL11; @@ -10,13 +11,15 @@ import java.util.Objects; import java.util.function.IntSupplier; public class ClearPass { + private final String name; private final Vector4f color; private final IntSupplier viewportX; private final IntSupplier viewportY; private final GlFramebuffer framebuffer; private final int clearFlags; - public ClearPass(Vector4f color, IntSupplier viewportX, IntSupplier viewportY, GlFramebuffer framebuffer, int clearFlags) { + public ClearPass(String name, Vector4f color, IntSupplier viewportX, IntSupplier viewportY, GlFramebuffer framebuffer, int clearFlags) { + this.name = name; this.color = color; this.viewportX = viewportX; this.viewportY = viewportY; @@ -25,6 +28,8 @@ public class ClearPass { } public void execute(Vector4f defaultClearColor) { + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + profiler.startSection(name); GLStateManager.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt()); framebuffer.bind(); @@ -36,9 +41,7 @@ public class ClearPass { GLStateManager.glClearColor(color.x, color.y, color.z, color.w); GLStateManager.glClear(clearFlags); - if (Minecraft.isRunningOnMac) { - GLStateManager.glGetError(); - } + profiler.endSection(); } public GlFramebuffer getFramebuffer() { diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java b/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java index d2866bdff..e1acc1302 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java +++ b/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java @@ -69,9 +69,9 @@ public class ClearPassCreator { } // No need to clear the depth buffer, since we're using Minecraft's depth buffer. - clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, + clearPasses.add(new ClearPass(clearPassName("alt", clearBuffers), clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, renderTargets.createClearFramebuffer(true, clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); - clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, + clearPasses.add(new ClearPass(clearPassName("main", clearBuffers), clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, renderTargets.createClearFramebuffer(false, clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); } }); @@ -115,14 +115,22 @@ public class ClearPassCreator { } // No need to clear the depth buffer, since we're using Minecraft's depth buffer. - clearPasses.add(new ClearPass(clearColor, renderTargets::getResolution, renderTargets::getResolution, + clearPasses.add(new ClearPass(clearPassName("shadow_alt", clearBuffers), clearColor, renderTargets::getResolution, renderTargets::getResolution, renderTargets.createFramebufferWritingToAlt(clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); - clearPasses.add(new ClearPass(clearColor, renderTargets::getResolution, renderTargets::getResolution, + clearPasses.add(new ClearPass(clearPassName("shadow_main", clearBuffers), clearColor, renderTargets::getResolution, renderTargets::getResolution, renderTargets.createFramebufferWritingToMain(clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); } }); return ImmutableList.copyOf(clearPasses); } + + private static String clearPassName(String kind, int[] clearBuffers) { + final StringBuilder sb = new StringBuilder("iris_clear_").append(kind); + for (int buffer : clearBuffers) { + sb.append('_').append(buffer); + } + return sb.toString(); + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java b/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java index 42197a5dc..ac49eb9f7 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java +++ b/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java @@ -2,6 +2,8 @@ package net.coderbot.iris.pipeline; import org.joml.Vector4f; +import java.util.Objects; + public class ClearPassInformation { private final Vector4f color; private final int width; @@ -33,6 +35,11 @@ public class ClearPassInformation { ClearPassInformation information = (ClearPassInformation) obj; - return information.color.equals(this.color) && information.height == this.height && information.width == this.width; + return Objects.equals(information.color, this.color) && information.height == this.height && information.width == this.width; + } + + @Override + public int hashCode() { + return Objects.hash(color, width, height); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java b/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java index 0d285aa4c..85787381a 100644 --- a/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java +++ b/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java @@ -1,5 +1,6 @@ package net.coderbot.iris.pipeline; +import com.gtnewhorizons.angelica.compat.mojang.NativeImage; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; @@ -9,7 +10,7 @@ import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.texture.GlTexture; import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.gl.texture.TextureWrapper; import net.coderbot.iris.rendertarget.NativeImageBackedCustomTexture; import net.coderbot.iris.rendertarget.NativeImageBackedNoiseTexture; @@ -33,8 +34,11 @@ import org.lwjgl.opengl.GL11; import java.io.IOException; import java.util.ArrayList; import java.util.EnumMap; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; public class CustomTextureManager { @Getter private final EnumMap> customTextureIdMap = new EnumMap<>(TextureStage.class); @@ -48,10 +52,14 @@ public class CustomTextureManager { private final List ownedTextures = new ArrayList<>(); private final List ownedRawTextures = new ArrayList<>(); + private Map> pngDecodeFutures; + public CustomTextureManager(PackDirectives packDirectives, EnumMap> customTextureDataMap, Object2ObjectMap irisCustomTextureDataMap, Optional customNoiseTextureData) { + this.pngDecodeFutures = submitPngDecodes(customTextureDataMap, irisCustomTextureDataMap, customNoiseTextureData); + customTextureDataMap.forEach((textureStage, customTextureStageDataMap) -> { final Object2ObjectMap customTextureIds = new Object2ObjectOpenHashMap<>(); @@ -93,9 +101,37 @@ public class CustomTextureManager { }); } + private static Map> submitPngDecodes( + EnumMap> customTextureDataMap, + Object2ObjectMap irisCustomTextureDataMap, + Optional customNoiseTextureData) { + final Map> futures = new HashMap<>(); + customTextureDataMap.values().forEach(stage -> stage.values().forEach(td -> tryQueueDecode(td, futures))); + irisCustomTextureDataMap.values().forEach(td -> tryQueueDecode(td, futures)); + customNoiseTextureData.ifPresent(td -> tryQueueDecode(td, futures)); + return futures; + } + + private static void tryQueueDecode(CustomTextureData td, Map> futures) { + if (!(td instanceof CustomTextureData.PngData png)) return; + if (futures.containsKey(png)) return; + futures.put(png, Iris.ShaderTransformExecutor.submitTracked(() -> { + try { + return NativeImageBackedCustomTexture.decode(png.getContent()); + } catch (IOException e) { + return null; + } + })); + } + private TextureAccess createCustomTexture(CustomTextureData textureData) throws IOException { - if (textureData instanceof CustomTextureData.PngData) { - final AbstractTexture texture = new NativeImageBackedCustomTexture((CustomTextureData.PngData) textureData); + if (textureData instanceof CustomTextureData.PngData png) { + final CompletableFuture future = pngDecodeFutures != null ? pngDecodeFutures.get(png) : null; + final NativeImage decoded = future != null ? future.join() : NativeImageBackedCustomTexture.decode(png.getContent()); + if (decoded == null) { + throw new IOException("Failed to decode PNG (see prior log for cause)"); + } + final AbstractTexture texture = new NativeImageBackedCustomTexture(decoded, png.getFilteringData()); ownedTextures.add(texture); return new TextureWrapper(texture::getGlTextureId, TextureType.TEXTURE_2D); diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 61d264970..c9af7a702 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -4,6 +4,14 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Ints; import com.gtnewhorizons.angelica.compat.mojang.Camera; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLDebug; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; +import org.joml.Matrix3f; +import org.joml.Matrix4fc; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; @@ -38,8 +46,8 @@ import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.state.FogMode; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.pipeline.transform.GlintScrollInjector; @@ -52,6 +60,7 @@ import net.coderbot.iris.postprocess.FinalPassRenderer; import net.coderbot.iris.postprocess.FullScreenQuadRenderer; import net.coderbot.iris.postprocess.ProgramBuildContext; import net.coderbot.iris.rendertarget.IRenderTargetExt; +import net.coderbot.iris.rendertarget.ParityFlipState; import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture; import net.coderbot.iris.rendertarget.RenderTargets; import net.coderbot.iris.samplers.IrisImages; @@ -59,12 +68,14 @@ import net.coderbot.iris.samplers.IrisSamplers; import net.coderbot.iris.shaderpack.CloudSetting; import net.coderbot.iris.shaderpack.ComputeSource; import net.coderbot.iris.shaderpack.OptionalBoolean; +import net.coderbot.iris.shaderpack.ParticleRenderingSettings; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.shaderpack.PackShadowDirectives; import net.coderbot.iris.shaderpack.ProgramDirectives; import net.coderbot.iris.shaderpack.ProgramFallbackResolver; import net.coderbot.iris.shaderpack.ProgramSet; import net.coderbot.iris.shaderpack.ProgramSource; +import net.coderbot.iris.shaderpack.loading.ProgramGroup; import net.coderbot.iris.shaderpack.loading.ProgramId; import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.shadows.ShadowCompositeRenderer; @@ -83,6 +94,7 @@ import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.shader.Framebuffer; +import net.minecraft.profiler.Profiler; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import org.joml.Vector3d; @@ -92,9 +104,13 @@ import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; import org.lwjgl.opengl.GL43; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -120,6 +136,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private ShadowRenderTargets shadowRenderTargets; @Nullable private ComputeProgram[] shadowComputes; + @Nullable private ComputeProgram shadowVoxelizationCompute; private final Supplier shadowTargetsSupplier; private final ProgramTable table; @@ -163,6 +180,13 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final ShaderStorageBufferHolder ssboHolder; private final Map, Map> attributeTransforms; + private final Map, Map> instancedAttributeTransforms; + private boolean supportsTesrInstancing = true; + private final ParityFlipState parityState = new ParityFlipState(AngelicaConfig.shaderParityFlip); + private final Supplier> flippedGbuffers; + private final Supplier> flippedShadowGbuffers; + private final Supplier> flippedAfterPrepareResolved; + private final Supplier> flippedBeforeShadowResolved; private final HorizonRenderer horizonRenderer = new HorizonRenderer(); @@ -185,8 +209,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final OptionalInt forcedShadowRenderDistanceChunks; private final CloudSetting dhCloudSetting; private Pass current = null; + private RenderCondition currentCondition = null; private WorldRenderingPhase overridePhase = null; private WorldRenderingPhase phase = WorldRenderingPhase.NONE; + private WorldRenderingPhase pushedPhase = WorldRenderingPhase.NONE; + private boolean worldGroupActive = false; private boolean isBeforeTranslucent; private boolean isRenderingShadow = false; private InputAvailability inputs = new InputAvailability(false, false); @@ -199,9 +226,17 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final Set activeFeatures; private final ProgramFallbackResolver resolver; + private int packSamplerUsage; + private final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + + private static final Vector4f EMPTY_CLEAR_COLOR = new Vector4f(1.0F); + public DeferredWorldRenderingPipeline(ProgramSet programs) { Objects.requireNonNull(programs); + final long _t0 = System.nanoTime(); + long _tLast = _t0; + final Map>> prepareTransformFutures = submitCompositeTransforms(programs.getPrepare(), TextureStage.PREPARE, programs.getPackDirectives().getTextureMap()); final Map>> deferredTransformFutures = @@ -216,7 +251,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R .orElse(null); resolver = new ProgramFallbackResolver(programs); - final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver); + final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver, ProgramId.values(), false); + final Map, CompletableFuture>> instancedTransformFutures = submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true); final Optional terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic()); final Optional translucentSource = first(programs.getGbuffersWater(), terrainSource); @@ -229,6 +265,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R final CompletableFuture> celeritasShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform).orElse(null); final CompletableFuture> celeritasShadowTranslucentFuture = shadowTranslucentSource.map(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform).orElse(null); + final Int2ObjectArrayMap> setupComputeFutures = submitSetupComputeTransforms(programs.getSetup(), programs.getPackDirectives().getTextureMap()); + this.cloudSetting = programs.getPackDirectives().getCloudSetting(); this.shouldRenderUnderwaterOverlay = programs.getPackDirectives().underwaterOverlay(); this.shouldRenderVignette = programs.getPackDirectives().vignette(); @@ -242,7 +280,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R this.shouldWriteRainAndSnowToDepthBuffer = programs.getPackDirectives().rainDepth(); this.dhCloudSetting = programs.getPackDirectives().getDHCloudSetting(); this.shouldRenderParticlesBeforeDeferred = programs.getPackDirectives().getParticleRenderingSettings() - .map(s -> s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.BEFORE || s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.MIXED) + .map(s -> s == ParticleRenderingSettings.BEFORE || s == ParticleRenderingSettings.MIXED) .orElse(false); this.allowConcurrentCompute = programs.getPackDirectives().getConcurrentCompute(); this.shouldRenderPrepareBeforeShadow = programs.getPackDirectives().isPrepareBeforeShadow(); @@ -261,6 +299,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R this.renderTargets = new RenderTargets(main.framebufferWidth, main.framebufferHeight, depthTextureId, ((IRenderTargetExt)main).iris$getDepthBufferVersion(), depthBufferFormat, programs.getPackDirectives().getRenderTargetDirectives().getRenderTargetSettings(), programs.getPackDirectives()); + this.renderTargets.setParityState(parityState); this.sunPathRotation = programs.getPackDirectives().getSunPathRotation(); @@ -361,22 +400,50 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this); final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this); - this.setup = createSetupComputes(programs.getSetup()); + this.setup = createSetupComputes(programs.getSetup(), setupComputeFutures); + Iris.logger.info("[Load #{}] DWRP phase=pre-renderers elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); this.beginRenderer = new CompositeRenderer(programs.getBegin(), programs.getBeginCompute(), flipper, beginBuildContext, programs.getPackDirectives().getExplicitFlips("begin_pre"), null, "begin", TextureStage.BEGIN); + recordSamplerUsage(beginRenderer.getSamplerUsage()); + Iris.logger.info("[Load #{}] DWRP renderer=begin elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); this.flippedBeforeShadow = flipper.snapshot(); this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare", TextureStage.PREPARE); + recordSamplerUsage(prepareRenderer.getSamplerUsage()); + Iris.logger.info("[Load #{}] DWRP renderer=prepare elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); flippedAfterPrepare = flipper.snapshot(); this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred", TextureStage.DEFERRED); + recordSamplerUsage(deferredRenderer.getSamplerUsage()); + Iris.logger.info("[Load #{}] DWRP renderer=deferred elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); flippedAfterTranslucent = flipper.snapshot(); this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite", TextureStage.COMPOSITE_AND_FINAL); + recordSamplerUsage(compositeRenderer.getSamplerUsage()); + Iris.logger.info("[Load #{}] DWRP renderer=composite elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final"); + recordSamplerUsage(finalPassRenderer.getSamplerUsage()); + Iris.logger.info("[Load #{}] DWRP phase=final-renderer elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); + + parityState.finalizeParitySet(flipper.snapshot(), programs.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared()); + renderTargets.finalizeParity(); + if (parityState.isEnabled()) { + Iris.logger.info("Parity flip active for buffers {}", parityState.parityBuffers()); + } + + this.flippedGbuffers = () -> parityState.resolve(isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent); + this.flippedShadowGbuffers = () -> parityState.resolve(shouldRenderPrepareBeforeShadow ? flippedAfterPrepare : flippedBeforeShadow); + this.flippedAfterPrepareResolved = () -> parityState.resolve(flippedAfterPrepare); + this.flippedBeforeShadowResolved = () -> parityState.resolve(flippedBeforeShadow); // [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)] final ProgramId[] ids = new ProgramId[] { @@ -416,6 +483,20 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R throw new RuntimeException("Shader transformation failed for " + entry.getKey().getLeft(), e); } } + Iris.logger.info("[Load #{}] DWRP phase=attribute-join elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); + + this.instancedAttributeTransforms = new HashMap<>(); + for (Map.Entry, CompletableFuture>> entry : instancedTransformFutures.entrySet()) { + try { + this.instancedAttributeTransforms.put(entry.getKey(), entry.getValue().join()); + } catch (Exception e) { + Iris.logger.warn("Instanced transform failed for {}; disabling TESR instancing", entry.getKey().getLeft(), e); + supportsTesrInstancing = false; + instancedAttributeTransforms.clear(); + break; + } + } final Map, Pass> cachedPasses = new HashMap<>(); @@ -468,6 +549,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } }); }); + Iris.logger.info("[Load #{}] DWRP phase=gbuffer-table elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); if (shadowRenderTargets == null && shadowDirectives.isShadowEnabled() == OptionalBoolean.TRUE) { shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives); } @@ -483,14 +566,17 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R customTextureManager.getCustomTextureIdMap(TextureStage.SHADOWCOMP), customImages, programs.getPackDirectives().getExplicitFlips("shadowcomp_pre"), customTextureManager.getIrisCustomTextures(), customUniforms); + recordSamplerUsage(shadowCompositeRenderer.getSamplerUsage()); if (programs.getPackDirectives().getShadowDirectives().isShadowEnabled().orElse(true)) { this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null), - programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer); + programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer, + () -> usesSampler(IrisSamplers.USAGE_SHADOWTEX1)); Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram(); Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, new InputAvailability(true, true)).getProgram(); shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0) || (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0)); + shadowRenderer.setPlayerReflectionCaptureEnabled((shadowProgram != null && GLStateManager.glGetUniformLocation(shadowProgram.getProgramId(), "playerAtlas_img") != -1) || (shadowWaterProgram != null && GLStateManager.glGetUniformLocation(shadowWaterProgram.getProgramId(), "playerAtlas_img") != -1)); } else { shadowRenderer = null; } @@ -500,6 +586,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R this.shadowCompositeRenderer = null; this.shadowRenderer = null; } + Iris.logger.info("[Load #{}] DWRP phase=shadow elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); + _tLast = System.nanoTime(); this.customUniforms.optimise(); @@ -527,7 +615,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // Terrain pipeline sampler/image factory setup follows. - Supplier> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; + Supplier> flipped = flippedGbuffers; IntFunction createTerrainSamplers = (programId) -> { ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); @@ -535,7 +623,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); - IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); + recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); // Bind custom images as samplers (for texture() access to voxel_sampler, floodfill_sampler, etc.) @@ -544,7 +632,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures()); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, true)); } return builder.build(); @@ -568,7 +656,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW)); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flippedAfterPrepare, renderTargets, false, this); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flippedAfterPrepareResolved, renderTargets, false, this); IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); @@ -579,7 +667,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // Only initialize these samplers if the shadow map renderer exists. Otherwise, this program shouldn't be used at all? if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, true)); } return builder.build(); @@ -587,7 +675,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IntFunction createShadowTerrainImages = (programId) -> { ProgramImages.Builder builder = ProgramImages.builder(programId); - IrisImages.addRenderTargetImages(builder, () -> flippedAfterPrepare, renderTargets); + IrisImages.addRenderTargetImages(builder, flippedAfterPrepareResolved, renderTargets); // Bind custom images as image units (for imageLoad/imageStore - voxelization uses this in shadow pass) IrisImages.addCustomImages(builder, customImages); @@ -613,12 +701,23 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R celeritasShadowFb); this.dhCompat = new DHCompat(this, shadowDirectives.isDhShadowEnabled().orElse(true)); + + this.shadowVoxelizationCompute = createShadowVoxelizationCompute(); + bindVoxelizationMatrixUniforms(); } private RenderTargets getRenderTargets() { return renderTargets; } + private void recordSamplerUsage(int mask) { + packSamplerUsage |= mask; + } + + private boolean usesSampler(int bit) { + return (packSamplerUsage & bit) != 0; + } + private void checkWorld() { // If we're not in a world, then obviously we cannot possibly be rendering a world. if (Minecraft.getMinecraft().theWorld == null) { @@ -803,17 +902,32 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R */ public void onModProgramOverride() { current = null; + currentCondition = null; } private void matchPass() { - if (!isRenderingWorld || isRenderingFullScreenPass || isPostChain || !isMainBound) { + if (!shouldOverrideShaders()) { + return; + } + + matchPass(getCondition(getPhase())); + } + + private void matchPass(RenderCondition condition) { + currentCondition = condition; + beginPass(table.match(condition, inputs)); + } + + @Override + public void onEntityRenderBoundary() { + if (!shouldOverrideShaders()) { return; } final RenderCondition condition = getCondition(getPhase()); - final Pass matched = table.match(condition, inputs); - - beginPass(matched); + if (condition != currentCondition) { + matchPass(condition); + } } public void beginPass(Pass pass) { @@ -834,6 +948,23 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } } + @Override + public void rebindCurrentPass() { + final Pass pass = this.current; + if (pass == null) { + if (GLStateManager.getActiveProgram() == 0) { + matchPass(); + } + return; + } + final Program program = pass.getProgram(); + final GlFramebuffer expected = isBeforeTranslucent ? pass.framebufferBeforeTranslucents : pass.framebufferAfterTranslucents; + if (program != null && GLStateManager.getActiveProgram() == program.getProgramId() && GLStateManager.getDrawFramebuffer() == expected.getId()) { + return; + } + pass.use(); + } + private Pass createDefaultPass() { final GlFramebuffer framebufferBeforeTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); final GlFramebuffer framebufferAfterTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, new int[] {0}); @@ -843,6 +974,18 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R null, Collections.emptyList(), false); } + private static ProgramBuilder beginBuilder(String name, Map transformed) { + final String vertex = transformed.get(PatchShaderType.VERTEX); + final String geometry = transformed.get(PatchShaderType.GEOMETRY); + final String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); + final String tessEval = transformed.get(PatchShaderType.TESS_EVAL); + final String fragment = transformed.get(PatchShaderType.FRAGMENT); + + PatchedShaderPrinter.debugPatchedShaders(name, vertex, geometry, tessControl, tessEval, fragment); + + return ProgramBuilder.begin(name, vertex, geometry, tessControl, tessEval, fragment, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); + } + private Pass createPass(ProgramSource source, InputAvailability availability, boolean shadow, ProgramId id) { // Use pre-computed transform if available, otherwise transform synchronously Pair key = Pair.of(source.getName(), availability); @@ -862,32 +1005,18 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R scrollGlint); } - String vertex = transformed.get(PatchShaderType.VERTEX); - String geometry = transformed.get(PatchShaderType.GEOMETRY); - String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); - String tessEval = transformed.get(PatchShaderType.TESS_EVAL); - String fragment = transformed.get(PatchShaderType.FRAGMENT); + ProgramBuilder builder = beginBuilder(source.getName(), transformed); - PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment); - - ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment, - IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); - - return createPassInner(builder, source.getDirectives(), availability, shadow, id); + final Pass pass = createPassInner(builder, source.getDirectives(), availability, shadow, id); + pass.setInstancingKey(source.getName(), availability, shadow); + return pass; } - private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) { - + private void wireGbufferProgram(ProgramBuilder builder, InputAvailability availability, boolean shadow) { CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); this.customUniforms.assignTo(builder); - Supplier> flipped; - - if (shadow) { - flipped = () -> (shouldRenderPrepareBeforeShadow ? flippedAfterPrepare : flippedBeforeShadow); - } else { - flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; - } + final Supplier> flipped = shadow ? flippedShadowGbuffers : flippedGbuffers; TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; @@ -905,7 +1034,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, availability); if (!shadow) { - IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); + recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets)); } IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); @@ -920,17 +1049,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } if (shadowRenderTargets != null) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true)); IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); } } + } + + private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) { + + wireGbufferProgram(builder, availability, shadow); GlFramebuffer framebufferBeforeTranslucents; GlFramebuffer framebufferAfterTranslucents; if (shadow) { - // Always add both draw buffers on the shadow pass. - framebufferBeforeTranslucents = shadowTargetsSupplier.get().createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] { 0, 1 }); + final int[] shadowDrawBuffers = programDirectives.hasUnknownDrawBuffers() ? new int[] { 0, 1 } : programDirectives.getDrawBuffers(); + framebufferBeforeTranslucents = shadowTargetsSupplier.get().createShadowFramebuffer(shadowRenderTargets.snapshot(), shadowDrawBuffers); framebufferAfterTranslucents = framebufferBeforeTranslucents; } else { framebufferBeforeTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, programDirectives.getDrawBuffers()); @@ -978,7 +1112,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(hasTexture, hasLightmap)); if (!isShadowPass) { - IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); + recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets)); } IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -986,7 +1120,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisImages.addCustomImages(images, customImages); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, true)); } if (isShadowPass || IrisImages.hasShadowImages(images)) { @@ -1055,15 +1189,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } public ImmutableSet getFlippedBeforeShadow() { - return flippedBeforeShadow; + return parityState.resolve(flippedBeforeShadow); } public ImmutableSet getFlippedAfterPrepare() { - return flippedAfterPrepare; + return parityState.resolve(flippedAfterPrepare); } public ImmutableSet getFlippedAfterTranslucent() { - return flippedAfterTranslucent; + return parityState.resolve(flippedAfterTranslucent); } public GlFramebuffer createDHFramebufferShadow(ProgramSource sources) { @@ -1088,6 +1222,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final List bufferBlendOverrides; private final boolean shadowViewport; + private String instancingSourceName; + private InputAvailability instancingAvailability; + private boolean instancingShadow; + @Nullable private Program instancedVariant; + private boolean instancedVariantAttempted; + private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents, @Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List bufferBlendOverrides, boolean shadowViewport) { this.program = program; @@ -1159,18 +1299,78 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return program; } + void setInstancingKey(String sourceName, InputAvailability availability, boolean shadow) { + this.instancingSourceName = sourceName; + this.instancingAvailability = availability; + this.instancingShadow = shadow; + } + + @Nullable + Program getInstancedVariant() { + if (!instancedVariantAttempted) { + instancedVariantAttempted = true; + if (instancingSourceName != null && supportsTesrInstancing) { + instancedVariant = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow); + } + } + return instancedVariant; + } + public void destroy() { if (this.program != null) { this.program.destroy(); } + if (this.instancedVariant != null) { + this.instancedVariant.destroy(); + this.instancedVariant = null; + } } } + @Nullable + private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow) { + final Map transformed = instancedAttributeTransforms.get(Pair.of(sourceName, availability)); + if (transformed == null) { + return null; + } + try { + final ProgramBuilder builder = beginBuilder(sourceName + "_instanced", transformed); + wireGbufferProgram(builder, availability, shadow); + final Program variant = builder.build(); + this.customUniforms.mapholderToPass(builder, variant); + return variant; + } catch (Exception e) { + Iris.logger.warn("TESR instanced variant link failed for {}; disabling TESR instancing", sourceName, e); + supportsTesrInstancing = false; + return null; + } + } + + public boolean supportsTesrInstancing() { + return supportsTesrInstancing; + } + + public boolean hasTesrInstancedVariant() { + final Pass pass = current; + return pass != null && pass.getInstancedVariant() != null; + } + + public void bindTesrInstancedVariant() { + final Pass pass = current; + final Program variant = pass.getInstancedVariant(); + variant.use(); + this.customUniforms.push(variant); + } + @Override public void destroy() { DepthColorStorage.unlockDepthColor(); BlendModeOverride.restore(); AlphaTestOverride.restore(); + GLStateManager.enableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1f); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.incrementFragmentGeneration(); FullScreenQuadRenderer.clearLocCache(); destroyPasses(table); @@ -1202,6 +1402,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } } } + if (shadowVoxelizationCompute != null) { + shadowVoxelizationCompute.destroy(); + shadowVoxelizationCompute = null; + } // Destroy shadow composite renderer if (shadowCompositeRenderer != null) { @@ -1263,26 +1467,23 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } private void prepareRenderTargets() { + parityState.onFrameStart(); // Make sure we're using texture unit 0 for this. GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); - final Vector4f emptyClearColor = new Vector4f(1.0F); if (shadowRenderTargets != null) { + profiler.startSection("iris_shadow_clear"); if (packDirectives.getShadowDirectives().isShadowEnabled() == OptionalBoolean.FALSE) { if (shadowRenderTargets.isFullClearRequired()) { shadowRenderTargets.onFullClear(); for (ClearPass clearPass : shadowClearPassesFull) { - clearPass.execute(emptyClearColor); + clearPass.execute(EMPTY_CLEAR_COLOR); } } } else { // Clear depth first, regardless of any color clearing. shadowRenderTargets.getDepthSourceFb().bind(); GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); - if (Minecraft.isRunningOnMac) { - GLStateManager.glGetError(); - } - ImmutableList passes; @@ -1302,11 +1503,13 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } for (ClearPass clearPass : passes) { - clearPass.execute(emptyClearColor); + clearPass.execute(EMPTY_CLEAR_COLOR); } } + profiler.endSection(); } + profiler.startSection("iris_clear"); final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); final int depthTextureId = ((IRenderTargetExt)main).iris$getDepthTextureId(); @@ -1317,6 +1520,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R main.framebufferHeight, depthBufferFormat, packDirectives); if (changed) { + profiler.startSection("iris_clear_resize"); beginRenderer.recalculateSizes(); prepareRenderer.recalculateSizes(); deferredRenderer.recalculateSizes(); @@ -1353,12 +1557,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ComputeProgram.unbind(); RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); } + profiler.endSection(); } final ImmutableList passes; if (renderTargets.isFullClearRequired()) { renderTargets.onFullClear(); + parityState.reset(); passes = clearPassesFull; } else { passes = clearPasses; @@ -1376,6 +1582,73 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // Reset framebuffer and viewport Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); + profiler.endSection(); + } + + @Nullable + private ComputeProgram createShadowVoxelizationCompute() { + if (celeritasTerrainPipeline == null) return null; + final Optional sourceOpt = celeritasTerrainPipeline.getShadowVoxelizationComputeSource(); + if (sourceOpt.isEmpty()) return null; + final String src = sourceOpt.get(); + final ProgramBuilder builder; + try { + PatchedShaderPrinter.debugPatchedShaders("shadow_voxelization_compute", null, null, null, src); + builder = ProgramBuilder.beginCompute("shadow_voxelization", src, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); + } catch (RuntimeException e) { + Iris.logger.error("Voxelization compute shader compilation failed; colored lighting will not render", e); + return null; + } + CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); + this.customUniforms.assignTo(builder); + final Supplier> flipped = () -> flippedBeforeShadow; + final TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; + final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = + ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage)); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); + IrisImages.addRenderTargetImages(builder, flipped, renderTargets); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); + IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); + IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); + IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures()); + if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor) && shadowRenderTargets != null) { + IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true); + IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); + } + customImages.stream() + .sorted(Comparator.comparing(GlImage::getName)) + .forEach(image -> builder.addTextureImage(image::getId, image.getInternalFormat(), image.getName())); + final ComputeProgram program = builder.buildCompute(); + this.customUniforms.mapholderToPass(builder, program); + return program; + } + + @Nullable + public ComputeProgram getShadowVoxelizationCompute() { return shadowVoxelizationCompute; } + + private GlUniformMatrix4f voxelizationModelView; + private GlUniformMatrix3f voxelizationNormalMatrix; + private final Matrix3f voxelizationNormalScratch = new Matrix3f(); + + private void bindVoxelizationMatrixUniforms() { + if (shadowVoxelizationCompute == null) return; + final int id = shadowVoxelizationCompute.getProgramId(); + final int modelView = GLStateManager.glGetUniformLocation(id, "iris_ModelViewMatrix"); + final int normal = GLStateManager.glGetUniformLocation(id, "iris_NormalMatrix"); + this.voxelizationModelView = modelView >= 0 ? new GlUniformMatrix4f(modelView) : null; + this.voxelizationNormalMatrix = normal >= 0 ? new GlUniformMatrix3f(normal) : null; + } + + public void prepareShadowVoxelizationCompute(Matrix4fc modelView) { + if (shadowVoxelizationCompute == null) return; + if (voxelizationModelView != null) { + voxelizationModelView.set(modelView); + } + if (voxelizationNormalMatrix != null) { + voxelizationNormalScratch.set(modelView).invert().transpose(); + voxelizationNormalMatrix.set(voxelizationNormalScratch); + } + customUniforms.push(shadowVoxelizationCompute); } private ComputeProgram[] createShadowComputes(ComputeSource[] compute) { @@ -1399,9 +1672,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); this.customUniforms.assignTo(builder); - Supplier> flipped; - - flipped = () -> flippedBeforeShadow; + final Supplier> flipped = flippedBeforeShadowResolved; TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; @@ -1420,7 +1691,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { if (shadowRenderTargets != null) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true)); IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); } } @@ -1439,7 +1710,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return programs; } - private ComputeProgram[] createSetupComputes(ComputeSource[] compute) { + private ComputeProgram[] createSetupComputes(ComputeSource[] compute, Int2ObjectArrayMap> futures) { ComputeProgram[] programs = new ComputeProgram[compute.length]; for (int i = 0; i < programs.length; i++) { ComputeSource source = compute[i]; @@ -1449,7 +1720,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ProgramBuilder builder; try { - String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SETUP, getTextureMap()); + final CompletableFuture future = futures.get(i); + final String transformed = future != null ? future.join() : TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SETUP, getTextureMap()); PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (RuntimeException e) { @@ -1473,11 +1745,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisImages.addCustomImages(builder, customImages); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); - IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); + recordSamplerUsage(IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets)); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { if (shadowRenderTargets != null) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true); + recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true)); IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); } } @@ -1495,9 +1767,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void beginHand() { + if (!usesSampler(IrisSamplers.USAGE_DEPTHTEX2)) { + return; + } + // We need to copy the current depth texture so that depthtex2 can contain the depth values for // all non-translucent content without the hand, as required. + profiler.startSection("iris_hand_depth_copy"); renderTargets.copyPreHandDepth(); + profiler.endSection(); } @Override @@ -1506,7 +1784,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // We need to copy the current depth texture so that depthtex1 can contain the depth values for // all non-translucent content, as required. - renderTargets.copyPreTranslucentDepth(); + if (usesSampler(IrisSamplers.USAGE_DEPTHTEX1)) { + profiler.startSection("iris_translucent_depth_copy"); + renderTargets.copyPreTranslucentDepth(); + profiler.endSection(); + } // needed to remove blend mode overrides and similar @@ -1514,7 +1796,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R isRenderingFullScreenPass = true; - deferredRenderer.renderAll(); + profiler.startSection("iris_deferred"); + GLDebug.pushGroup("deferred"); + try { + deferredRenderer.renderAll(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } GLStateManager.enableBlend(); GLStateManager.enableAlphaTest(); @@ -1531,12 +1820,24 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R isRenderingFullScreenPass = false; } + @Override + public void preSubmitShadowGraph(int frame, boolean spectator) { + if (shadowRenderer != null) shadowRenderer.preSubmitGraphUpdate(frame, spectator); + } + @Override public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) { if (shouldRenderPrepareBeforeShadow) { isRenderingFullScreenPass = true; - prepareRenderer.renderAll(); + profiler.startSection("iris_prepare_passes"); + GLDebug.pushGroup("prepare"); + try { + prepareRenderer.renderAll(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } isRenderingFullScreenPass = false; } @@ -1545,7 +1846,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R isRenderingShadow = true; matchPass(); // Ensure shadow shader is bound for entity rendering - shadowRenderer.renderShadows(levelRenderer, playerCamera); + GLDebug.pushGroup("shadow"); + try { + shadowRenderer.renderShadows(levelRenderer, playerCamera); + } finally { + GLDebug.popGroup(); + } // needed to remove blend mode overrides and similar beginPass(null); @@ -1555,7 +1861,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R if (!shouldRenderPrepareBeforeShadow) { isRenderingFullScreenPass = true; - prepareRenderer.renderAll(); + profiler.startSection("iris_prepare_passes"); + GLDebug.pushGroup("prepare"); + try { + prepareRenderer.renderAll(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } isRenderingFullScreenPass = false; } @@ -1608,6 +1921,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R throw new IllegalStateException("Called beginLevelRendering but level rendering appears to still be in progress?"); } + profiler.startSection("iris_uniforms"); updateNotifier.onNewFrame(); this.customUniforms.update(); @@ -1616,17 +1930,32 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R if (ssboHolder != null) { ssboHolder.setupBuffers(); } + profiler.endSection(); // Get ready for world rendering prepareRenderTargets(); // Clear custom images that need clearing each frame - for (GlImage image : imagesToClear) { - image.clear(); + if (imagesToClear.length > 0) { + profiler.startSection("iris_clear_images"); + for (GlImage image : imagesToClear) { + image.clear(); + } + profiler.endSection(); } + GLDebug.pushGroup("world"); + worldGroupActive = true; + isRenderingFullScreenPass = true; - beginRenderer.renderAll(); + profiler.startSection("iris_begin_passes"); + GLDebug.pushGroup("begin"); + try { + beginRenderer.renderAll(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } isRenderingFullScreenPass = false; setPhase(WorldRenderingPhase.SKY); @@ -1638,6 +1967,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // DimensionSpecialEffects.SkyType skyType = Minecraft.getMinecraft().theWorld.effects().skyType(); if (true/*skyType == DimensionSpecialEffects.SkyType.NORMAL*/) { + profiler.startSection("iris_horizon"); GLStateManager.glDisable(GL11.GL_TEXTURE_2D); GLStateManager.glDepthMask(false); @@ -1648,6 +1978,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R GLStateManager.glDepthMask(true); GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + profiler.endSection(); } } @@ -1665,15 +1996,38 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R isRenderingWorld = false; phase = WorldRenderingPhase.NONE; overridePhase = null; + syncPhaseDebugGroup(); isRenderingFullScreenPass = true; + profiler.startSection("iris_center_depth"); centerDepthSampler.sampleCenterDepth(); + profiler.endSection(); - compositeRenderer.renderAll(); - finalPassRenderer.renderFinalPass(); + profiler.startSection("iris_composites"); + GLDebug.pushGroup("composite"); + try { + compositeRenderer.renderAll(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } + + profiler.startSection("iris_final_pass"); + GLDebug.pushGroup("final"); + try { + finalPassRenderer.renderFinalPass(); + } finally { + GLDebug.popGroup(); + profiler.endSection(); + } isRenderingFullScreenPass = false; + + if (worldGroupActive) { + GLDebug.popGroup(); + worldGroupActive = false; + } } @Override @@ -1703,6 +2057,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void setOverridePhase(WorldRenderingPhase phase) { this.overridePhase = phase; + syncPhaseDebugGroup(); matchPass(); GbufferPrograms.runPhaseChangeNotifier(); } @@ -1710,10 +2065,34 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void setPhase(WorldRenderingPhase phase) { this.phase = phase; + syncPhaseDebugGroup(); matchPass(); GbufferPrograms.runPhaseChangeNotifier(); } + private static final String[] PHASE_GROUP_NAMES = buildPhaseGroupNames(); + + private static String[] buildPhaseGroupNames() { + final WorldRenderingPhase[] phases = WorldRenderingPhase.values(); + final String[] names = new String[phases.length]; + for (int i = 0; i < phases.length; i++) { + names[i] = "phase:" + phases[i].name(); + } + return names; + } + + private void syncPhaseDebugGroup() { + final WorldRenderingPhase target = overridePhase != null ? overridePhase : phase; + if (target == pushedPhase) return; + if (pushedPhase != WorldRenderingPhase.NONE) { + GLDebug.popGroup(); + } + if (target != WorldRenderingPhase.NONE) { + GLDebug.pushGroup(PHASE_GROUP_NAMES[target.ordinal()]); + } + pushedPhase = target; + } + @Override public void setInputs(InputAvailability availability) { this.inputs = availability; @@ -1759,9 +2138,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } private static final InputAvailability INPUT_NONE = new InputAvailability(false, false); + private static final InputAvailability INPUT_LIGHTMAP_ONLY = new InputAvailability(false, true); private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false); private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true); - private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP }; + private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_LIGHTMAP_ONLY, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP }; private static CompletableFuture> submitCompositeTransform(ProgramSource source, TextureStage stage, Object2ObjectMap, String> textureMap) { @@ -1792,29 +2172,88 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } private static Map, CompletableFuture>> - submitAttributeTransforms(ProgramFallbackResolver resolver) { + submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, boolean instanced) { final Map, CompletableFuture>> futures = new HashMap<>(); final Set processedSourceNames = new HashSet<>(); - for (ProgramId id : ProgramId.values()) { - ProgramSource source = resolver.resolveNullable(id); - if (source != null && !processedSourceNames.contains(source.getName())) { - processedSourceNames.add(source.getName()); - final ProgramSource src = source; - final String vertexSource = src.getVertexSource().orElse(null); - final boolean scrollGlint = GlintScrollInjector.shouldInject(id, src); - for (InputAvailability avail : INPUT_AVAILABILITIES) { - Pair key = Pair.of(src.getName(), avail); - futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(vertexSource, src.getGeometrySource().orElse(null), src.getTessControlSource().orElse(null), src.getTessEvalSource().orElse(null), src.getFragmentSource().orElse(null), avail, scrollGlint))); - } + for (ProgramId id : ids) { + if (id.getGroup() == ProgramGroup.Dh) continue; + final ProgramSource source = resolver.resolveNullable(id); + if (source == null || !processedSourceNames.add(source.getName())) { + continue; + } + if (instanced && referencesMvBuiltinsOutsideVertex(source)) { + Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", source.getName()); + continue; + } + final String vertexSource = source.getVertexSource().orElse(null); + final boolean scrollGlint = GlintScrollInjector.shouldInject(id, source); + for (InputAvailability avail : INPUT_AVAILABILITIES) { + futures.put(Pair.of(source.getName(), avail), Iris.ShaderTransformExecutor.submitTracked(() -> { + final String geometry = source.getGeometrySource().orElse(null); + final String tessControl = source.getTessControlSource().orElse(null); + final String tessEval = source.getTessEvalSource().orElse(null); + final String fragment = source.getFragmentSource().orElse(null); + return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint) + : TransformPatcher.patchAttributes(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint); + })); } } return futures; } + private static final ProgramId[] INSTANCED_PROGRAM_IDS = { + ProgramId.Block, ProgramId.BlockTrans, ProgramId.Entities, ProgramId.EntitiesTrans, + ProgramId.Shadow, ProgramId.ShadowWater + }; + + private static final String[] MV_BUILTINS = { + "gl_ModelViewMatrix", "gl_ModelViewMatrixInverse", + "gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixInverse", + "gl_NormalMatrix", "ftransform" + }; + + static boolean referencesMvBuiltins(String source) { + if (source == null) { + return false; + } + try { + final Transformer transformer = new Transformer(ShaderParser.parseShader(source).full()); + for (String builtin : MV_BUILTINS) { + if (transformer.containsCall(builtin)) { + return true; + } + } + return false; + } catch (Exception e) { + return true; + } + } + + private static boolean referencesMvBuiltinsOutsideVertex(ProgramSource source) { + return referencesMvBuiltins(source.getGeometrySource().orElse(null)) + || referencesMvBuiltins(source.getTessControlSource().orElse(null)) + || referencesMvBuiltins(source.getTessEvalSource().orElse(null)) + || referencesMvBuiltins(source.getFragmentSource().orElse(null)); + } + private static CompletableFuture> submitCeleritasTerrainTransform(ProgramSource source) { return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchCeleritasTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null))); } + private static Int2ObjectArrayMap> submitSetupComputeTransforms(ComputeSource[] compute, + Object2ObjectMap, String> textureMap) { + if (compute == null) return new Int2ObjectArrayMap<>(0); + final Int2ObjectArrayMap> futures = new Int2ObjectArrayMap<>(compute.length); + for (int i = 0; i < compute.length; i++) { + final ComputeSource source = compute[i]; + if (source == null || !source.getSource().isPresent()) continue; + final String name = source.getName(); + final String src = source.getSource().get(); + futures.put(i, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchCompute(name, src, TextureStage.SETUP, textureMap))); + } + return futures; + } + @SafeVarargs private static Optional first(Optional... candidates) { for (Optional candidate : candidates) { @@ -1824,4 +2263,5 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } return Optional.empty(); } + } diff --git a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java index f03cc16c8..57da5a3cd 100644 --- a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java @@ -11,7 +11,7 @@ import net.coderbot.iris.features.FeatureFlags; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.shaderpack.CloudSetting; import net.coderbot.iris.shaderpack.texture.TextureStage; @@ -103,6 +103,11 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli } + @Override + public void rebindCurrentPass() { + // no-op: fixed-function pipeline doesn't manage Pass state + } + @Override public void beginHand() { // stub: nothing to do here diff --git a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java index 51c2689c6..7203d6a86 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java @@ -5,11 +5,18 @@ import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.profiling.RenderClassTimings; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.rendering.PlayerReflectionCapture; import com.gtnewhorizons.angelica.rendering.RenderingState; +import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaRenderSectionManager; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.coderbot.iris.Iris; import net.coderbot.iris.compat.dh.DHCompat; import net.coderbot.iris.gui.option.IrisVideoSettings; @@ -21,6 +28,7 @@ import net.coderbot.iris.shaderpack.ShadowCullState; import net.coderbot.iris.shadow.ShadowMatrices; import net.coderbot.iris.shadows.CullingDataCache; import net.coderbot.iris.shadows.ShadowCompositeRenderer; +import net.coderbot.iris.shadows.ShadowGraphGate; import net.coderbot.iris.shadows.ShadowRenderTargets; import net.coderbot.iris.shadows.frustum.BoxCuller; import net.coderbot.iris.shadows.frustum.CullEverythingFrustum; @@ -31,6 +39,7 @@ import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum; import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.CelestialUniforms; +import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.EntityRenderer; @@ -43,6 +52,7 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; +import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider; import org.joml.Matrix4f; import org.joml.Matrix4fc; @@ -62,13 +72,20 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; +import java.util.function.BooleanSupplier; public class ShadowRenderer { + private static final long P_SHADOW_ENTITIES_RENDERED = Tracy.plotHandle("shadow.entitiesRendered"); + private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_SHADOW_FRUSTUM = Tracy.zoneId("shadowFrustum", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_SHADOW_VIEWPORT = Tracy.zoneId("shadowViewport", Tracy.COLOR_IRIS); + private static final Tracy.ZoneId Z_SHADOW_MODEL_PARTS = Tracy.zoneId("shadowModelParts", Tracy.COLOR_IRIS); + public static final Matrix4f MODELVIEW = new Matrix4f(); public static final FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16); public static final Matrix4f PROJECTION = new Matrix4f(); - public static final List visibleTileEntities = new ArrayList<>(); - public static final List globalTileEntities = new ArrayList<>(); + public static final List> visibleTileEntities = new ArrayList<>(); + public static final List> globalTileEntities = new ArrayList<>(); public static boolean ACTIVE = false; public static Frustrum FRUSTUM; @@ -89,6 +106,7 @@ public class ShadowRenderer { private final ShadowCullState packCullingState; private final ShadowCompositeRenderer compositeRenderer; private boolean packHasVoxelization; + private boolean playerReflectionCaptureEnabled = true; private final boolean shouldRenderTerrain; private final boolean shouldRenderTranslucent; private final boolean shouldRenderEntities; @@ -102,26 +120,66 @@ public class ShadowRenderer { private int renderedShadowEntities = 0; private int renderedShadowTileEntities = 0; private Profiler profiler; - private final List renderedEntitiesList = new ArrayList<>(64); + private final ObjectArrayList renderedEntitiesList = new ObjectArrayList<>(64); private final MatrixStack shadowModelView = new MatrixStack(); private final CelestialUniforms celestialUniforms; - private final AdvancedShadowCullingFrustum cachedAdvancedFrustum = new AdvancedShadowCullingFrustum(); + private static final class FrustumCaches { + final AdvancedShadowCullingFrustum advancedFrustum = new AdvancedShadowCullingFrustum(); + BoxCuller boxCuller; + BoxCullingFrustum boxCullingFrustum; + BoxCuller advancedBoxCuller; + double lastBoxCullerDistance = -1; + double lastAdvancedBoxCullerDistance = -1; + } + + private static final long SHADOW_RELAY_MAX_AGE_NANOS = 250_000_000L; + + public static boolean SHADOW_TERRAIN_RELAID = true; + private static float activeShadowAngle = Float.NaN; + + private final FrustumCaches terrainFrustumCaches = new FrustumCaches(); + private final FrustumCaches entityFrustumCaches = new FrustumCaches(); + private float lastGraphShadowAngle = Float.NaN; + private float relayShadowAngle = Float.NaN; + private FrustumHolder preSubmitFrustumHolder = new FrustumHolder(); + private final FrustumCaches preSubmitFrustumCaches = new FrustumCaches(); + private boolean preSubmitActive; + private float preSubmittedShadowAngle = Float.NaN; + + public void preSubmitGraphUpdate(int frame, boolean spectator) { + final AngelicaRenderSectionManager rsm = CeleritasWorldRenderer.getInstance().getRenderSectionManager(); + final float currentShadowAngle = getShadowAngle(); + if (ShadowGraphGate.shouldMarkDirty(lastGraphShadowAngle, currentShadowAngle)) { + rsm.markShadowGraphDirty(); + lastGraphShadowAngle = currentShadowAngle; + } + if (!rsm.isShadowGraphDirty()) return; + + preSubmitFrustumHolder = createShadowFrustum(renderDistanceMultiplier, preSubmitFrustumHolder, preSubmitFrustumCaches); + if (!(preSubmitFrustumHolder.getFrustum() instanceof ViewportProvider provider)) return; + final Vector3d entityPos = Camera.INSTANCE.getEntityPos(); + preSubmitFrustumHolder.getFrustum().setPosition(entityPos.x, entityPos.y, entityPos.z); + + if (rsm.preSubmitShadowGraphUpdate(provider.sodium$createViewport(), frame, spectator)) { + preSubmittedShadowAngle = lastGraphShadowAngle; + preSubmitActive = true; + } + } + private long lastRelayNanos; private final Vector3f shadowLightVectorCache = new Vector3f(); - private BoxCuller cachedBoxCuller; - private BoxCullingFrustum cachedBoxCullingFrustum; - private BoxCuller cachedAdvancedBoxCuller; private BoxCuller cachedTileEntityCuller; - private double lastBoxCullerDistance = -1; - private double lastAdvancedBoxCullerDistance = -1; private double lastTileEntityCullerDistance = -1; private final boolean shouldRenderDH; private final float nearPlane, farPlane; + private final BooleanSupplier packUsesShadowtex1; - public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer) { + public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer, BooleanSupplier packUsesShadowtex1) { this.profiler = Minecraft.getMinecraft().mcProfiler; + SHADOW_TERRAIN_RELAID = true; + activeShadowAngle = Float.NaN; final PackShadowDirectives shadowDirectives = directives.getShadowDirectives(); this.nearPlane = shadowDirectives.getNearPlane(); @@ -139,6 +197,7 @@ public class ShadowRenderer { this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer(); this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities(); this.shouldRenderDH = shadowDirectives.isDhShadowEnabled().orElse(false); + this.packUsesShadowtex1 = packUsesShadowtex1; this.compositeRenderer = compositeRenderer; @@ -178,22 +237,28 @@ public class ShadowRenderer { this.packHasVoxelization = packHasVoxelization || usesImages; } + public void setPlayerReflectionCaptureEnabled(boolean enabled) { + this.playerReflectionCaptureEnabled = enabled; + } + public static MatrixStack createShadowModelView(float sunPathRotation, float intervalSize) { // Use entity position for shadow matrix final Vector3d entityPos = Camera.INSTANCE.getEntityPos(); + final float angle = Float.isNaN(activeShadowAngle) ? getShadowAngle() : activeShadowAngle; + // Set up our modelview matrix stack final MatrixStack modelView = new MatrixStack(); - ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, entityPos.x, entityPos.y, entityPos.z); + ShadowMatrices.createModelViewMatrix(modelView, angle, intervalSize, sunPathRotation, entityPos.x, entityPos.y, entityPos.z); return modelView; } - private MatrixStack getShadowModelView() { + private MatrixStack getShadowModelView(float shadowAngle) { final Vector3d entityPos = Camera.INSTANCE.getEntityPos(); shadowModelView.reset(); - ShadowMatrices.createModelViewMatrix(shadowModelView, getShadowAngle(), this.intervalSize, this.sunPathRotation, entityPos.x, entityPos.y, entityPos.z); + ShadowMatrices.createModelViewMatrix(shadowModelView, shadowAngle, this.intervalSize, this.sunPathRotation, entityPos.x, entityPos.y, entityPos.z); return shadowModelView; } @@ -292,11 +357,19 @@ public class ShadowRenderer { } private void setupMipmappingForTexture(int texture, int filteringMode) { - RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + if (Tracy.ENABLED) { + Tracy.beginZone(Z_GEN_MIPMAP); + Tracy.zoneValue(texture); + } + try { + RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filteringMode); } - private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder) { + private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder, FrustumCaches caches) { // TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected. String distanceInfo; String cullingInfo; @@ -319,7 +392,7 @@ public class ShadowRenderer { } else { distanceInfo = distance + " blocks (set by shader pack)"; cullingInfo = "distance only " + reason; - holder.setInfo(getOrCreateBoxCullingFrustum(distance), distanceInfo, cullingInfo); + holder.setInfo(getOrCreateBoxCullingFrustum(distance, caches), distanceInfo, cullingInfo); } } else { BoxCuller boxCuller; @@ -349,7 +422,7 @@ public class ShadowRenderer { return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo); } - boxCuller = getOrCreateAdvancedBoxCuller(distance); + boxCuller = getOrCreateAdvancedBoxCuller(distance, caches); } cullingInfo = (hasSafeZone ? "Safe Zone" : "Advanced") + " Frustum Culling enabled"; @@ -367,35 +440,35 @@ public class ShadowRenderer { shadowLightVectorCache, boxCuller, distanceCuller); return holder.setInfo(safeZoneFrustum, distanceInfo, cullingInfo); } else { - cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache, boxCuller); - return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo); + caches.advancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache, boxCuller); + return holder.setInfo(caches.advancedFrustum, distanceInfo, cullingInfo); } } return holder; } - private BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance) { - if (cachedBoxCuller == null) { - cachedBoxCuller = new BoxCuller(distance); - cachedBoxCullingFrustum = new BoxCullingFrustum(cachedBoxCuller); - lastBoxCullerDistance = distance; - } else if (lastBoxCullerDistance != distance) { - cachedBoxCuller.setMaxDistance(distance); - lastBoxCullerDistance = distance; + private static BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance, FrustumCaches caches) { + if (caches.boxCuller == null) { + caches.boxCuller = new BoxCuller(distance); + caches.boxCullingFrustum = new BoxCullingFrustum(caches.boxCuller); + caches.lastBoxCullerDistance = distance; + } else if (caches.lastBoxCullerDistance != distance) { + caches.boxCuller.setMaxDistance(distance); + caches.lastBoxCullerDistance = distance; } - return cachedBoxCullingFrustum; + return caches.boxCullingFrustum; } - private BoxCuller getOrCreateAdvancedBoxCuller(double distance) { - if (cachedAdvancedBoxCuller == null) { - cachedAdvancedBoxCuller = new BoxCuller(distance); - lastAdvancedBoxCullerDistance = distance; - } else if (lastAdvancedBoxCullerDistance != distance) { - cachedAdvancedBoxCuller.setMaxDistance(distance); - lastAdvancedBoxCullerDistance = distance; + private static BoxCuller getOrCreateAdvancedBoxCuller(double distance, FrustumCaches caches) { + if (caches.advancedBoxCuller == null) { + caches.advancedBoxCuller = new BoxCuller(distance); + caches.lastAdvancedBoxCullerDistance = distance; + } else if (caches.lastAdvancedBoxCullerDistance != distance) { + caches.advancedBoxCuller.setMaxDistance(distance); + caches.lastAdvancedBoxCullerDistance = distance; } - return cachedAdvancedBoxCuller; + return caches.advancedBoxCuller; } private BoxCuller getOrCreateTileEntityCuller(double distance) { @@ -410,8 +483,6 @@ public class ShadowRenderer { } private void setupGlState(Matrix4f projMatrix) { - // Bind shadow framebuffer and set viewport to shadow resolution - targets.getDepthSourceFb().bind(); GLStateManager.glViewport(0, 0, resolution, resolution); // Set up our projection matrix and load it into the legacy matrix stack @@ -434,6 +505,9 @@ public class ShadowRenderer { // Make sure to unload the projection matrix RenderSystem.restoreProjectionMatrix(); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glClearDepth(1.0); + // Restore main framebuffer and viewport Minecraft mc = Minecraft.getMinecraft(); mc.getFramebuffer().bindFramebuffer(false); @@ -441,13 +515,17 @@ public class ShadowRenderer { } private void copyPreTranslucentDepth() { - profiler.endStartSection("translucent depth copy"); + if (!packUsesShadowtex1.getAsBoolean()) { + return; + } + + profiler.endStartSection("iris_shadow_translucent_depth_copy"); targets.copyPreTranslucentDepth(); } private void renderEntities(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) { - profiler.startSection("cull"); + profiler.startSection("iris_shadow_cull"); renderedEntitiesList.clear(); @@ -462,31 +540,111 @@ public class ShadowRenderer { renderedEntitiesList.add(entity); } - profiler.endStartSection("sort"); + profiler.endStartSection("iris_shadow_sort"); - renderedEntitiesList.sort(ENTITY_CLASS_COMPARATOR); + renderedEntitiesList.unstableSort(ENTITY_CLASS_COMPARATOR); - profiler.endStartSection("build geometry"); + profiler.endStartSection("iris_shadow_build_geometry"); setupEntityShadowState(modelView, cameraX, cameraY, cameraZ); - PlayerReflectionCapture.begin(player); + if (playerReflectionCaptureEnabled) { + PlayerReflectionCapture.begin(player); + } + ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.ENTITIES, true); try { for (Entity entity : renderedEntitiesList) { - RenderManager.instance.renderEntitySimple(entity, tickDelta); + final long start = Tracy.ENABLED ? System.nanoTime() : 0L; + try { + RenderManager.instance.renderEntitySimple(entity, tickDelta); + } finally { + if (Tracy.ENABLED) RenderClassTimings.SHADOW_ENTITY.add(entity.getClass(), System.nanoTime() - start); + } } } finally { + flushShadowModelParts(); PlayerReflectionCapture.end(); teardownEntityShadowState(); } renderedShadowEntities = renderedEntitiesList.size(); + if (Tracy.ENABLED) Tracy.plotInt(P_SHADOW_ENTITIES_RENDERED, renderedShadowEntities); profiler.endSection(); } + private boolean entityFrustumConstrained; + + private Frustrum createEntityShadowFrustum(double entityX, double entityY, double entityZ) { + // Shader packs can shrink the entity shadow distance so faraway entities skip the shadow pass + entityFrustumConstrained = false; + if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_FRUSTUM); + try { + if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) { + entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo()); + return entityFrustumHolder.getFrustum(); + } + + entityFrustumConstrained = true; + entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder, entityFrustumCaches); + final Frustrum frustum = entityFrustumHolder.getFrustum(); + frustum.setPosition(entityX, entityY, entityZ); + return frustum; + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private void applyEntityShadowViewport(Frustrum entityShadowFrustum) { + if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_VIEWPORT); + try { + CeleritasWorldRenderer.getInstance().setCurrentViewport(((ViewportProvider) entityShadowFrustum).sodium$createViewport()); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private void renderShadowEntitiesAndPlayer(EntityRenderer levelRenderer, Frustrum entityShadowFrustum, MatrixStack modelView, double entityX, double entityY, double entityZ, float tickDelta) { + if (shouldRenderEntities) { + renderEntities(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta); + } else if (shouldRenderPlayer) { + renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta); + } + } + + private static boolean voxelizationActive() { + return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline deferred && deferred.getShadowVoxelizationCompute() != null; + } + + private void renderSolidShadowTerrain(Minecraft mc, RenderGlobal rg, Camera playerCamera) { + // Render all opaque terrain unless pack requests not to + if (shouldRenderTerrain) { + mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); + rg.sortAndRender(mc.renderViewEntity, 0, playerCamera.getPartialTicks()); + } + + // Reset viewport in case terrain rendering changed it + GLStateManager.glViewport(0, 0, resolution, resolution); + } + // Saved RenderManager position for shadow pass private double savedRenderPosX, savedRenderPosY, savedRenderPosZ; + /** Flushes shadow-pass batched model parts while GL_POLYGON_OFFSET_FILL is still enabled. */ + private static void flushShadowModelParts() { + if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_MODEL_PARTS); + final boolean alphaEnabled = GLStateManager.getAlphaTest().isEnabled(); + final int alphaFunc = GLStateManager.getAlphaState().getFunction(); + final float alphaRef = GLStateManager.getAlphaState().getReference(); + try { + ModelPartBatcher.INSTANCE.flush(); + } finally { + if (alphaEnabled) GLStateManager.enableAlphaTest(); + else GLStateManager.disableAlphaTest(); + GLStateManager.glAlphaFunc(alphaFunc, alphaRef); + if (Tracy.ENABLED) Tracy.endZone(); + } + } + private void setupEntityShadowState(MatrixStack modelView, double cameraX, double cameraY, double cameraZ) { savedRenderPosX = RenderManager.renderPosX; savedRenderPosY = RenderManager.renderPosY; @@ -517,7 +675,7 @@ public class ShadowRenderer { } private void renderPlayerEntity(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) { - profiler.startSection("cull"); + profiler.startSection("iris_shadow_cull"); EntityPlayer player = Minecraft.getMinecraft().thePlayer; @@ -534,11 +692,12 @@ public class ShadowRenderer { return; } - profiler.endStartSection("build geometry"); + profiler.endStartSection("iris_shadow_build_geometry"); int shadowEntities = 0; setupEntityShadowState(modelView, cameraX, cameraY, cameraZ); + ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.ENTITIES, true); try { if (player.riddenByEntity != null) { RenderManager.instance.renderEntitySimple(player.riddenByEntity, tickDelta); @@ -550,7 +709,9 @@ public class ShadowRenderer { shadowEntities++; } - PlayerReflectionCapture.begin(player); + if (playerReflectionCaptureEnabled) { + PlayerReflectionCapture.begin(player); + } try { RenderManager.instance.renderEntitySimple(player, tickDelta); } finally { @@ -558,6 +719,7 @@ public class ShadowRenderer { } shadowEntities++; } finally { + flushShadowModelParts(); teardownEntityShadowState(); } @@ -567,9 +729,22 @@ public class ShadowRenderer { } private void renderTileEntity(TileEntity tile, double cameraX, double cameraY, double cameraZ, float partialTicks) { - if (tile.getDistanceFrom(cameraX, cameraY, cameraZ) >= tile.getMaxRenderDistanceSquared()) { + final double distSq = tile.getDistanceFrom(cameraX, cameraY, cameraZ); + if (distSq >= tile.getMaxRenderDistanceSquared()) { return; } + if (AngelicaConfig.cullShadowTileEntities) { + final int maxD = AngelicaConfig.shadowTileEntityMaxDistance; + if (distSq >= (double) maxD * maxD) { + return; + } + if (AngelicaConfig.shadowSkipInMeshTileEntities) { + final Block block = tile.getBlockType(); + if (block != null && block.getRenderType() != -1) { + return; + } + } + } int brightness = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, (float) brightness % 65536, (float) brightness / 65536); GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); @@ -582,7 +757,7 @@ public class ShadowRenderer { } private void renderTileEntities(Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks, boolean hasEntityFrustum) { - profiler.startSection("build blockentities"); + profiler.startSection("iris_shadow_build_blockentities"); int shadowTileEntities = 0; BoxCuller culler = null; @@ -597,26 +772,40 @@ public class ShadowRenderer { modelView.peek().getModel().get(MODELVIEW_BUFFER); GLStateManager.glLoadMatrix(MODELVIEW_BUFFER); + TesrBatchRenderer.INSTANCE.beginPass(TesrBatchRenderer.PASS_SHADOW, modelView.peek().getModel(), cameraX, cameraY, cameraZ); + GbufferPrograms.beginBlockEntities(); GbufferPrograms.setBlockEntityDefaults(); + ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES, true); - for (TileEntity tileEntity : visibleTileEntities) { - if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { - continue; + for (int b = 0, bn = visibleTileEntities.size(); b < bn; b++) { + final List bucket = visibleTileEntities.get(b); + for (int i = 0, n = bucket.size(); i < n; i++) { + final TileEntity tileEntity = bucket.get(i); + if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { + continue; + } + renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); + + shadowTileEntities++; } - renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); - - shadowTileEntities++; } - for (TileEntity tileEntity : globalTileEntities) { - if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { - continue; + for (int b = 0, bn = globalTileEntities.size(); b < bn; b++) { + final List bucket = globalTileEntities.get(b); + for (int i = 0, n = bucket.size(); i < n; i++) { + final TileEntity tileEntity = bucket.get(i); + if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { + continue; + } + renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); + + shadowTileEntities++; } - renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); - - shadowTileEntities++; } + flushShadowModelParts(); + TesrBatchRenderer.INSTANCE.flush(); + GbufferPrograms.endBlockEntities(); GLStateManager.glPopMatrix(); @@ -633,7 +822,7 @@ public class ShadowRenderer { // If the profiler is inactive, it will return InactiveProfiler.INSTANCE this.profiler = Minecraft.getMinecraft().mcProfiler; - profiler.endStartSection("shadows"); + profiler.endStartSection("iris_shadows"); ACTIVE = true; CURRENT_TARGETS = this.targets; @@ -645,8 +834,32 @@ public class ShadowRenderer { visibleTileEntities.clear(); globalTileEntities.clear(); + final float currentShadowAngle = getShadowAngle(); + if (ShadowGraphGate.shouldMarkDirty(lastGraphShadowAngle, currentShadowAngle)) { + CeleritasWorldRenderer.getInstance().getRenderSectionManager().markShadowGraphDirty(); + lastGraphShadowAngle = currentShadowAngle; + } + + final boolean deferActive = shouldRenderTerrain; + final long frameNanos = System.nanoTime(); + final boolean consumePreSubmit = preSubmitActive; + preSubmitActive = false; + + final boolean relayTerrain = !deferActive + || voxelizationActive() + || !targets.isTerrainSnapshotValid() + || consumePreSubmit + || CeleritasWorldRenderer.getInstance().getRenderSectionManager().isShadowGraphDirty() + || frameNanos - lastRelayNanos >= SHADOW_RELAY_MAX_AGE_NANOS; + if (relayTerrain) { + + relayShadowAngle = consumePreSubmit && !CeleritasWorldRenderer.getInstance().getRenderSectionManager().isShadowGraphDirty() ? preSubmittedShadowAngle : currentShadowAngle; + } + activeShadowAngle = relayShadowAngle; + SHADOW_TERRAIN_RELAID = relayTerrain; + // Create our camera - final MatrixStack modelView = getShadowModelView(); + final MatrixStack modelView = getShadowModelView(relayShadowAngle); MODELVIEW.set(modelView.peek().getModel()); final Matrix4f shadowProjection; @@ -659,15 +872,15 @@ public class ShadowRenderer { PROJECTION.set(shadowProjection); - profiler.startSection("terrain_setup"); + profiler.startSection("iris_shadow_terrain_setup"); if (levelRenderer instanceof CullingDataCache) { ((CullingDataCache) levelRenderer).saveState(); } - profiler.startSection("initialize frustum"); + profiler.startSection("iris_shadow_initialize_frustum"); - terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder); + terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder, terrainFrustumCaches); FRUSTUM = terrainFrustumHolder.getFrustum(); // Use the player/entity position for shadow rendering @@ -681,19 +894,18 @@ public class ShadowRenderer { profiler.endSection(); - // Always schedule a terrain update - // TODO: Only schedule a terrain update if the sun / moon is moving, or the shadow map camera moved. - // We have to ensure that we don't regenerate clouds every frame, since that's what needsUpdate ends up doing. - // This took up to 10% of the frame time before we applied this fix! That's really bad! -// boolean regenerateClouds = levelRenderer.shouldRegenerateClouds(); -// ((LevelRenderer) levelRenderer).needsUpdate(); -// levelRenderer.setShouldRegenerateClouds(regenerateClouds); - - // Mark the shadow graph as needing update before terrain setup - // Modern Celeritas does this to ensure the shadow render lists get populated - com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer.getInstance() - .getRenderSectionManager().markShadowGraphDirty(); + // Save the main camera viewport before shadow pass overwrites it. + // clipRenderersByFrustum -> setupTerrain sets currentViewport to the shadow frustum. + // If the shadow pass throws or the main setupTerrain doesn't run after us, the shadow + // viewport would persist and corrupt entity culling in the main pass. + final Viewport savedViewport = CeleritasWorldRenderer.getInstance().getCurrentViewport(); + // Pair setupGlState / restoreGlState with try-finally so any throw between them + // (translucent terrain, entity rendering, mipmaps, etc.) still unwinds the + // projection push and the shadow framebuffer binding. Without this, a single + // mid-pass throw strands shadow GL state into the next frame's vanilla rendering. + boolean setupGlStateRan = false; + try { // Execute the vanilla terrain setup / culling routines using our shadow frustum. mc.renderGlobal.clipRenderersByFrustum(terrainFrustumHolder.getFrustum(), playerCamera.getPartialTicks()); @@ -702,57 +914,42 @@ public class ShadowRenderer { // chunks during traversal, and break rendering in concerning ways. // levelRenderer.setFrameId(levelRenderer.getFrameId() + 1); - profiler.endStartSection("terrain"); - setupGlState(PROJECTION); - - // Render all opaque terrain unless pack requests not to - if (shouldRenderTerrain) { - mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); - rg.sortAndRender(mc.renderViewEntity, 0, playerCamera.getPartialTicks()); - } - - // Reset viewport in case terrain rendering changed it - GLStateManager.glViewport(0, 0, resolution, resolution); - - profiler.endStartSection("entities"); + setupGlStateRan = true; // Get the current tick delta. Normally this is the same as client.getTickDelta(), but when the game is paused, // it is set to a fixed value. final float tickDelta = CapturedRenderingState.INSTANCE.getTickDelta(); - // Create a constrained shadow frustum for entities to avoid rendering faraway entities in the shadow pass, - // if the shader pack has requested it. Otherwise, use the same frustum as for terrain. - boolean hasEntityFrustum = false; - - if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) { - entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo()); + profiler.endStartSection("iris_shadow_terrain"); + if (relayTerrain) { + try (GLDebug.Scope s = GLDebug.scope("shadow:terrain")) { + renderSolidShadowTerrain(mc, rg, playerCamera); + } + if (deferActive) { + targets.captureTerrainSnapshot(); + lastRelayNanos = frameNanos; + } } else { - hasEntityFrustum = true; - entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder); + try (GLDebug.Scope s = GLDebug.scope("shadow:terrain_restore")) { + targets.restoreTerrainSnapshot(); + } } - Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum(); - entityShadowFrustum.setPosition(entityX, entityY, entityZ); - - // Set viewport for entity visibility checks during shadow pass (matches modern Celeritas) - if (AngelicaConfig.enableCeleritas) { - CeleritasWorldRenderer.getInstance().setCurrentViewport(((ViewportProvider)entityShadowFrustum).sodium$createViewport()); - } - - // Render nearby entities - - if (shouldRenderEntities) { - renderEntities(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta); - } else if (shouldRenderPlayer) { - renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta); + profiler.endStartSection("iris_shadow_entities"); + final Frustrum entityShadowFrustum = createEntityShadowFrustum(entityX, entityY, entityZ); + applyEntityShadowViewport(entityShadowFrustum); + try (GLDebug.Scope s = GLDebug.scope("shadow:entities")) { + renderShadowEntitiesAndPlayer(levelRenderer, entityShadowFrustum, modelView, entityX, entityY, entityZ, tickDelta); } if (shouldRenderBlockEntities) { - renderTileEntities(null, modelView, entityX, entityY, entityZ, tickDelta, hasEntityFrustum); + try (GLDebug.Scope s = GLDebug.scope("shadow:block_entities")) { + renderTileEntities(null, modelView, entityX, entityY, entityZ, tickDelta, entityFrustumConstrained); + } } - profiler.endStartSection("draw entities"); + profiler.endStartSection("iris_shadow_draw_entities"); // NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some // shader packs assume that everything drawn afterwards is actually translucent and should cast a colored @@ -760,13 +957,15 @@ public class ShadowRenderer { copyPreTranslucentDepth(); - profiler.endStartSection("translucent terrain"); + profiler.endStartSection("iris_shadow_translucent_terrain"); // TODO (Iris): Prevent these calls from scheduling translucent sorting... // It doesn't matter a ton, since this just means that they won't be sorted in the getNormal rendering pass. // Just something to watch out for, however... if (shouldRenderTranslucent) { - rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks()); + try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) { + rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks()); + } } // Note: Apparently tripwire isn't rendered in the shadow pass. @@ -776,26 +975,32 @@ public class ShadowRenderer { // renderBuffersExt.endLevelRendering(); // } - profiler.endStartSection("generate mipmaps"); + profiler.endStartSection("iris_shadow_generate_mipmaps"); generateMipmaps(); - profiler.endStartSection("restore gl state"); - - restoreGlState(); + profiler.endStartSection("iris_shadow_restore_gl_state"); + } finally { + if (setupGlStateRan) { + restoreGlState(); + } + if (savedViewport != null) { + CeleritasWorldRenderer.getInstance().setCurrentViewport(savedViewport); + } + } if (levelRenderer instanceof CullingDataCache) { ((CullingDataCache) levelRenderer).restoreState(); } - profiler.endStartSection("shadowcomp"); + profiler.endStartSection("iris_shadowcomp"); if (compositeRenderer != null) compositeRenderer.renderAll(); ACTIVE = false; CURRENT_TARGETS = null; profiler.endSection(); - profiler.endStartSection("updatechunks"); + profiler.endStartSection("culling"); } public void addDebugText(List messages) { diff --git a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java index 7f1ac6f53..a1940e01c 100644 --- a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java @@ -8,7 +8,7 @@ import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; import net.coderbot.iris.celeritas.CeleritasTerrainPipeline; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.shaderpack.CloudSetting; import net.coderbot.iris.shaderpack.texture.TextureStage; @@ -21,6 +21,7 @@ import java.util.OptionalInt; public interface WorldRenderingPipeline { void beginLevelRendering(); void renderShadows(EntityRenderer levelRenderer, Camera camera); + default void preSubmitShadowGraph(int frame, boolean spectator) {} void addDebugText(List messages); OptionalInt getForcedShadowRenderDistanceChunksForDisplay(); @@ -37,6 +38,11 @@ public interface WorldRenderingPipeline { void onBindTexture(int id); + /** Re-bind the program/framebuffer for the currently-active Pass, if any. */ + void rebindCurrentPass(); + + default void onEntityRenderBoundary() {} + void beginHand(); void beginTranslucents(); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java index aa06e0532..ae2b2aa8e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -1,8 +1,9 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLParser; import java.util.HashMap; @@ -29,18 +30,32 @@ class AttributeTransformer { } private static void transformCore(Transformer transformer, AttributeParameters parameters) { - CoreTransformHelper.injectMatrixUniforms(transformer); + final boolean instancedVertex = parameters.instanced && parameters.type == ShaderType.VERTEX; + final boolean wantsMvInverse = instancedVertex && transformer.containsCall("gl_ModelViewMatrixInverse"); + CoreTransformHelper.injectMatrixUniforms(transformer, instancedVertex); + + aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix"); + aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix"); + aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix"); if (parameters.type == ShaderType.VERTEX) { transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); transformer.injectVariable("layout(location = 1) in vec4 iris_Color;"); transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;"); - transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;"); + if (instancedVertex) { + transformer.injectVariable("vec4 iris_MultiTexCoord1;"); + } else { + transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;"); + } transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); transformer.rename("gl_Vertex", "iris_Vertex"); - transformer.replaceExpression("gl_Color", "(iris_Color * iris_ColorModulator)"); + transformer.replaceExpression("gl_Color", instancedVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)"); transformer.rename("gl_Normal", "iris_Normal"); + aliasIfUsed(transformer, "vaNormal", "iris_Normal"); + if (transformer.containsCall("vaPosition") && !transformer.hasVariable("vaPosition")) { + transformer.replaceExpression("vaPosition", "iris_Vertex.xyz"); + } // ftransform() = gl_ModelViewProjectionMatrix * gl_Vertex transformer.renameFunctionCall("ftransform", "iris_ftransform"); @@ -69,7 +84,42 @@ class AttributeTransformer { transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord"); transformer.injectVariable("in vec4 mc_midTexCoord;"); } + + if (instancedVertex) { + foldConstantAttribute(transformer, "mc_Entity", "-1.0", "vec2(-1.0, -1.0)", "vec3(-1.0, -1.0, 0.0)", "vec4(-1.0, -1.0, 0.0, 1.0)"); + foldConstantAttribute(transformer, "mc_midTexCoord", "0.5", "vec2(0.5, 0.5)", "vec3(0.5, 0.5, 0.0)", "vec4(0.5, 0.5, 0.0, 1.0)"); + + final StringBuilder init = new StringBuilder(256); + init.append("{ iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3);"); + init.append(" iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz));"); + if (wantsMvInverse) { + init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);"); + } + init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0); }"); + transformer.prependMain(init.toString()); + } } } + private static void foldConstantAttribute(Transformer transformer, String name, String floatVal, String vec2Val, String vec3Val, String vec4Val) { + final int type = transformer.findType(name); + if (type == 0) { + return; + } + final String replacement = switch (type) { + case GLSLLexer.FLOAT -> floatVal; + case GLSLLexer.VEC2 -> vec2Val; + case GLSLLexer.VEC3 -> vec3Val; + case GLSLLexer.VEC4 -> vec4Val; + default -> throw new IllegalStateException("Unsupported " + name + " type token " + type + " for instanced variant"); + }; + transformer.removeVariable(name); + transformer.replaceExpression(name, replacement); + } + + private static void aliasIfUsed(Transformer transformer, String modernName, String irisName) { + if (transformer.containsCall(modernName) && !transformer.hasVariable(modernName)) { + transformer.rename(modernName, irisName); + } + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java index 8c5783297..3e13098c2 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java @@ -67,5 +67,7 @@ class CeleritasTransformer { private static void transformShared(Transformer transformer, Parameters parameters) { transformer.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0)"); CoreTransformHelper.injectMatrixUniforms(transformer); + // Celeritas terrain: texture matrix is always identity, replace uniform with constant + transformer.replaceExpression("iris_TextureMatrix", "mat4(1.0)"); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java index ded7984fe..1606af637 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java @@ -1,7 +1,7 @@ package net.coderbot.iris.pipeline.transform; import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLParser; @@ -135,7 +135,12 @@ public class CommonTransformer { + "gl_ClipDistance[4] = dot(angelica_ClipPlane[4], _cp_ep); " + "gl_ClipDistance[5] = dot(angelica_ClipPlane[5], _cp_ep); " + "gl_ClipDistance[6] = dot(angelica_ClipPlane[6], _cp_ep); " - + "gl_ClipDistance[7] = dot(angelica_ClipPlane[7], _cp_ep); } }" + + "gl_ClipDistance[7] = dot(angelica_ClipPlane[7], _cp_ep); " + + "} else { " + + "gl_ClipDistance[0] = 0.0; gl_ClipDistance[1] = 0.0; " + + "gl_ClipDistance[2] = 0.0; gl_ClipDistance[3] = 0.0; " + + "gl_ClipDistance[4] = 0.0; gl_ClipDistance[5] = 0.0; " + + "gl_ClipDistance[6] = 0.0; gl_ClipDistance[7] = 0.0; } }" ); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java index ccf461775..86f756f03 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.antlr.v4.runtime.tree.ParseTree; import org.taumc.glsl.ShaderPrinter; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java index 933a49098..6e37a5c48 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java index d0d7083e9..1e9b52015 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java @@ -15,11 +15,27 @@ class CoreTransformHelper { * Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix. */ static void injectMatrixUniforms(Transformer transformer) { - transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); - transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + injectMatrixUniforms(transformer, false); + } + + static void injectMatrixUniforms(Transformer transformer, boolean instancedVertex) { + if (instancedVertex) { + transformer.injectVariable("layout(location = 7) in vec4 iris_InstMat0;"); + transformer.injectVariable("layout(location = 8) in vec4 iris_InstMat1;"); + transformer.injectVariable("layout(location = 9) in vec4 iris_InstMat2;"); + transformer.injectVariable("layout(location = 10) in vec4 iris_InstMat3;"); + transformer.injectVariable("layout(location = 11) in vec4 iris_InstColor;"); + transformer.injectVariable("layout(location = 12) in vec2 iris_InstLightmap;"); + transformer.injectVariable("mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("mat3 iris_NormalMatrix;"); + } else { + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + } transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;"); transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;"); - transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;"); transformer.injectVariable("uniform mat4 iris_TextureMatrix;"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java index 99f928ecf..0af74a260 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; @@ -70,12 +70,12 @@ public class DHGenericTransformer { addIfNotExists(transformer, "uCameraPosSubChunk", "uniform vec3 uCameraPosSubChunk;"); addIfNotExists(transformer, "uSkyLight", "uniform int uSkyLight;"); addIfNotExists(transformer, "uBlockLight", "uniform int uBlockLight;"); - addIfNotExists(transformer, "iris_color", "in vec4 iris_color;"); - addIfNotExists(transformer, "aScale", "in vec3 aScale;"); - addIfNotExists(transformer, "aTranslateChunk", "in ivec3 aTranslateChunk;"); - addIfNotExists(transformer, "aTranslateSubChunk", "in vec3 aTranslateSubChunk;"); - addIfNotExists(transformer, "aMaterial", "in int aMaterial;"); - addIfNotExists(transformer, "vPosition", "in vec3 vPosition;"); + addIfNotExists(transformer, "iris_color", DH_GENERIC_LOC_COLOR, "in vec4 iris_color;"); + addIfNotExists(transformer, "aScale", DH_GENERIC_LOC_SCALE, "in vec3 aScale;"); + addIfNotExists(transformer, "aTranslateChunk", DH_GENERIC_LOC_TRANSLATE_CHUNK, "in ivec3 aTranslateChunk;"); + addIfNotExists(transformer, "aTranslateSubChunk", DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK, "in vec3 aTranslateSubChunk;"); + addIfNotExists(transformer, "aMaterial", DH_GENERIC_LOC_MATERIAL, "in int aMaterial;"); + addIfNotExists(transformer, "vPosition", DH_GENERIC_LOC_POSITION, "in vec3 vPosition;"); transformer.injectFunction("const vec3 irisNormals[6] = vec3[](vec3(0,0,-1), vec3(0,0,1), vec3(-1,0,0), vec3(1,0,0), vec3(0,-1,0), vec3(0,1,0));"); transformer.injectFunction( @@ -100,12 +100,23 @@ public class DHGenericTransformer { transformer.prependMain("_vert_init();"); } + public static final int DH_GENERIC_LOC_POSITION = 0; + public static final int DH_GENERIC_LOC_COLOR = 1; + public static final int DH_GENERIC_LOC_SCALE = 2; + public static final int DH_GENERIC_LOC_TRANSLATE_CHUNK = 3; + public static final int DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK = 4; + public static final int DH_GENERIC_LOC_MATERIAL = 5; + private static void addIfNotExists(Transformer transformer, String name, String code) { if (!transformer.hasVariable(name)) { transformer.injectVariable(code); } } + private static void addIfNotExists(Transformer transformer, String name, int location, String code) { + addIfNotExists(transformer, name, "layout (location = " + location + ") " + code); + } + private static void replaceGlMultiTexCoordBounded(Transformer transformer, int from, int to) { for (int i = from; i <= to; i++) { transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java index 14e75fa61..3820a36cf 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/GlslAstHelpers.java b/src/main/java/net/coderbot/iris/pipeline/transform/GlslAstHelpers.java new file mode 100644 index 000000000..b4a2b8099 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/GlslAstHelpers.java @@ -0,0 +1,116 @@ +package net.coderbot.iris.pipeline.transform; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.tree.ParseTree; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.ArrayList; +import java.util.List; + +final class GlslAstHelpers { + + private GlslAstHelpers() {} + + @SuppressWarnings("unchecked") + static List collectAll(ParseTree root, Class klass) { + final List out = new ArrayList<>(); + walk(root, klass, out); + return out; + } + + @SuppressWarnings("unchecked") + static void walk(ParseTree node, Class klass, List out) { + if (klass.isInstance(node)) out.add((T) node); + for (int i = 0, n = node.getChildCount(); i < n; i++) { + walk(node.getChild(i), klass, out); + } + } + + @SuppressWarnings("unchecked") + static T enclosingOfType(ParseTree node, Class type) { + ParseTree cur = node; + while (cur != null && !type.isInstance(cur)) cur = cur.getParent(); + return (T) cur; + } + + static void collectInto(ParseTree root, List[] sinks, Class[] types) { + if (types.length != sinks.length) throw new IllegalArgumentException(); + collectIntoWalk(root, sinks, types); + } + + @SuppressWarnings("unchecked") + private static void collectIntoWalk(ParseTree node, List[] sinks, Class[] types) { + for (int i = 0; i < types.length; i++) { + if (types[i].isInstance(node)) ((List) sinks[i]).add(node); + } + for (int i = 0, n = node.getChildCount(); i < n; i++) collectIntoWalk(node.getChild(i), sinks, types); + } + + static String extractCallName(GLSLParser.Postfix_expressionContext expr) { + if (expr.function_call_parameters() == null) return null; + if (expr.postfix_expression() == null) { + return expr.type_specifier() != null ? expr.type_specifier().getText() : null; + } + final GLSLParser.Postfix_expressionContext inner = expr.postfix_expression(); + if (inner.primary_expression() == null) return null; + if (inner.primary_expression().variable_identifier() == null) return null; + return inner.primary_expression().variable_identifier().getText(); + } + + static String firstArgIdentifier(GLSLParser.Postfix_expressionContext expr) { + final List args = argsOf(expr); + if (args.isEmpty()) return ""; + return args.get(0).getText(); + } + + static String secondArgText(GLSLParser.Postfix_expressionContext expr) { + final List args = argsOf(expr); + if (args.size() < 2) return null; + return args.get(1).getText(); + } + + static List argsOf(GLSLParser.Postfix_expressionContext expr) { + final GLSLParser.Function_call_parametersContext params = expr.function_call_parameters(); + if (params == null) return List.of(); + return params.assignment_expression(); + } + + static void replaceNode(ParseTree oldNode, ParseTree newNode) { + if (!(oldNode instanceof ParserRuleContext oldCtx)) return; + if (!(newNode instanceof ParserRuleContext newCtx)) return; + if (!(oldCtx.parent instanceof ParserRuleContext parentCtx)) return; + final int idx = parentCtx.children.indexOf(oldCtx); + if (idx < 0) return; + newCtx.parent = parentCtx; + parentCtx.children.set(idx, newCtx); + } + + static boolean deleteStatementContaining(ParseTree expr) { + final GLSLParser.StatementContext stmt = enclosingOfType(expr, GLSLParser.StatementContext.class); + if (stmt == null) return false; + if (!(stmt.parent instanceof ParserRuleContext parent) || parent.children == null) return false; + final var empty = ShaderParser.parseSnippet(";", GLSLParser::statement); + if (empty == null) return parent.children.remove(stmt); + final int idx = parent.children.indexOf(stmt); + if (idx < 0) return false; + empty.parent = parent; + parent.children.set(idx, empty); + return true; + } + + static String zeroLiteralFor(String imageGlslType) { + return switch (componentTypeFor(imageGlslType)) { + case "ivec4" -> "ivec4(0)"; + case "uvec4" -> "uvec4(0u)"; + default -> "vec4(0.0)"; + }; + } + + static String componentTypeFor(String imageGlslType) { + if (imageGlslType == null) return "vec4"; + if (imageGlslType.startsWith("iimage")) return "ivec4"; + if (imageGlslType.startsWith("uimage")) return "uvec4"; + return "vec4"; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformer.java new file mode 100644 index 000000000..9d7420ed4 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformer.java @@ -0,0 +1,95 @@ +package net.coderbot.iris.pipeline.transform; + +import org.antlr.v4.runtime.tree.TerminalNode; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.Map; + +final class LocalZeroInitTransformer { + + private LocalZeroInitTransformer() {} + + static void transformGrouped(Map trees) { + for (Transformer t : trees.values()) { + if (t != null) transform(t); + } + } + + static void transform(Transformer transformer) { + transformer.mutateTree(tree -> { + for (GLSLParser.Declaration_statementContext stmt : + GlslAstHelpers.collectAll(tree, GLSLParser.Declaration_statementContext.class)) { + initializeStatement(stmt); + } + }); + } + + private static void initializeStatement(GLSLParser.Declaration_statementContext stmt) { + final GLSLParser.DeclarationContext declaration = stmt.declaration(); + if (declaration == null) return; + final GLSLParser.Init_declarator_listContext list = declaration.init_declarator_list(); + if (list == null) return; + final GLSLParser.Single_declarationContext single = list.single_declaration(); + if (single == null) return; + + final GLSLParser.Fully_specified_typeContext type = single.fully_specified_type(); + if (type == null || type.type_qualifier() != null) return; + final GLSLParser.Type_specifierContext specifier = type.type_specifier(); + if (specifier == null || specifier.array_specifier() != null) return; + + final String zero = zeroInitializerFor(specifier.type_specifier_nonarray()); + if (zero == null) return; + + initializeDeclarator(single.typeless_declaration(), zero); + for (GLSLParser.Typeless_declarationContext declarator : list.typeless_declaration()) { + initializeDeclarator(declarator, zero); + } + } + + private static void initializeDeclarator(GLSLParser.Typeless_declarationContext declarator, String zero) { + if (declarator == null) return; + if (declarator.initializer() != null || declarator.array_specifier() != null) return; + final TerminalNode name = declarator.IDENTIFIER(); + if (name == null) return; + + final GLSLParser.Typeless_declarationContext replacement = + ShaderParser.parseSnippet(name.getText() + " = " + zero, GLSLParser::typeless_declaration); + if (replacement != null) GlslAstHelpers.replaceNode(declarator, replacement); + } + + private static String zeroInitializerFor(GLSLParser.Type_specifier_nonarrayContext specifier) { + if (specifier == null || specifier.getChildCount() != 1) return null; + if (!(specifier.getChild(0) instanceof TerminalNode token)) return null; + final String type = switch (token.getSymbol().getType()) { + case GLSLLexer.FLOAT -> "float"; + case GLSLLexer.INT -> "int"; + case GLSLLexer.UINT -> "uint"; + case GLSLLexer.VEC2 -> "vec2"; + case GLSLLexer.VEC3 -> "vec3"; + case GLSLLexer.VEC4 -> "vec4"; + case GLSLLexer.IVEC2 -> "ivec2"; + case GLSLLexer.IVEC3 -> "ivec3"; + case GLSLLexer.IVEC4 -> "ivec4"; + case GLSLLexer.UVEC2 -> "uvec2"; + case GLSLLexer.UVEC3 -> "uvec3"; + case GLSLLexer.UVEC4 -> "uvec4"; + case GLSLLexer.MAT2 -> "mat2"; + case GLSLLexer.MAT3 -> "mat3"; + case GLSLLexer.MAT4 -> "mat4"; + case GLSLLexer.MAT2X2 -> "mat2x2"; + case GLSLLexer.MAT2X3 -> "mat2x3"; + case GLSLLexer.MAT2X4 -> "mat2x4"; + case GLSLLexer.MAT3X2 -> "mat3x2"; + case GLSLLexer.MAT3X3 -> "mat3x3"; + case GLSLLexer.MAT3X4 -> "mat3x4"; + case GLSLLexer.MAT4X2 -> "mat4x2"; + case GLSLLexer.MAT4X3 -> "mat4x3"; + case GLSLLexer.MAT4X4 -> "mat4x4"; + default -> null; + }; + return type == null ? null : type + "(0)"; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java b/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java index e2af97691..14d53a66a 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; public enum PatchShaderType { VERTEX(ShaderType.VERTEX), diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/PreRasterComputeDispatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/PreRasterComputeDispatcher.java new file mode 100644 index 000000000..551bc0419 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/PreRasterComputeDispatcher.java @@ -0,0 +1,39 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import net.coderbot.iris.gl.program.ComputeProgram; +import net.coderbot.iris.uniforms.custom.CustomUniforms; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL42; + +public final class PreRasterComputeDispatcher { + public static final int LOC_UNRESOLVED = -2; + + private PreRasterComputeDispatcher() {} + + public static int dispatch(ComputeProgram compute, RwImageStoreExtractor.RwExtractMode mode, int cachedTargetSizeLoc, int width, int height, CustomUniforms uniforms) { + final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); + compute.use(); + uniforms.push(compute); + int targetSizeLoc = cachedTargetSizeLoc; + if (mode == RwImageStoreExtractor.RwExtractMode.COMPOSITE_FSH) { + if (targetSizeLoc == LOC_UNRESOLVED) { + targetSizeLoc = GLStateManager.glGetUniformLocation(compute.getProgramId(), "_vg_target_size"); + } + if (targetSizeLoc >= 0) { + GLStateManager.glUniform2i(targetSizeLoc, width, height); + } + } + final int gx, gy, gz; + switch (mode) { + case COMPOSITE_VSH -> { gx = 1; gy = 1; gz = 1; } + case COMPOSITE_FSH -> { gx = (width + 7) / 8; gy = (height + 7) / 8; gz = 1; } + default -> { gx = 1; gy = 1; gz = 1; } + } + GLStateManager.glDispatchCompute(gx, gy, gz); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); + if (prevProgram != 0) GLStateManager.glUseProgram(prevProgram); + return targetSizeLoc; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractor.java b/src/main/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractor.java new file mode 100644 index 000000000..d4333f485 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractor.java @@ -0,0 +1,804 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import net.coderbot.iris.gl.image.ImageInformation; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import org.antlr.v4.runtime.CommonToken; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.HashSet; +import java.util.Set; + +public final class RwImageStoreExtractor { + + public enum RwExtractMode { CHUNK, COMPOSITE_VSH, COMPOSITE_FSH } + + public static RwExtractMode parseSentinel(String computeSource) { + if (computeSource == null) return null; + if (computeSource.startsWith("// _vg_mode: chunk")) return RwExtractMode.CHUNK; + if (computeSource.startsWith("// _vg_mode: composite-vsh")) return RwExtractMode.COMPOSITE_VSH; + if (computeSource.startsWith("// _vg_mode: composite-fsh")) return RwExtractMode.COMPOSITE_FSH; + return null; + } + + public record AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr, boolean liveBranch) { + public AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr) { + this(name, glslType, byteOffset, unpackExpr, true); + } + } + + public record Result(String strippedSource, String computeSource, Set writtenImages, RwExtractMode mode) {} + + public record ImageDecl(String name, String glslType, String layoutFormat) {} + + public static class UnknownAttributeException extends RuntimeException { + public UnknownAttributeException(String msg) { super(msg); } + } + + private RwImageStoreExtractor() {} + + public static final int VG_VBUF_SSBO_BINDING = 9; + private static final int STRIDE_BYTES = 48; + private static final int STRIDE_UINTS = STRIDE_BYTES / 4; + + private static volatile Map activeCustomImages = Map.of(); + + public static void setActiveCustomImages(Map images) { + activeCustomImages = (images == null) ? Map.of() : Map.copyOf(images); + } + + private static final Set RW_CALLS = Set.of( + "imageStore", + "imageAtomicAdd", "imageAtomicAnd", "imageAtomicOr", "imageAtomicXor", + "imageAtomicMin", "imageAtomicMax", "imageAtomicExchange", "imageAtomicCompSwap" + ); + + public static Result tryExtract(String source, PatchShaderType stage, String programName) { + if (source == null) return null; + if (stage != PatchShaderType.VERTEX && stage != PatchShaderType.FRAGMENT) return null; + + final ShaderParser.ParsedShader parsed = ShaderParser.parseShader(source); + final GLSLParser.Translation_unitContext root = parsed.full(); + + final List decls = new ArrayList<>(); + final List exprs = new ArrayList<>(); + GlslAstHelpers.collectInto(root, + new List[] { decls, exprs }, + new Class[] { GLSLParser.Single_declarationContext.class, GLSLParser.Postfix_expressionContext.class }); + + final Map declared = collectImageDecls(decls); + final Set writtenImages = new LinkedHashSet<>(); + final Set nonWriteonlyImages = new LinkedHashSet<>(); + classifyImageCalls(exprs, declared, writtenImages, nonWriteonlyImages); + if (writtenImages.isEmpty()) return null; + + final Map chunkAttrAstTypes = (stage == PatchShaderType.VERTEX) ? collectChunkAttrAstTypes(decls) : Map.of(); + final Set chunkAttrsUsed = (stage == PatchShaderType.VERTEX) ? collectChunkAttrsUsed(decls, root, source) : Set.of(); + + final RwExtractMode mode = (stage == PatchShaderType.VERTEX) ? (chunkAttrsUsed.isEmpty() ? RwExtractMode.COMPOSITE_VSH : RwExtractMode.CHUNK) : RwExtractMode.COMPOSITE_FSH; + + final List attrs = (mode == RwExtractMode.CHUNK) ? collectVertexAttributes(chunkAttrsUsed, chunkAttrAstTypes) : List.of(); + + final String stripped = buildRasterOutputViaSourceSlicing(source, decls, exprs, writtenImages, declared, mode); + + final Transformer tc = new Transformer(root); + applyComputeMutations(tc, writtenImages, declared, chunkAttrsUsed, mode, nonWriteonlyImages); + final String compute = buildComputeOutput(root, mode, writtenImages, nonWriteonlyImages, declared, attrs); + + return new Result(stripped, compute, writtenImages, mode); + } + + private static Map collectImageDecls(List decls) { + final LinkedHashMap out = new LinkedHashMap<>(); + for (var decl : decls) { + final var ts = decl.fully_specified_type(); + if (ts == null || ts.type_specifier() == null || ts.type_specifier().type_specifier_nonarray() == null) continue; + final var nonArray = ts.type_specifier().type_specifier_nonarray(); + if (nonArray.getChildCount() == 0) continue; + final var first = nonArray.getChild(0); + if (!(first instanceof TerminalNode tn)) continue; + final int tokenType = tn.getSymbol().getType(); + if (!isImageToken(tokenType)) continue; + final var typeless = decl.typeless_declaration(); + if (typeless == null || typeless.IDENTIFIER() == null) continue; + final String name = typeless.IDENTIFIER().getText(); + final String glslType = tn.getText(); + final String layoutFormat = extractLayoutFormat(ts); + out.putIfAbsent(name, new ImageDecl(name, glslType, layoutFormat)); + } + return out; + } + + private static String extractLayoutFormat(GLSLParser.Fully_specified_typeContext fst) { + if (fst.type_qualifier() == null) return null; + for (var sq : fst.type_qualifier().single_type_qualifier()) { + final var lq = sq.layout_qualifier(); + if (lq == null || lq.layout_qualifier_id_list() == null) continue; + for (var id : lq.layout_qualifier_id_list().layout_qualifier_id()) { + if (id.IDENTIFIER() == null) continue; + final String text = id.IDENTIFIER().getText(); + if (isImageFormat(text)) return text; + } + } + return null; + } + + private static boolean isImageFormat(String s) { + return s.startsWith("rgba") || s.startsWith("rgb") || s.startsWith("rg") + || s.startsWith("r32") || s.startsWith("r16") || s.startsWith("r8") + || s.startsWith("r11f") || s.startsWith("r10"); + } + + private static boolean isImageToken(int t) { + return t == GLSLLexer.IMAGE1D || t == GLSLLexer.IMAGE2D || t == GLSLLexer.IMAGE3D + || t == GLSLLexer.IIMAGE1D || t == GLSLLexer.IIMAGE2D || t == GLSLLexer.IIMAGE3D + || t == GLSLLexer.UIMAGE1D || t == GLSLLexer.UIMAGE2D || t == GLSLLexer.UIMAGE3D; + } + + private static void classifyImageCalls(List exprs, Map declared, Set writtenImages, Set nonWriteonlyImages) { + for (var expr : exprs) { + final String fname = GlslAstHelpers.extractCallName(expr); + if (fname == null) continue; + final String firstArg = GlslAstHelpers.firstArgIdentifier(expr); + if (firstArg.isEmpty() || !declared.containsKey(firstArg)) continue; + if (RW_CALLS.contains(fname)) { + writtenImages.add(firstArg); + if (!"imageStore".equals(fname)) { + nonWriteonlyImages.add(firstArg); + } + } else if ("imageLoad".equals(fname)) { + nonWriteonlyImages.add(firstArg); + } + } + } + + private static Set collectChunkAttrsUsed(List decls, GLSLParser.Translation_unitContext root, String source) { + final LinkedHashSet out = new LinkedHashSet<>(); + for (var decl : decls) { + if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue; + final String name = decl.typeless_declaration().IDENTIFIER().getText(); + if (CHUNK_VERTEX_ATTRS.containsKey(name)) out.add(name); + } + for (var ref : GlslAstHelpers.collectAll(root, GLSLParser.Variable_identifierContext.class)) { + if (ref.IDENTIFIER() == null) continue; + final String name = ref.IDENTIFIER().getText(); + if (CHUNK_VERTEX_ATTRS.containsKey(name)) out.add(name); + } + for (String attr : CHUNK_VERTEX_ATTRS.keySet()) { + if (containsAsToken(source, attr)) out.add(attr); + } + return out; + } + + private static boolean containsAsToken(String text, String name) { + int from = 0; + while (true) { + final int idx = text.indexOf(name, from); + if (idx < 0) return false; + final boolean beforeOk = idx == 0 || !isIdentChar(text.charAt(idx - 1)); + final int end = idx + name.length(); + final boolean afterOk = end >= text.length() || !isIdentChar(text.charAt(end)); + if (beforeOk && afterOk) return true; + from = idx + 1; + } + } + + private static boolean isIdentChar(char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; + } + + + private record SourceEdit(int start, int stop, String replacement) {} + + private static String buildRasterOutputViaSourceSlicing(String source, List decls, List exprs, Set writtenImages, Map declared, RwExtractMode mode) { + final List edits = new ArrayList<>(); + + for (var decl : decls) { + if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue; + final String name = decl.typeless_declaration().IDENTIFIER().getText(); + if (!writtenImages.contains(name)) continue; + final var ext = GlslAstHelpers.enclosingOfType(decl, GLSLParser.External_declarationContext.class); + if (ext == null) continue; + edits.add(rangeOf(ext)); + } + + for (var expr : exprs) { + final String fname = GlslAstHelpers.extractCallName(expr); + if (fname == null) continue; + final String firstArg = GlslAstHelpers.firstArgIdentifier(expr); + if (!writtenImages.contains(firstArg)) continue; + if (RW_CALLS.contains(fname)) { + final var stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class); + if (stmt != null) edits.add(replaceOf(stmt, ";")); + } else if ("imageLoad".equals(fname)) { + final ImageDecl d = declared.get(firstArg); + if (d == null) continue; + edits.add(replaceOf(expr, GlslAstHelpers.zeroLiteralFor(d.glslType()))); + } + } + + return applyEdits(source, edits); + } + + private static SourceEdit rangeOf(ParserRuleContext ctx) { + return new SourceEdit(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex() + 1, ""); + } + + private static SourceEdit replaceOf(ParserRuleContext ctx, String text) { + return new SourceEdit(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex() + 1, text); + } + + private static String applyEdits(String source, List edits) { + if (edits.isEmpty()) return source; + edits.sort(Comparator.comparingInt(SourceEdit::start)); + final StringBuilder out = new StringBuilder(source.length()); + int cursor = 0; + for (SourceEdit e : edits) { + if (e.start() < cursor) continue; + out.append(source, cursor, e.start()); + out.append(e.replacement()); + cursor = e.stop(); + } + if (cursor < source.length()) out.append(source, cursor, source.length()); + return out.toString(); + } + + private static void applyComputeMutations(Transformer tc, Set writtenImages, Map declared, Set chunkAttrsUsed, RwExtractMode mode, Set nonWriteonlyImages) { + hoistNonConstGlobalInitializers(tc); + renameMainToVgBody(tc); + rewriteImageAtomicsToNonAtomic(tc, declared, writtenImages, nonWriteonlyImages); + for (String name : writtenImages) tc.removeVariable(name); + if (mode == RwExtractMode.CHUNK) { + for (String name : chunkAttrsUsed) tc.removeVariable(name); + stripStorageQualifiers(tc, Set.of("out", "varying")); + } else if (mode == RwExtractMode.COMPOSITE_VSH) { + tc.renameFunctionCall("ftransform", "iris_ftransform"); + stripStorageQualifiers(tc, Set.of("in", "attribute", "out", "varying")); + } else if (mode == RwExtractMode.COMPOSITE_FSH) { + stripFragOutputs(tc); + stripStorageQualifiers(tc, Set.of("in", "varying")); + } + stripInterfaceOnlyQualifiers(tc); + } + + private static final Set ATOMIC_CALLS = Set.of( + "imageAtomicAdd", "imageAtomicAnd", "imageAtomicOr", "imageAtomicXor", + "imageAtomicMin", "imageAtomicMax", "imageAtomicExchange", "imageAtomicCompSwap" + ); + + private static void rewriteImageAtomicsToNonAtomic(Transformer tc, Map declared, Set writtenImages, Set nonWriteonlyImages) { + tc.mutateTree(tree -> { + for (var expr : GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class)) { + final String fname = GlslAstHelpers.extractCallName(expr); + if (fname == null || !ATOMIC_CALLS.contains(fname)) continue; + final String imgName = GlslAstHelpers.firstArgIdentifier(expr); + if (!writtenImages.contains(imgName)) continue; + final ImageDecl decl = declared.get(imgName); + if (decl == null) continue; + if (!isCallTopLevelStatement(expr)) continue; + final String inlined = buildInlineAtomicEmulation(fname, imgName, GlslAstHelpers.argsOf(expr), decl); + if (inlined == null) continue; + final var replacement = ShaderParser.parseSnippet(inlined, GLSLParser::statement); + if (replacement == null) continue; + if (replaceEnclosingStatement(expr, replacement)) { + nonWriteonlyImages.add(imgName); + } + } + }); + } + + private static boolean isCallTopLevelStatement(GLSLParser.Postfix_expressionContext expr) { + final GLSLParser.StatementContext stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class); + if (stmt == null) return false; + return stmt.getText().equals(expr.getText() + ";"); + } + + private static boolean replaceEnclosingStatement(ParseTree expr, ParserRuleContext replacement) { + final GLSLParser.StatementContext stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class); + if (stmt == null) return false; + if (!(stmt.parent instanceof ParserRuleContext parent) || parent.children == null) return false; + final int idx = parent.children.indexOf(stmt); + if (idx < 0) return false; + replacement.parent = parent; + parent.children.set(idx, replacement); + return true; + } + + private static String buildInlineAtomicEmulation(String op, String imgName, List args, ImageDecl decl) { + if (args.size() < 2) return null; + final String idx = args.get(1).getText(); + final String glslType = decl.glslType(); + final String scalar = scalarFor(glslType); + final String vec = componentVecFor(glslType); + final String vecArgs = vecArgsFor(vec); + final String compute; + switch (op) { + case "imageAtomicAdd" -> { + if (args.size() < 3) return null; + compute = "_vg_prev + " + args.get(2).getText(); + } + case "imageAtomicAnd" -> { + if (args.size() < 3) return null; + compute = "_vg_prev & " + args.get(2).getText(); + } + case "imageAtomicOr" -> { + if (args.size() < 3) return null; + compute = "_vg_prev | " + args.get(2).getText(); + } + case "imageAtomicXor" -> { + if (args.size() < 3) return null; + compute = "_vg_prev ^ " + args.get(2).getText(); + } + case "imageAtomicMin" -> { + if (args.size() < 3) return null; + compute = "min(_vg_prev, " + args.get(2).getText() + ")"; + } + case "imageAtomicMax" -> { + if (args.size() < 3) return null; + compute = "max(_vg_prev, " + args.get(2).getText() + ")"; + } + case "imageAtomicExchange" -> { + if (args.size() < 3) return null; + compute = args.get(2).getText(); + } + case "imageAtomicCompSwap" -> { + if (args.size() < 4) return null; + compute = "(_vg_prev == " + args.get(2).getText() + " ? " + args.get(3).getText() + " : _vg_prev)"; + } + default -> { + return null; + } + } + return "{ " + scalar + " _vg_prev = imageLoad(" + imgName + ", " + idx + ").x; " + + "imageStore(" + imgName + ", " + idx + ", " + vec + "(" + compute + vecArgs + ")); }"; + } + + private static String scalarFor(String glslType) { + if (glslType.startsWith("iimage")) return "int"; + if (glslType.startsWith("uimage")) return "uint"; + return "float"; + } + + private static String componentVecFor(String glslType) { + if (glslType.startsWith("iimage")) return "ivec4"; + if (glslType.startsWith("uimage")) return "uvec4"; + return "vec4"; + } + + private static String vecArgsFor(String vec) { + return switch (vec) { + case "ivec4" -> ", 0, 0, 0"; + case "uvec4" -> ", 0u, 0u, 0u"; + default -> ", 0.0, 0.0, 0.0"; + }; + } + + private static void stripStorageQualifiers(Transformer t, Set kill) { + t.mutateTree(tree -> { + for (var sq : GlslAstHelpers.collectAll(tree, GLSLParser.Storage_qualifierContext.class)) { + if (!kill.contains(sq.getText())) continue; + blankLeadingToken(sq); + } + }); + } + + private static void stripInterfaceOnlyQualifiers(Transformer t) { + t.mutateTree(tree -> { + for (var iq : GlslAstHelpers.collectAll(tree, GLSLParser.Interpolation_qualifierContext.class)) { + blankLeadingToken(iq); + } + for (var sq : GlslAstHelpers.collectAll(tree, GLSLParser.Storage_qualifierContext.class)) { + if (!AUXILIARY_STORAGE_QUALIFIERS.contains(sq.getText())) continue; + blankLeadingToken(sq); + } + }); + } + + private static final Set AUXILIARY_STORAGE_QUALIFIERS = Set.of("centroid", "sample", "patch"); + + private static void blankLeadingToken(ParserRuleContext ctx) { + if (ctx.getChildCount() == 0) return; + if (!(ctx.getChild(0) instanceof TerminalNode tn)) return; + if (tn.getSymbol() instanceof CommonToken ct) ct.setText(""); + } + + private static void hoistNonConstGlobalInitializers(Transformer t) { + final StringBuilder assigns = new StringBuilder(); + t.mutateTree(tree -> { + for (var ed : ((GLSLParser.Translation_unitContext) tree).external_declaration()) { + final var decl = ed.declaration(); + if (decl == null) continue; + final var singles = GlslAstHelpers.collectAll(decl, GLSLParser.Single_declarationContext.class); + if (singles.isEmpty()) continue; + final var fst = singles.get(0).fully_specified_type(); + if (fst == null || (fst.type_qualifier() != null && hasStorageQualifier(fst.type_qualifier()))) continue; + if (hasUnsizedArraySpecifierOutsideInitializer(decl)) continue; + for (var td : GlslAstHelpers.collectAll(decl, GLSLParser.Typeless_declarationContext.class)) { + if (td.IDENTIFIER() == null || td.EQUAL() == null || td.initializer() == null) continue; + assigns.append(td.IDENTIFIER().getText()).append(" = ").append(joinTerminals(td.initializer())).append(";\n"); + if (td.EQUAL().getSymbol() instanceof CommonToken ct) ct.setText(""); + blankAllTerminals(td.initializer()); + } + } + }); + if (assigns.length() > 0) t.prependMain("{\n" + assigns + "}\n"); + } + + private static boolean hasUnsizedArraySpecifierOutsideInitializer(ParserRuleContext decl) { + for (var as : GlslAstHelpers.collectAll(decl, GLSLParser.Array_specifierContext.class)) { + if (GlslAstHelpers.enclosingOfType(as, GLSLParser.InitializerContext.class) != null) continue; + if (as.getText().replace(" ", "").contains("[]")) return true; + } + return false; + } + + private static boolean hasStorageQualifier(GLSLParser.Type_qualifierContext tq) { + for (var sq : tq.single_type_qualifier()) { + if (sq.storage_qualifier() != null) return true; + } + return false; + } + + private static String joinTerminals(ParseTree node) { + final StringBuilder sb = new StringBuilder(); + joinTerminalsWalk(node, sb); + return sb.toString(); + } + + private static void joinTerminalsWalk(ParseTree node, StringBuilder sb) { + if (node instanceof TerminalNode tn) { + if (sb.length() > 0) sb.append(' '); + sb.append(tn.getText()); + return; + } + for (int i = 0; i < node.getChildCount(); i++) joinTerminalsWalk(node.getChild(i), sb); + } + + private static void blankAllTerminals(ParseTree node) { + if (node instanceof TerminalNode tn) { + if (tn.getSymbol() instanceof CommonToken ct) ct.setText(""); + return; + } + for (int i = 0; i < node.getChildCount(); i++) blankAllTerminals(node.getChild(i)); + } + + private static void renameMainToVgBody(Transformer t) { + t.mutateTree(tree -> { + for (var fdef : GlslAstHelpers.collectAll(tree, GLSLParser.Function_definitionContext.class)) { + final var id = fdef.function_prototype().IDENTIFIER(); + if (id == null) continue; + if (!"main".equals(id.getText())) continue; + if (id.getSymbol() instanceof CommonToken ct) { + ct.setText("_vg_body"); + } + return; + } + }); + } + + private static void stripFragOutputs(Transformer t) { + final LinkedHashSet outVars = new LinkedHashSet<>(); + t.mutateTree(tree -> { + for (var decl : GlslAstHelpers.collectAll(tree, GLSLParser.Single_declarationContext.class)) { + final var fst = decl.fully_specified_type(); + if (fst == null || fst.type_qualifier() == null) continue; + if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue; + boolean isOut = false; + for (var sq : fst.type_qualifier().single_type_qualifier()) { + if (sq.storage_qualifier() != null && sq.storage_qualifier().getText().equals("out")) { + isOut = true; + break; + } + } + if (isOut) outVars.add(decl.typeless_declaration().IDENTIFIER().getText()); + } + }); + for (String name : outVars) t.removeVariable(name); + t.mutateTree(tree -> { + for (var assign : GlslAstHelpers.collectAll(tree, GLSLParser.Assignment_expressionContext.class)) { + if (assign.unary_expression() == null) continue; + final String lhs = assign.unary_expression().getText(); + if (lhs.startsWith("gl_FragData") || lhs.equals("gl_FragColor")) { + GlslAstHelpers.deleteStatementContaining(assign); + } + } + }); + } + + private static String buildComputeOutput(GLSLParser.Translation_unitContext computeRoot, RwExtractMode mode, Set writtenImages, Set nonWriteonlyImages, Map declared, List attrs) { + final StringBuilder out = new StringBuilder(8192); + out.append("// _vg_mode: ").append(modeTag(mode)).append('\n'); + out.append("#version 460 core\n"); + switch (mode) { + case CHUNK -> emitChunkPrelude(out, writtenImages, nonWriteonlyImages, declared, attrs); + case COMPOSITE_VSH -> emitCompositeVshPrelude(out, writtenImages, nonWriteonlyImages, declared); + case COMPOSITE_FSH -> emitCompositeFshPrelude(out, writtenImages, nonWriteonlyImages, declared); + } + out.append('\n'); + out.append(GlslTransformUtils.getFormattedShader(computeRoot, "")); + out.append('\n'); + emitDispatchMain(out, mode, attrs); + return out.toString(); + } + + private static String modeTag(RwExtractMode mode) { + return switch (mode) { + case CHUNK -> "chunk"; + case COMPOSITE_VSH -> "composite-vsh"; + case COMPOSITE_FSH -> "composite-fsh"; + }; + } + + private static void emitImageDecls(StringBuilder out, Set writtenImages, Set nonWriteonlyImages, Map declared) { + final List sorted = new ArrayList<>(writtenImages); + Collections.sort(sorted); + final Map infos = activeCustomImages; + for (int i = 0; i < sorted.size(); i++) { + final String name = sorted.get(i); + final ImageDecl d = declared.get(name); + if (d == null) continue; + final InternalTextureFormat fmt = (infos != null && infos.get(name) != null) ? infos.get(name).internalTextureFormat() : null; + final String layoutInner = (fmt != null) ? "binding = " + i + ", " + fmt.name().toLowerCase(Locale.ROOT) : "binding = " + i; + final String qualifier = nonWriteonlyImages.contains(name) ? "" : "writeonly "; + out.append("layout(").append(layoutInner).append(") ").append(qualifier).append("uniform ").append(d.glslType()).append(' ').append(name).append(";\n"); + } + } + + private static void emitChunkPrelude(StringBuilder out, Set writtenImages, Set nonWriteonlyImages, Map declared, List attrs) { + out.append("layout(local_size_x = 64) in;\n\n"); + emitImageDecls(out, writtenImages, nonWriteonlyImages, declared); + out.append("\nuniform int _vg_startVertex;\n"); + out.append("uniform int _vg_vertexCount;\n\n"); + out.append("layout(std430, binding = ").append(VG_VBUF_SSBO_BINDING).append(") readonly buffer _VgVbuf { uint data[]; } _vg_vbuf;\n\n"); + out.append("vec4 _vg_sink_pos;\n"); + out.append("float _vg_sink_psize;\n"); + out.append("int _vg_id_global;\n"); + out.append("#define gl_Position _vg_sink_pos\n"); + out.append("#define gl_PointSize _vg_sink_psize\n"); + out.append("#define gl_VertexID _vg_id_global\n"); + out.append("#define gl_VertexIndex _vg_id_global\n"); + out.append("#define gl_InstanceID 0\n"); + out.append("#define gl_InstanceIndex 0\n\n"); + emitAttributeGlobals(out, attrs); + out.append('\n'); + out.append("int _vg_si8(uint v) { return int(v << 24) >> 24; }\n\n"); + out.append("void _vg_unpack(uint id) {\n"); + out.append(" uint base = id * ").append(STRIDE_UINTS).append("u;\n"); + emitAttributeAssignments(out, attrs); + out.append("}\n\n"); + out.append("void _vert_init() {}\n"); + } + + private static void emitCompositeVshPrelude(StringBuilder out, Set writtenImages, Set nonWriteonlyImages, Map declared) { + out.append("layout(local_size_x = 64) in;\n\n"); + emitImageDecls(out, writtenImages, nonWriteonlyImages, declared); + out.append("\nconst vec4 _vg_quad[4] = vec4[4](\n"); + out.append(" vec4(1.0, 1.0, 0.0, 1.0),\n"); + out.append(" vec4(0.0, 1.0, 0.0, 1.0),\n"); + out.append(" vec4(1.0, 0.0, 0.0, 1.0),\n"); + out.append(" vec4(0.0, 0.0, 0.0, 1.0));\n"); + out.append("vec4 _vg_gl_vertex;\n"); + out.append("int _vg_gl_vertex_id;\n"); + out.append("#define gl_Vertex _vg_gl_vertex\n"); + out.append("#define gl_VertexID _vg_gl_vertex_id\n"); + out.append("uniform mat4 gl_ModelViewProjectionMatrix;\n"); + out.append("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }\n"); + } + + private static void emitCompositeFshPrelude(StringBuilder out, Set writtenImages, Set nonWriteonlyImages, Map declared) { + out.append("layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;\n\n"); + emitImageDecls(out, writtenImages, nonWriteonlyImages, declared); + out.append("\nuniform ivec2 _vg_target_size;\n"); + out.append("vec4 _vg_gl_fragcoord_raw;\n"); + out.append("#define gl_FragCoord _vg_gl_fragcoord_raw\n"); + } + + private static void emitVertexDecode(StringBuilder out, List attrs) { + final Set present = new HashSet<>(); + for (AttributeSlot slot : attrs) present.add(slot.name()); + + out.append("#ifdef USE_VERTEX_COMPRESSION\n"); + if (present.contains("a_PosId")) { + out.append(" _vert_position = vec3(a_PosId.xyz) * VERT_POS_SCALE + VERT_POS_OFFSET;\n"); + out.append(" _draw_id = (a_PosId.w >> 8u) & 0xFFu;\n"); + out.append(" _material_params = (a_PosId.w >> 0u) & 0xFFu;\n"); + } + if (present.contains("a_TexCoord")) out.append(" _vert_tex_diffuse_coord = a_TexCoord * VERT_TEX_SCALE;\n"); + if (present.contains("a_LightCoord")) out.append(" _vert_tex_light_coord = a_LightCoord;\n"); + if (present.contains("a_Color")) out.append(" _vert_color = a_Color;\n"); + out.append("#else\n"); + if (present.contains("a_PosId")) out.append(" _vert_position = a_PosId;\n"); + if (present.contains("a_TexCoord")) out.append(" _vert_tex_diffuse_coord = a_TexCoord;\n"); + if (present.contains("a_Color")) out.append(" _vert_color = a_Color;\n"); + if (present.contains("a_LightCoord")) { + out.append(" uint _vg_draw_params = a_LightCoord & 0xFFFFu;\n"); + out.append(" _material_params = _vg_draw_params & 0xFFu;\n"); + out.append(" _draw_id = (_vg_draw_params >> 8) & 0xFFu;\n"); + out.append(" _vert_tex_light_coord = ivec2((uvec2((a_LightCoord >> 16) & 0xFFFFu) >> uvec2(0, 8)) & uvec2(0xFFu));\n"); + } + out.append("#endif\n"); + } + + private static void emitDispatchMain(StringBuilder out, RwExtractMode mode, List attrs) { + out.append("void main() {\n"); + switch (mode) { + case CHUNK -> { + out.append(" int id = _vg_startVertex + int(gl_GlobalInvocationID.x);\n"); + out.append(" if (id >= _vg_startVertex + _vg_vertexCount) return;\n"); + out.append(" _vg_id_global = id;\n"); + out.append(" _vg_unpack(uint(id));\n"); + emitVertexDecode(out, attrs); + out.append(" _vg_body();\n"); + } + case COMPOSITE_VSH -> { + out.append(" uint vid = gl_GlobalInvocationID.x;\n"); + out.append(" if (vid >= 4u) return;\n"); + out.append(" _vg_gl_vertex = _vg_quad[vid];\n"); + out.append(" _vg_gl_vertex_id = int(vid);\n"); + out.append(" _vg_body();\n"); + } + case COMPOSITE_FSH -> { + out.append(" ivec2 px = ivec2(gl_GlobalInvocationID.xy);\n"); + out.append(" if (px.x >= _vg_target_size.x || px.y >= _vg_target_size.y) return;\n"); + out.append(" _vg_gl_fragcoord_raw = vec4(vec2(px) + 0.5, 0.0, 1.0);\n"); + out.append(" _vg_body();\n"); + } + } + out.append("}\n"); + } + + private static List collectVertexAttributes(Set chunkAttrsUsed, Map chunkAttrAstTypes) { + final List out = new ArrayList<>(); + for (String name : chunkAttrsUsed) { + final Map variants = CHUNK_VERTEX_ATTRS.get(name); + if (variants == null) continue; + final String astType = chunkAttrAstTypes.get(name); + if (astType != null) { + final AttributeSlot pinned = variants.get(astType); + if (pinned != null) { + out.add(pinned); + continue; + } + } + out.addAll(variants.values()); + } + return out; + } + + private static Map collectChunkAttrAstTypes(List decls) { + final LinkedHashMap out = new LinkedHashMap<>(); + for (var decl : decls) { + if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue; + final String name = decl.typeless_declaration().IDENTIFIER().getText(); + if (!CHUNK_VERTEX_ATTRS.containsKey(name)) continue; + if (decl.fully_specified_type() == null || decl.fully_specified_type().type_specifier() == null) continue; + final String typeText = decl.fully_specified_type().type_specifier().getText(); + out.putIfAbsent(name, typeText); + } + return out; + } + + private static void emitAttributeGlobals(StringBuilder out, List attrs) { + final LinkedHashMap> byName = groupByName(attrs); + for (var e : byName.entrySet()) { + final List variants = e.getValue(); + if (variants.size() == 1) { + final AttributeSlot v = variants.get(0); + out.append(v.glslType()).append(' ').append(v.name()).append(";\n"); + } else { + final AttributeSlot live = pickLive(variants); + final AttributeSlot dead = pickDead(variants, live); + out.append("#ifdef USE_VERTEX_COMPRESSION\n"); + out.append(dead.glslType()).append(' ').append(dead.name()).append(";\n"); + out.append("#else\n"); + out.append(live.glslType()).append(' ').append(live.name()).append(";\n"); + out.append("#endif\n"); + } + } + } + + private static void emitAttributeAssignments(StringBuilder out, List attrs) { + final LinkedHashMap> byName = groupByName(attrs); + for (var e : byName.entrySet()) { + final List variants = e.getValue(); + if (variants.size() == 1) { + final AttributeSlot v = variants.get(0); + out.append(" ").append(v.name()).append(" = ").append(v.unpackExpr()).append(";\n"); + } else { + final AttributeSlot live = pickLive(variants); + final AttributeSlot dead = pickDead(variants, live); + out.append("#ifdef USE_VERTEX_COMPRESSION\n"); + out.append(" ").append(dead.name()).append(" = ").append(dead.unpackExpr()).append(";\n"); + out.append("#else\n"); + out.append(" ").append(live.name()).append(" = ").append(live.unpackExpr()).append(";\n"); + out.append("#endif\n"); + } + } + } + + private static LinkedHashMap> groupByName(List attrs) { + final LinkedHashMap> out = new LinkedHashMap<>(); + for (AttributeSlot a : attrs) out.computeIfAbsent(a.name(), k -> new ArrayList<>()).add(a); + return out; + } + + private static AttributeSlot pickLive(List variants) { + for (AttributeSlot v : variants) if (v.liveBranch()) return v; + return variants.get(0); + } + + private static AttributeSlot pickDead(List variants, AttributeSlot live) { + for (AttributeSlot v : variants) if (v != live) return v; + return variants.get(0); + } + + static final Map> CHUNK_VERTEX_ATTRS = buildAttrTable(); + + private static Map> buildAttrTable() { + final LinkedHashMap> m = new LinkedHashMap<>(); + + addAttr(m, new AttributeSlot("iris_Vertex", "vec4", 0, + "vec4(uintBitsToFloat(_vg_vbuf.data[base + 0u]), uintBitsToFloat(_vg_vbuf.data[base + 1u]), uintBitsToFloat(_vg_vbuf.data[base + 2u]), 1.0)")); + addAttr(m, new AttributeSlot("iris_Color", "vec4", 12, + "vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 8) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 16) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 24) & 0xFFu)) * (1.0 / 255.0)")); + addAttr(m, new AttributeSlot("iris_MultiTexCoord0", "vec4", 16, + "vec4(uintBitsToFloat(_vg_vbuf.data[base + 4u]), uintBitsToFloat(_vg_vbuf.data[base + 5u]), 0.0, 1.0)")); + addAttr(m, new AttributeSlot("iris_MultiTexCoord1", "vec4", 24, + "vec4(float(_vg_vbuf.data[base + 6u] & 0xFFFFu) * (1.0/16.0), float((_vg_vbuf.data[base + 6u] >> 16) & 0xFFFFu) * (1.0/16.0), 0.0, 1.0)")); + + addAttr(m, new AttributeSlot("mc_midTexCoord", "vec4", 28, + "vec4(float(_vg_vbuf.data[base + 7u] & 0xFFFFu), float((_vg_vbuf.data[base + 7u] >> 16) & 0xFFFFu), 0.0, 1.0)")); + addAttr(m, new AttributeSlot("mc_midTexCoord", "vec2", 28, + "vec2(float(_vg_vbuf.data[base + 7u] & 0xFFFFu), float((_vg_vbuf.data[base + 7u] >> 16) & 0xFFFFu))")); + + addAttr(m, new AttributeSlot("at_tangent", "vec4", 32, + "vec4(float(_vg_si8(_vg_vbuf.data[base + 8u])) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 8)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 16)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 24)) * (1.0/127.0))")); + + addAttr(m, new AttributeSlot("iris_Normal", "vec3", 36, + "vec3(float(_vg_si8(_vg_vbuf.data[base + 9u])) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 9u] >> 8)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 9u] >> 16)) * (1.0/127.0))")); + + addAttr(m, new AttributeSlot("mc_Entity", "vec4", 40, + "vec4(float(_vg_vbuf.data[base + 10u]), 0.0, 0.0, 0.0)")); + addAttr(m, new AttributeSlot("mc_Entity", "uint", 40, + "_vg_vbuf.data[base + 10u]")); + + addAttr(m, new AttributeSlot("at_midBlock", "vec4", 44, + "vec4(float(_vg_si8(_vg_vbuf.data[base + 11u])), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 8)), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 16)), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 24)))")); + + addAttr(m, new AttributeSlot("a_PosId", "vec3", 0, + "vec3(uintBitsToFloat(_vg_vbuf.data[base + 0u]), uintBitsToFloat(_vg_vbuf.data[base + 1u]), uintBitsToFloat(_vg_vbuf.data[base + 2u]))")); + addAttr(m, new AttributeSlot("a_Color", "vec4", 12, + "vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 8) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 16) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 24) & 0xFFu)) * (1.0 / 255.0)")); + addAttr(m, new AttributeSlot("a_TexCoord", "vec2", 16, + "vec2(uintBitsToFloat(_vg_vbuf.data[base + 4u]), uintBitsToFloat(_vg_vbuf.data[base + 5u]))")); + addAttr(m, new AttributeSlot("a_LightCoord", "uint", 24, + "_vg_vbuf.data[base + 6u]")); + + addAttr(m, new AttributeSlot("a_PosId", "uvec4", 0, + "uvec4(0u, 0u, 0u, 0u)", false)); + addAttr(m, new AttributeSlot("a_LightCoord", "ivec2", 24, + "ivec2(0, 0)", false)); + + final LinkedHashMap> immutable = new LinkedHashMap<>(); + for (var e : m.entrySet()) immutable.put(e.getKey(), Map.copyOf(e.getValue())); + return Map.copyOf(immutable); + } + + private static void addAttr(LinkedHashMap> m, AttributeSlot slot) { + m.computeIfAbsent(slot.name(), _ -> new LinkedHashMap<>()).put(slot.glslType(), slot); + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicator.java b/src/main/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicator.java new file mode 100644 index 000000000..ef34caee1 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicator.java @@ -0,0 +1,41 @@ +package net.coderbot.iris.pipeline.transform; + +import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import org.taumc.glsl.Transformer; + +import java.util.List; +import java.util.Map; + +final class SamplerAliasDeduplicator { + + private record AliasGroup(String canonical, List aliases) {} + + private static final List GROUPS = List.of( + new AliasGroup("tex", List.of("texture", "gtexture", "textureAtlas")), + new AliasGroup("depthtex0", List.of("gdepthtex")), + new AliasGroup("dhDepthTex0", List.of("dhDepthTex")) + ); + + private SamplerAliasDeduplicator() {} + + static void transformGrouped(Map trees, Parameters parameters) { + for (AliasGroup group : GROUPS) { + applyGroup(trees, group); + } + } + + private static void applyGroup(Map trees, AliasGroup group) { + String canonical = group.canonical(); + for (String alias : group.aliases()) { + for (Transformer t : trees.values()) { + if (t == null || t.findType(alias) == 0) continue; + if (t.findType(canonical) != 0) { + t.removeVariable(alias); + t.rename(alias, canonical); + } else { + t.rename(alias, canonical); + } + } + } + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriter.java b/src/main/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriter.java new file mode 100644 index 000000000..6e93f64be --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriter.java @@ -0,0 +1,156 @@ +package net.coderbot.iris.pipeline.transform; + +import net.coderbot.iris.gl.image.ImageInformation; +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +public final class SamplerToStorageImageRewriter { + + + public record Candidate(String samplerName, String imageName, String layoutQualifier, int dim, boolean signedInt) {} + + private static volatile Set activeCandidates = Set.of(); + + public static void setActiveCandidates(Set candidates) { + activeCandidates = (candidates == null) ? Set.of() : Set.copyOf(candidates); + } + + public static Set activeCandidates() { + return activeCandidates; + } + + /** SDL_GPU forbids sampler usage on integer formats */ + public static Set buildCandidates(Iterable infos) { + if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return Set.of(); + final HashSet out = new HashSet<>(); + for (ImageInformation info : infos) { + if (info.samplerName() == null || info.samplerName().isEmpty()) continue; + if (!info.format().isInteger()) continue; + final int dim = switch (info.target()) { + case TEXTURE_1D -> 1; + case TEXTURE_2D, TEXTURE_RECTANGLE -> 2; + case TEXTURE_3D -> 3; + }; + final InternalTextureFormat fmt = info.internalTextureFormat(); + final String layout = fmt.name().toLowerCase(Locale.ROOT); + final boolean signed = fmt.name().endsWith("I") && !fmt.name().endsWith("UI"); + out.add(new Candidate(info.samplerName(), info.name(), layout, dim, signed)); + } + return out; + } + + private SamplerToStorageImageRewriter() {} + + public static void transformGrouped(Map trees, Parameters parameters) { + final Set candidates = activeCandidates; + if (candidates.isEmpty()) return; + + final Set samplerNames = new HashSet<>(); + for (Candidate c : candidates) samplerNames.add(c.samplerName()); + final Set filtered = collectFilteredSamplers(trees, samplerNames); + + for (Candidate c : candidates) { + if (filtered.contains(c.samplerName())) continue; + applyCandidate(trees, c); + } + } + + private static void applyCandidate(Map trees, Candidate c) { + final int expectedType = c.signedInt + ? lexerTypeForISampler(c.dim) + : lexerTypeForUSampler(c.dim); + if (expectedType == 0) return; + + for (Transformer t : trees.values()) { + if (t == null) continue; + if (t.findType(c.samplerName) != expectedType) continue; + if (t.findType(c.imageName) != 0) continue; + t.removeVariable(c.samplerName); + final String imageType = (c.signedInt ? "iimage" : "uimage") + c.dim + "D"; + t.variable = null; + t.injectVariable("layout(" + c.layoutQualifier + ") readonly uniform " + imageType + " " + c.imageName + ";"); + t.rename(c.samplerName, c.imageName); + rewriteTexelFetchToImageLoad(t, c.imageName); + } + } + + private static int lexerTypeForUSampler(int dim) { + return switch (dim) { + case 1 -> GLSLLexer.USAMPLER1D; + case 2 -> GLSLLexer.USAMPLER2D; + case 3 -> GLSLLexer.USAMPLER3D; + default -> 0; + }; + } + + private static int lexerTypeForISampler(int dim) { + return switch (dim) { + case 1 -> GLSLLexer.ISAMPLER1D; + case 2 -> GLSLLexer.ISAMPLER2D; + case 3 -> GLSLLexer.ISAMPLER3D; + default -> 0; + }; + } + + private static final Set FILTERED_CALL_NAMES = buildFilteredCallNames(); + + private static Set buildFilteredCallNames() { + final Set modernNames = new HashSet<>(Set.of("texture", "textureLod", "textureGrad", "textureProj", "textureGather", "textureOffset", "textureProjLod")); + final Set names = new HashSet<>(modernNames); + GlslTransformUtils.TEXTURE_RENAMES.forEach((legacy, modern) -> { + if (modernNames.contains(modern)) names.add(legacy); + }); + return Set.copyOf(names); + } + + private static Set collectFilteredSamplers(Map trees, Set samplerNames) { + final Set filtered = new HashSet<>(); + if (samplerNames.isEmpty()) return filtered; + for (Transformer t : trees.values()) { + if (t == null) continue; + t.mutateTree(tree -> { + for (GLSLParser.Postfix_expressionContext expr : GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class)) { + final String fname = GlslAstHelpers.extractCallName(expr); + if (fname == null) continue; + if (!isFilteredCallName(fname)) continue; + final String first = GlslAstHelpers.firstArgIdentifier(expr); + if (samplerNames.contains(first)) filtered.add(first); + } + }); + } + return filtered; + } + + private static boolean isFilteredCallName(String fname) { + for (String n : FILTERED_CALL_NAMES) if (n.equals(fname)) return true; + return false; + } + + private static void rewriteTexelFetchToImageLoad(Transformer transformer, String imageName) { + transformer.mutateTree(tree -> { + final List all = GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class); + for (GLSLParser.Postfix_expressionContext expr : all) { + final String fname = GlslAstHelpers.extractCallName(expr); + if (!"texelFetch".equals(fname)) continue; + if (!GlslAstHelpers.firstArgIdentifier(expr).equals(imageName)) continue; + final String secondArg = GlslAstHelpers.secondArgText(expr); + if (secondArg == null) continue; + final String replacement = "imageLoad(" + imageName + ", " + secondArg + ")"; + final GLSLParser.Postfix_expressionContext parsed = ShaderParser.parseSnippet(replacement, GLSLParser::postfix_expression); + GlslAstHelpers.replaceNode(expr, parsed); + } + }); + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java index e772d1d17..69b842338 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java @@ -4,12 +4,11 @@ import com.google.common.base.Stopwatch; import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer; import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; @@ -18,6 +17,7 @@ import org.taumc.glsl.ShaderParser; import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLLexer; +import java.util.Arrays; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; @@ -45,14 +45,18 @@ public class ShaderTransformer { } - private record VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {} + private record VersionRequirement(String keyword, int minVersion, boolean prefix, BooleanSupplier supported) { + VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) { + this(keyword, minVersion, false, supported); + } + } // Sorted descending by minVersion for early exit in getRequiredVersion private static final VersionRequirement[] VERSION_REQUIREMENTS = { new VersionRequirement("std430", 430, RenderSystem::supportsSSBO), - new VersionRequirement("iimage", 420, RenderSystem::supportsImageLoadStore), - new VersionRequirement("uimage", 420, RenderSystem::supportsImageLoadStore), + new VersionRequirement("iimage", 420, true, RenderSystem::supportsImageLoadStore), + new VersionRequirement("uimage", 420, true, RenderSystem::supportsImageLoadStore), new VersionRequirement("imageLoad", 420, RenderSystem::supportsImageLoadStore), new VersionRequirement("imageStore", 420, RenderSystem::supportsImageLoadStore), @@ -63,6 +67,10 @@ public class ShaderTransformer { new VersionRequirement("flat", 130, () -> RenderSystem.getMaxGlslVersion() >= 130), }; + static boolean canEmitImageOps() { + return RenderSystem.supportsImageLoadStore() && RenderSystem.getMaxGlslVersion() >= 420; + } + record NegotiationResult(int targetVersion, String profile, String error) { static NegotiationResult error(String message) { @@ -101,31 +109,33 @@ public class ShaderTransformer { } private static Pattern hoistPattern; - private static Object2IntMap keywordToVersion; + /** By capturing group: a prefix match's text is not the keyword, so it cannot be looked up by name. */ + private static int[] hoistGroupVersions; private static int maxSupportedHoistVersion; public static void init() { final StringBuilder patternBuilder = new StringBuilder(); - final Object2IntOpenHashMap versionMap = new Object2IntOpenHashMap<>(); + final int[] groupVersions = new int[VERSION_REQUIREMENTS.length + 1]; + int groupCount = 0; int maxVersion = 0; for (VersionRequirement req : VERSION_REQUIREMENTS) { if (req.supported.getAsBoolean()) { if (!patternBuilder.isEmpty()) patternBuilder.append('|'); - patternBuilder.append("\\b").append(Pattern.quote(req.keyword)).append("\\b"); - versionMap.put(req.keyword, req.minVersion); + patternBuilder.append("(\\b").append(Pattern.quote(req.keyword)) .append(req.prefix ? "\\w*" : "\\b").append(')'); + groupVersions[++groupCount] = req.minVersion; maxVersion = Math.max(maxVersion, req.minVersion); } } if (!patternBuilder.isEmpty()) { hoistPattern = Pattern.compile(patternBuilder.toString()); - keywordToVersion = versionMap; + hoistGroupVersions = Arrays.copyOf(groupVersions, groupCount + 1); } maxSupportedHoistVersion = maxVersion; - Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", versionMap.size(), maxVersion > 0 ? maxVersion : "N/A"); + Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", groupCount, maxVersion > 0 ? maxVersion : "N/A"); } private static int getRequiredVersion(String shaderSource, int declaredVersion) { @@ -136,15 +146,31 @@ public class ShaderTransformer { final Matcher m = hoistPattern.matcher(shaderSource); int required = declaredVersion; while (m.find()) { - final int ver = keywordToVersion.getInt(m.group()); - if (ver > required) { - required = ver; - if (required >= maxSupportedHoistVersion) break; + for (int group = 1; group < hoistGroupVersions.length; group++) { + if (m.start(group) < 0) continue; + if (hoistGroupVersions[group] > required) required = hoistGroupVersions[group]; + break; } + if (required >= maxSupportedHoistVersion) break; } return required; } + private record StageHeader(int version, String extensions) {} + + private static String finalizeStage(int version, String headerTail, String body, PatchShaderType stage) { + final int required = getRequiredVersion(headerTail + body, version); + if (required > version) { + final NegotiationResult negotiation = negotiateVersion(required, stage); + if (negotiation.isError()) { + throw new RuntimeException("Shader version negotiation failed for " + stage.name() + " after transformation: " + negotiation.error()); + } + Iris.logger.debug("Transformed {} requires GLSL {} for injected features, hoisting from {}", stage.name(), required, version); + version = required; + } + return "#version " + version + " core\n" + headerTail + body; + } + private static final class TransformKey

{ private final Patch patchType; private final EnumMap inputs; @@ -298,8 +324,6 @@ public class ShaderTransformer { versionString = String.valueOf(versionInt); } - final String profileString = "#version " + versionString + " core\n"; - // Pre-parse reserved word renaming String input = GlslTransformUtils.replaceTexture(compute); input = GlslTransformUtils.renameReservedWords(input, versionInt); @@ -309,15 +333,25 @@ public class ShaderTransformer { doTransform(transformer, patchType, parameters, versionInt); + // SDL_GPU forbids sampler usage on integer formats, so an integer sampler has to become a storage image here + final EnumMap computeTypes = new EnumMap<>(PatchShaderType.class); + computeTypes.put(PatchShaderType.COMPUTE, transformer); + if (canEmitImageOps()) { + SamplerToStorageImageRewriter.transformGrouped(computeTypes, parameters); + } + if (BackendManager.RENDER_BACKEND.isSDLGPU()) { + LocalZeroInitTransformer.transformGrouped(computeTypes); + } + // Extract extensions final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); - final String finalHeader = profileString + (extensions.isEmpty() ? "" : "\n" + extensions); + final String headerTail = extensions.isEmpty() ? "" : "\n" + extensions; final StringBuilder formattedShaderBuilder = new StringBuilder(); - transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader))); + transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, ""))); - String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString()); + final String formattedShader = GlslTransformUtils.restoreReservedWords(finalizeStage(versionInt, headerTail, formattedShaderBuilder.toString(), PatchShaderType.COMPUTE)); result.put(PatchShaderType.COMPUTE, formattedShader); @@ -329,7 +363,7 @@ public class ShaderTransformer { private static

Map transformInternal(EnumMap inputs, Patch patchType, P parameters) { final EnumMap result = new EnumMap<>(PatchShaderType.class); final EnumMap types = new EnumMap<>(PatchShaderType.class); - final EnumMap prepatched = new EnumMap<>(PatchShaderType.class); + final EnumMap prepatched = new EnumMap<>(PatchShaderType.class); final Stopwatch watch = Stopwatch.createStarted(); @@ -353,9 +387,7 @@ public class ShaderTransformer { int versionInt = Integer.parseInt(versionString); - // Include celeritas header in scan — it's injected post-negotiation but contains uint/uvec3 - final String scanSource = (patchType == Patch.CELERITAS_TERRAIN && type == PatchShaderType.VERTEX) ? input + computeCeleritasHeader() : input; - final int requiredVersion = getRequiredVersion(scanSource, versionInt); + final int requiredVersion = getRequiredVersion(input, versionInt); if (requiredVersion > versionInt) { Iris.logger.debug("Shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt); versionInt = requiredVersion; @@ -375,10 +407,6 @@ public class ShaderTransformer { throw new RuntimeException("Shader version negotiation failed for " + type.name() + ": " + negotiation.error()); } - // All stages >= 330 use core profile - final String profile = "core"; - final String profileString = "#version " + versionString + " " + profile + "\n"; - // Pre-parse reserved word renaming — prevents ANTLR parse failures input = GlslTransformUtils.replaceTexture(input); input = GlslTransformUtils.renameReservedWords(input, versionInt); @@ -394,38 +422,70 @@ public class ShaderTransformer { final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); types.put(type, transformer); - prepatched.put(type, profileString + (extensions.isEmpty() ? "" : "\n" + extensions)); + prepatched.put(type, new StageHeader(versionInt, extensions.isEmpty() ? "" : "\n" + extensions)); } CompatibilityTransformer.transformGrouped(types, parameters); + if (BackendManager.RENDER_BACKEND.isSDLGPU()) { + SamplerAliasDeduplicator.transformGrouped(types, parameters); + } + if (canEmitImageOps()) { + SamplerToStorageImageRewriter.transformGrouped(types, parameters); + } + if (BackendManager.RENDER_BACKEND.isSDLGPU()) { + LocalZeroInitTransformer.transformGrouped(types); + } for (var entry : types.entrySet()) { final PatchShaderType shaderType = entry.getKey(); final Transformer transformer = entry.getValue(); - String header = prepatched.get(shaderType); + final StageHeader stageHeader = prepatched.get(shaderType); + String headerTail = stageHeader.extensions(); // For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header if (patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX) { - header += computeCeleritasHeader(); + headerTail += computeCeleritasHeader(); } - final String finalHeader = header; final StringBuilder formattedShaderBuilder = new StringBuilder(); - transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader))); + transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, ""))); - String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString()); + final String formattedShader = GlslTransformUtils.restoreReservedWords( finalizeStage(stageHeader.version(), headerTail, formattedShaderBuilder.toString(), shaderType)); result.put(shaderType, formattedShader); } + maybeExtractRwImageStores(result, patchType); watch.stop(); Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch); return result; } + private static void maybeExtractRwImageStores(EnumMap result, Patch patchType) { + if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return; + if (result.containsKey(PatchShaderType.COMPUTE)) return; + + final String vsh = result.get(PatchShaderType.VERTEX); + final String fsh = result.get(PatchShaderType.FRAGMENT); + final RwImageStoreExtractor.Result vshResult = (vsh != null) ? RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, patchType.name()) : null; + final RwImageStoreExtractor.Result fshResult = (fsh != null) ? RwImageStoreExtractor.tryExtract(fsh, PatchShaderType.FRAGMENT, patchType.name()) : null; + + if (vshResult != null && fshResult != null) { + throw new RuntimeException("Program " + patchType.name() + " writes images from both VSH and FSH; only one stage may write per program under SDL_GPU"); + } + if (vshResult != null) { + result.put(PatchShaderType.VERTEX, vshResult.strippedSource()); + result.put(PatchShaderType.COMPUTE, vshResult.computeSource()); + Iris.logger.info("[RwImageStoreExtractor] Extracted compute pre-pass for {} (mode={}, written={})", patchType.name(), vshResult.mode(), vshResult.writtenImages()); + } else if (fshResult != null) { + result.put(PatchShaderType.FRAGMENT, fshResult.strippedSource()); + result.put(PatchShaderType.COMPUTE, fshResult.computeSource()); + Iris.logger.info("[RwImageStoreExtractor] Extracted compute pre-pass for {} (mode={}, written={})", patchType.name(), fshResult.mode(), fshResult.writtenImages()); + } + } + private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, int versionInt) { switch (patchType) { case CELERITAS_TERRAIN: CeleritasTransformer.transform(transformer, parameters, versionInt); - // Handle mc_midTexCoord for Celeritas patchMultiTexCoord3(transformer, parameters); replaceMidTexCoord(transformer, IrisExtendedChunkVertexType.MID_TEX_SCALE); replaceMCEntity(transformer, parameters); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TextureTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/TextureTransformer.java index 56793f68d..140e37bd6 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TextureTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TextureTransformer.java @@ -1,7 +1,7 @@ package net.coderbot.iris.pipeline.transform; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import net.coderbot.iris.shaderpack.texture.TextureStage; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java index 3e71f3adc..d1af7526f 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -1,8 +1,13 @@ package net.coderbot.iris.pipeline.transform; +import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import net.coderbot.iris.pipeline.transform.parameter.CeleritasTerrainParameters; @@ -94,9 +99,30 @@ public class TransformPatcher { // Double-check in case another thread added it while we were transforming final Map existing = cache.get(key); if (existing != null) { - return existing; + result = existing; + } else { + cache.put(key, result); } - cache.put(key, result); + } + } + } + + if (result != null && RenderSystem.isGLES()) { + for (Map.Entry entry : result.entrySet()) { + final String src = entry.getValue(); + if (src == null) continue; + final PatchShaderType pType = entry.getKey(); + CompatShaderTransformer.prewarm(src, pType.glShaderType.id, pType == PatchShaderType.FRAGMENT); + } + } + + if (result != null && BackendManager.RENDER_BACKEND.isSDLGPU()) { + final ShaderTransformPostProcessor processor = GLSMHooks.postTransformProcessor; + if (processor != null) { + for (Map.Entry entry : result.entrySet()) { + final String src = entry.getValue(); + if (src == null) continue; + processor.onTransformed(src, entry.getKey().glShaderType); } } } @@ -108,6 +134,10 @@ public class TransformPatcher { return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint)); } + public static Map patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) { + return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint, true)); + } + public static Map patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) { return patchAttributes(vertex, geometry, tessControl, tessEval, fragment, inputs, false); } @@ -154,7 +184,14 @@ public class TransformPatcher { return null; } Map result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap)); - return result != null ? result.get(PatchShaderType.COMPUTE) : null; + final String transformed = result != null ? result.get(PatchShaderType.COMPUTE) : null; + if (transformed != null && BackendManager.RENDER_BACKEND.isSDLGPU()) { + final ShaderTransformPostProcessor processor = GLSMHooks.postTransformProcessor; + if (processor != null) { + processor.onTransformed(transformed, PatchShaderType.COMPUTE.glShaderType); + } + } + return transformed; } public static void clearCache() { diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java index 9e98a41ba..62637df6b 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java @@ -8,13 +8,19 @@ public class AttributeParameters extends Parameters { public final boolean hasGeometry; public final InputAvailability inputs; public final boolean scrollGlint; + public final boolean instanced; // WARNING: adding new fields requires updating hashCode and equals methods! public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint) { + this(patch, hasGeometry, inputs, scrollGlint, false); + } + + public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint, boolean instanced) { super(patch, null); this.hasGeometry = hasGeometry; this.inputs = inputs; this.scrollGlint = scrollGlint; + this.instanced = instanced; } @Override @@ -28,6 +34,7 @@ public class AttributeParameters extends Parameters { int result = super.hashCode(); result = prime * result + (hasGeometry ? 1231 : 1237); result = prime * result + (scrollGlint ? 1231 : 1237); + result = prime * result + (instanced ? 1231 : 1237); result = prime * result + ((inputs == null) ? 0 : inputs.hashCode()); return result; } @@ -45,6 +52,8 @@ public class AttributeParameters extends Parameters { return false; if (scrollGlint != other.scrollGlint) return false; + if (instanced != other.instanced) + return false; if (inputs == null) { if (other.inputs != null) return false; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java index 25cb8199b..1d07147e7 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java @@ -2,7 +2,7 @@ package net.coderbot.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.Patch; import net.coderbot.iris.shaderpack.texture.TextureStage; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/DHParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/DHParameters.java index 1898357c5..25612678d 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/DHParameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/DHParameters.java @@ -1,7 +1,7 @@ package net.coderbot.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.Patch; import net.coderbot.iris.shaderpack.texture.TextureStage; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java index aef7981ea..07d8e57da 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java @@ -2,8 +2,8 @@ package net.coderbot.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.Patch; import net.coderbot.iris.shaderpack.texture.TextureStage; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java index 4ae606a6b..17edc9d40 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java @@ -2,7 +2,7 @@ package net.coderbot.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.pipeline.transform.Patch; import net.coderbot.iris.shaderpack.texture.TextureStage; diff --git a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java b/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java index ca13c62ec..4a05cc1df 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java +++ b/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java @@ -9,8 +9,8 @@ import net.coderbot.iris.gl.program.ProgramBuilder; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.gl.texture.DepthCopyStrategy; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.coderbot.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; diff --git a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java index a8b2aba1e..0bb75dd04 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java @@ -3,10 +3,13 @@ package net.coderbot.iris.postprocess; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import lombok.Getter; +import net.coderbot.iris.Iris; import net.coderbot.iris.features.FeatureFlags; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; import net.coderbot.iris.gl.framebuffer.ViewportData; @@ -22,7 +25,10 @@ import net.coderbot.iris.gl.texture.TextureAccess; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.pipeline.transform.PatchShaderType; +import net.coderbot.iris.pipeline.transform.PreRasterComputeDispatcher; +import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor; import net.coderbot.iris.pipeline.transform.TransformPatcher; +import org.lwjgl.opengl.GL20; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.rendertarget.RenderTargets; import net.coderbot.iris.samplers.IrisImages; @@ -39,6 +45,7 @@ import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.shader.Framebuffer; +import net.minecraft.profiler.Profiler; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; @@ -54,6 +61,8 @@ import java.util.concurrent.CompletionException; import java.util.function.Supplier; public class CompositeRenderer { + private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS); + private final RenderTargets renderTargets; private final ImmutableList passes; @@ -66,8 +75,8 @@ public class CompositeRenderer { @Nullable private final Object2ObjectMap irisCustomTextures; @Nullable private final WorldRenderingPipeline pipeline; private final TextureStage textureStage; - @Getter - private final ImmutableSet flippedAtLeastOnceFinal; + @Getter private final ImmutableSet flippedAtLeastOnceFinal; + @Getter private int samplerUsage; public CompositeRenderer(PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, RenderTargets renderTargets, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier, @@ -112,6 +121,7 @@ public class CompositeRenderer { if (source == null || !source.isValid()) { if (computes[i] != null) { final ComputeOnlyPass pass = new ComputeOnlyPass(); + pass.name = computeOnlyPassName(computes[i], stageName, i); pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); passes.add(pass); } @@ -119,14 +129,34 @@ public class CompositeRenderer { } final Pass pass = new Pass(); + pass.name = "iris_" + source.getName(); final ProgramDirectives directives = source.getDirectives(); + final long _passStart = System.nanoTime(); Map transformed = getTransformed(source, transformFutures, i, stageName); + final long _afterTx = System.nanoTime(); pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); + final long _afterProg = System.nanoTime(); + final String preComputeSrc = transformed.get(PatchShaderType.COMPUTE); + if (preComputeSrc != null) { + pass.preRasterMode = RwImageStoreExtractor.parseSentinel(preComputeSrc); + if (pass.preRasterMode != null) { + pass.preRasterCompute = buildPreRasterCompute(source.getName(), preComputeSrc, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); + } + } pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); + final long _afterComp = System.nanoTime(); final int[] drawBuffers = directives.getDrawBuffers(); final GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers); + final long _afterFb = System.nanoTime(); + Iris.logger.info("[Load #{}] {}[{}] tx={}ms prog={}ms compute={}ms fb={}ms total={}ms", + Iris.getShaderPackLoadId(), stageName, i, + String.format("%.1f", (_afterTx - _passStart) / 1_000_000.0), + String.format("%.1f", (_afterProg - _afterTx) / 1_000_000.0), + String.format("%.1f", (_afterComp - _afterProg) / 1_000_000.0), + String.format("%.1f", (_afterFb - _afterComp) / 1_000_000.0), + String.format("%.1f", (_afterFb - _passStart) / 1_000_000.0)); int passWidth = 0, passHeight = 0; // Flip the buffers that this shader wrote to, and set pass width and height @@ -170,6 +200,12 @@ public class CompositeRenderer { this.passes = passes.build(); this.flippedAtLeastOnceFinal = flippedAtLeastOnce.build(); + if (Tracy.ENABLED) { + for (Pass pass : this.passes) { + Tracy.message("passGraph " + stageName + "/" + pass.name + " draw=" + java.util.Arrays.toString(pass.drawBuffers) + " mipmapped=" + pass.mipmappedBuffers + " readsAlt=" + pass.stageReadsFromAlt); + } + } + OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); } @@ -213,17 +249,29 @@ public class CompositeRenderer { } } + private static String computeOnlyPassName(ComputeSource[] computes, String stageName, int index) { + for (ComputeSource compute : computes) { + if (compute != null) { + return "iris_" + compute.getName(); + } + } + return "iris_" + stageName + "_compute" + index; + } + private static class Pass { + String name; int[] drawBuffers; int viewWidth; int viewHeight; Program program; ComputeProgram[] computes; + @Nullable ComputeProgram preRasterCompute; + @Nullable RwImageStoreExtractor.RwExtractMode preRasterMode; + int preRasterTargetSizeLoc = -2; GlFramebuffer framebuffer; ImmutableSet stageReadsFromAlt; ImmutableSet mipmappedBuffers; ViewportData viewportScale; - protected void destroy() { this.program.destroy(); for (ComputeProgram compute : this.computes) { @@ -231,6 +279,10 @@ public class CompositeRenderer { compute.destroy(); } } + if (this.preRasterCompute != null) { + this.preRasterCompute.destroy(); + this.preRasterCompute = null; + } } } @@ -251,49 +303,72 @@ public class CompositeRenderer { FullScreenQuadRenderer.INSTANCE.begin(); + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + for (Pass renderPass : passes) { - boolean ranCompute = false; - for (ComputeProgram computeProgram : renderPass.computes) { - if (computeProgram != null) { - ranCompute = true; - final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); - computeProgram.use(); - this.customUniforms.push(computeProgram); - computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight); + profiler.startSection(renderPass.name); + GLDebug.pushGroup(renderPass.name); + try { + boolean ranCompute = false; + for (ComputeProgram computeProgram : renderPass.computes) { + if (computeProgram != null) { + ranCompute = true; + final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); + computeProgram.use(); + this.customUniforms.push(computeProgram); + computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight); + } } - } - if (ranCompute) { - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); - } - - Program.unbind(); - - if (renderPass instanceof ComputeOnlyPass) { - continue; - } - - if (!renderPass.mipmappedBuffers.isEmpty()) { - GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); - - for (int index : renderPass.mipmappedBuffers) { - setupMipmapping(CompositeRenderer.this.renderTargets.get(index), renderPass.stageReadsFromAlt.contains(index)); + if (ranCompute) { + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); + for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) { + renderTargets.get(i).markBothDirty(); + } } + + Program.unbind(); + + if (renderPass instanceof ComputeOnlyPass) { + continue; + } + + final ImmutableSet readsFromAlt = renderTargets.parityResolve(renderPass.stageReadsFromAlt); + + if (!renderPass.mipmappedBuffers.isEmpty()) { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + + for (int index : renderPass.mipmappedBuffers) { + setupMipmapping(CompositeRenderer.this.renderTargets.get(index), readsFromAlt.contains(index)); + } + } + + final float scaledWidth = renderPass.viewWidth * renderPass.viewportScale.scale(); + final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale.scale(); + final float viewportX = renderPass.viewWidth * renderPass.viewportScale.viewportX(); + final float viewportY = renderPass.viewHeight * renderPass.viewportScale.viewportY(); + GLStateManager.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight); + + if (renderPass.preRasterCompute != null && renderPass.preRasterMode != null) { + dispatchPreRasterCompute(renderPass); + } + + renderPass.framebuffer.bind(); + renderPass.program.use(); + + this.customUniforms.push(renderPass.program); + FullScreenQuadRenderer.uploadCompositeMatrices(); + + FullScreenQuadRenderer.INSTANCE.renderQuad(); + + for (int buffer : renderPass.drawBuffers) { + final boolean writeIsAlt = !readsFromAlt.contains(buffer); + CompositeRenderer.this.renderTargets.get(buffer).markDirty(writeIsAlt); + } + } finally { + GLDebug.popGroup(); + profiler.endSection(); } - - final float scaledWidth = renderPass.viewWidth * renderPass.viewportScale.scale(); - final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale.scale(); - final float viewportX = renderPass.viewWidth * renderPass.viewportScale.viewportX(); - final float viewportY = renderPass.viewHeight * renderPass.viewportScale.viewportY(); - GLStateManager.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight); - - renderPass.framebuffer.bind(); - renderPass.program.use(); - - this.customUniforms.push(renderPass.program); - FullScreenQuadRenderer.uploadCompositeMatrices(); - - FullScreenQuadRenderer.INSTANCE.renderQuad(); } FullScreenQuadRenderer.end(); @@ -306,7 +381,8 @@ public class CompositeRenderer { GLStateManager.glUseProgram(0); // NB: Unbinding all of these textures is necessary for proper shaderpack reloading. - for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { + final int maxUnit = Math.min(SamplerLimits.get().getMaxTextureUnits() - 1, GLStateManager.getMaxBoundTextureUnit()); + for (int i = 0; i <= maxUnit; i++) { // Unbind all textures that we may have used. // NB: This is necessary for shader pack reloading to work propely GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); @@ -316,21 +392,26 @@ public class CompositeRenderer { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } + private void dispatchPreRasterCompute(Pass pass) { + pass.preRasterTargetSizeLoc = PreRasterComputeDispatcher.dispatch(pass.preRasterCompute, pass.preRasterMode, pass.preRasterTargetSizeLoc, pass.viewWidth, pass.viewHeight, this.customUniforms); + } + private static void setupMipmapping(RenderTarget target, boolean readFromAlt) { int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); - // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer - // (since the last mipmap was generated) - // - // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the - // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a - // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the - // sampling mode is always reset between frames, so this only persists after the first program to use - // mipmapping on this buffer. - // - // Also note that this only applies to one of the two buffers in a render target buffer pair - making it - // unlikely that this issue occurs in practice with most shader packs. - RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + // Only regen when the sampled side has been written since the last regen. + if (target.isDirty(readFromAlt)) { + if (Tracy.ENABLED) { + Tracy.beginZone(Z_GEN_MIPMAP); + Tracy.zoneValue(texture); + } + try { + RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + target.clearDirty(readFromAlt); + } int filter = GL11.GL_LINEAR_MIPMAP_LINEAR; if (target.getInternalFormat().getPixelFormat().isInteger()) { @@ -354,6 +435,7 @@ public class CompositeRenderer { Objects.requireNonNull(flipped); ProgramBuilder builder; + final long _cpStart = System.nanoTime(); try { builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); @@ -361,12 +443,60 @@ public class CompositeRenderer { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } + final long _afterBegin = System.nanoTime(); CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); this.customUniforms.assignTo(builder); ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline); + IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); + IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); + + IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets); + IrisImages.addCustomImages(builder, customImages); + + IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); + samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); + + if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null); + } + + // TODO: Don't duplicate this with FinalPassRenderer + centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); + final long _afterSamplers = System.nanoTime(); + + Program build = builder.build(); + final long _afterBuild = System.nanoTime(); + + this.customUniforms.mapholderToPass(builder, build); + final long _afterMapholder = System.nanoTime(); + Iris.logger.info("[Load #{}] createProg name={} begin={}ms samplers={}ms build={}ms mapholder={}ms", + Iris.getShaderPackLoadId(), source.getName(), + String.format("%.1f", (_afterBegin - _cpStart) / 1_000_000.0), + String.format("%.1f", (_afterSamplers - _afterBegin) / 1_000_000.0), + String.format("%.1f", (_afterBuild - _afterSamplers) / 1_000_000.0), + String.format("%.1f", (_afterMapholder - _afterBuild) / 1_000_000.0)); + + return build; + } + + private ComputeProgram buildPreRasterCompute(String name, String computeSource, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier) { + PatchedShaderPrinter.debugPatchedShaders(name + "_pre_compute", null, null, null, computeSource); + final ProgramBuilder builder; + try { + builder = ProgramBuilder.beginCompute(name + "_pre", computeSource, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); + } catch (RuntimeException e) { + throw new RuntimeException("Pre-raster compute compilation failed for " + name, e); + } + final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); + + CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); + this.customUniforms.assignTo(builder); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); @@ -382,15 +512,10 @@ public class CompositeRenderer { IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null); } - // TODO: Don't duplicate this with FinalPassRenderer - centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); - - Program build = builder.build(); - - this.customUniforms.mapholderToPass(builder, build); - - return build; - } + final ComputeProgram cp = builder.buildCompute(); + this.customUniforms.mapholderToPass(builder, cp); + return cp; + } private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier) { ComputeProgram[] programs = new ComputeProgram[compute.length]; @@ -418,18 +543,18 @@ public class CompositeRenderer { this.customUniforms.assignTo(builder); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); - IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); + IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets); IrisImages.addCustomImages(builder, customImages); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); - IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); + samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null); } diff --git a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java index dee5b1790..5c95926b9 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java @@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.features.FeatureFlags; @@ -37,6 +38,7 @@ import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.shader.Framebuffer; +import net.minecraft.profiler.Profiler; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; @@ -52,6 +54,8 @@ import java.util.concurrent.CompletionException; import java.util.function.Supplier; public class FinalPassRenderer { + private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS); + private final RenderTargets renderTargets; @Nullable @@ -69,6 +73,11 @@ public class FinalPassRenderer { @Nullable private final Set customImages; @Nullable private final Object2ObjectMap irisCustomTextures; @Nullable private final WorldRenderingPipeline pipeline; + private int samplerUsage; + + public int getSamplerUsage() { + return samplerUsage; + } public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier, ImmutableSet flippedBuffers, @@ -104,6 +113,10 @@ public class FinalPassRenderer { return pass; }).orElse(null); + if (Tracy.ENABLED && finalPass != null) { + Tracy.message("passGraph final/" + stageName + " mipmapped=" + finalPass.mipmappedBuffers + " readsAlt=" + finalPass.stageReadsFromAlt); + } + final IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared(); // The name of this method might seem a bit odd here, but we want a framebuffer with color attachments that line @@ -117,30 +130,29 @@ public class FinalPassRenderer { this.lastColorTextureVersion = ((IRenderTargetExt)main).iris$getColorBufferVersion(); this.colorHolder.addColorAttachment(0, lastColorTextureId); - // TODO: We don't actually fully swap the content, we merely copy it from alt to main - // This works for the most part, but it's not perfect. A better approach would be creating secondary - // framebuffers for every other frame, but that would be a lot more complex... - final ImmutableList.Builder swapPasses = ImmutableList.builder(); + final boolean parityFlip = renderTargets.getParityState() != null && renderTargets.getParityState().isEnabled(); - flippedBuffers.forEach((i) -> { - final int target = i; + if (!parityFlip) { + flippedBuffers.forEach((i) -> { + final int target = i; - if (buffersToBeCleared.contains(target)) { - return; - } + if (buffersToBeCleared.contains(target)) { + return; + } - final SwapPass swap = new SwapPass(); - final RenderTarget target1 = renderTargets.get(target); - swap.target = target; - swap.width = target1.getWidth(); - swap.height = target1.getHeight(); - // Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data - swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target}); - swap.targetTexture = renderTargets.get(target).getMainTexture(); + final SwapPass swap = new SwapPass(); + final RenderTarget target1 = renderTargets.get(target); + swap.target = target; + swap.width = target1.getWidth(); + swap.height = target1.getHeight(); + // Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data + swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target}); + swap.targetTexture = renderTargets.get(target).getMainTexture(); - swapPasses.add(swap); - }); + swapPasses.add(swap); + }); + } this.swapPasses = swapPasses.build(); @@ -215,6 +227,8 @@ public class FinalPassRenderer { colorHolder.addColorAttachment(0, lastColorTextureId); } + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + profiler.startSection("iris_final_program"); if (this.finalPass != null) { // If there is a final pass, we use the shader-based full screen quad rendering pathway instead of just copying the color buffer. @@ -222,8 +236,10 @@ public class FinalPassRenderer { FullScreenQuadRenderer.INSTANCE.begin(); + boolean ranCompute = false; for (ComputeProgram computeProgram : finalPass.computes) { if (computeProgram != null) { + ranCompute = true; computeProgram.use(); this.customUniforms.push(computeProgram); computeProgram.dispatch(baseWidth, baseHeight); @@ -232,11 +248,18 @@ public class FinalPassRenderer { RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); + if (ranCompute) { + for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) { + renderTargets.get(i).markBothDirty(); + } + } + if (!finalPass.mipmappedBuffers.isEmpty()) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + final ImmutableSet readsFromAlt = renderTargets.parityResolve(finalPass.stageReadsFromAlt); for (int index : finalPass.mipmappedBuffers) { - setupMipmapping(renderTargets.get(index), finalPass.stageReadsFromAlt.contains(index)); + setupMipmapping(renderTargets.get(index), readsFromAlt.contains(index)); } } @@ -263,6 +286,7 @@ public class FinalPassRenderer { RenderSystem.copyTexSubImage2D(main.framebufferTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, baseWidth, baseHeight); } + profiler.endSection(); GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); @@ -271,6 +295,8 @@ public class FinalPassRenderer { resetRenderTarget(renderTargets.get(i)); } + profiler.startSection("iris_final_swaps"); + if (Tracy.ENABLED) Tracy.zoneValue(swapPasses.size()); for (SwapPass swapPass : swapPasses) { // NB: We need to use bind(), not bindAsReadBuffer()... Previously we used bindAsReadBuffer() here which // broke TAA on many packs and on many drivers. @@ -285,6 +311,7 @@ public class FinalPassRenderer { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, swapPass.targetTexture); GLStateManager.glCopyTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, swapPass.width, swapPass.height); } + profiler.endSection(); // Make sure to reset the viewport to how it was before... Otherwise weird issues could occur. // Also bind the "main" framebuffer if it isn't already bound. @@ -293,7 +320,8 @@ public class FinalPassRenderer { ProgramSamplers.clearActiveSamplers(); GLStateManager.glUseProgram(0); - for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { + final int maxUnit = Math.min(SamplerLimits.get().getMaxTextureUnits() - 1, GLStateManager.getMaxBoundTextureUnit()); + for (int i = 0; i <= maxUnit; i++) { // Unbind all textures that we may have used. // NB: This is necessary for shader pack reloading to work properly GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); @@ -319,18 +347,18 @@ public class FinalPassRenderer { private static void setupMipmapping(RenderTarget target, boolean readFromAlt) { final int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); - // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer - // (since the last mipmap was generated) - // - // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the - // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a - // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the - // sampling mode is always reset between frames, so this only persists after the first program to use - // mipmapping on this buffer. - // - // Also note that this only applies to one of the two buffers in a render target buffer pair - making it - // unlikely that this issue occurs in practice with most shader packs. - RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + if (target.isDirty(readFromAlt)) { + if (Tracy.ENABLED) { + Tracy.beginZone(Z_GEN_MIPMAP); + Tracy.zoneValue(texture); + } + try { + RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + target.clearDirty(readFromAlt); + } int filter = GL11.GL_LINEAR_MIPMAP_LINEAR; if (target.getInternalFormat().getPixelFormat().isInteger()) { @@ -381,21 +409,21 @@ public class FinalPassRenderer { final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline); // Bind custom images as samplers BEFORE render target images IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); // Bind custom textures (PNG files from shader pack) IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); - IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); + IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets); // Bind custom images as image units AFTER render target images IrisImages.addCustomImages(builder, customImages); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); - IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); + samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null); } @@ -434,18 +462,18 @@ public class FinalPassRenderer { customUniforms.assignTo(builder); CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); - IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); + IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets); IrisImages.addCustomImages(builder, customImages); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); - IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); + samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null); } diff --git a/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java b/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java index 17138ed0c..a9d93e185 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java +++ b/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java @@ -3,7 +3,7 @@ package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; diff --git a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java b/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java index ef8d5b0a4..951cec29b 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java +++ b/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java @@ -3,6 +3,7 @@ package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.compat.mojang.NativeImage; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.shaderpack.texture.CustomTextureData; +import net.coderbot.iris.shaderpack.texture.TextureFilteringData; import net.minecraft.client.renderer.texture.DynamicTexture; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -12,23 +13,27 @@ import java.nio.ByteBuffer; public class NativeImageBackedCustomTexture extends DynamicTexture { public NativeImageBackedCustomTexture(CustomTextureData.PngData textureData) throws IOException { - super(create(textureData.getContent())); + this(decode(textureData.getContent()), textureData.getFilteringData()); + } + + public NativeImageBackedCustomTexture(NativeImage image, TextureFilteringData filtering) { + super(image); // By default, images are unblurred and not clamped. - if (textureData.getFilteringData().shouldBlur()) { + if (filtering.shouldBlur()) { RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); } - if (textureData.getFilteringData().shouldClamp()) { + if (filtering.shouldClamp()) { RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } } - private static NativeImage create(byte[] content) throws IOException { - ByteBuffer buffer = ByteBuffer.allocateDirect(content.length); + public static NativeImage decode(byte[] content) throws IOException { + final ByteBuffer buffer = ByteBuffer.allocateDirect(content.length); buffer.put(content); buffer.flip(); diff --git a/src/main/java/net/coderbot/iris/rendertarget/ParityFlipState.java b/src/main/java/net/coderbot/iris/rendertarget/ParityFlipState.java new file mode 100644 index 000000000..4fe9f37a2 --- /dev/null +++ b/src/main/java/net/coderbot/iris/rendertarget/ParityFlipState.java @@ -0,0 +1,99 @@ +package net.coderbot.iris.rendertarget; + +import com.google.common.collect.ImmutableSet; +import it.unimi.dsi.fastutil.ints.IntList; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public final class ParityFlipState { + + private boolean enabled; + private boolean finalized; + private boolean odd; + private ImmutableSet parityBuffers = ImmutableSet.of(); + private final Map, ImmutableSet> oddSets = new HashMap<>(); + private final Function, ImmutableSet> xorParityFn = this::xorParity; + + public ParityFlipState(boolean enabled) { + this.enabled = enabled; + } + + public boolean isEnabled() { + return enabled; + } + + public boolean isFinalized() { + return finalized; + } + + public boolean isOdd() { + return odd; + } + + public ImmutableSet parityBuffers() { + return parityBuffers; + } + + public void finalizeParitySet(ImmutableSet finalFlipped, IntList buffersToBeCleared) { + finalized = true; + if (!enabled) { + return; + } + final ImmutableSet.Builder builder = ImmutableSet.builder(); + for (int buffer : finalFlipped) { + if (!buffersToBeCleared.contains(buffer)) { + builder.add(buffer); + } + } + parityBuffers = builder.build(); + if (parityBuffers.isEmpty()) { + enabled = false; + } + } + + public void onFrameStart() { + if (enabled && finalized) { + odd = !odd; + } + } + + public void reset() { + odd = false; + } + + public ImmutableSet resolve(ImmutableSet even) { + if (!odd) { + return even; + } + return oddSets.computeIfAbsent(even, xorParityFn); + } + + private ImmutableSet xorParity(ImmutableSet even) { + final ImmutableSet.Builder builder = ImmutableSet.builder(); + for (int buffer : even) { + if (!parityBuffers.contains(buffer)) { + builder.add(buffer); + } + } + for (int buffer : parityBuffers) { + if (!even.contains(buffer)) { + builder.add(buffer); + } + } + return builder.build(); + } + + public boolean affectsAny(int[] drawBuffers) { + if (!enabled) { + return false; + } + for (int buffer : drawBuffers) { + if (parityBuffers.contains(buffer)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java b/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java index 175d77f6a..2a091d2c0 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java +++ b/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java @@ -6,9 +6,9 @@ import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import lombok.Getter; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; import org.joml.Vector2i; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; @@ -30,6 +30,8 @@ public class RenderTarget { private boolean isValid; private final int mainTexture; private final int altTexture; + private boolean mainDirty = true; + private boolean altDirty = true; private static final ByteBuffer NULL_BUFFER = null; @@ -87,6 +89,26 @@ public class RenderTarget { resizeTexture(mainTexture, width, height); resizeTexture(altTexture, width, height); + + mainDirty = true; + altDirty = true; + } + + public void markDirty(boolean isAlt) { + if (isAlt) altDirty = true; else mainDirty = true; + } + + public void markBothDirty() { + mainDirty = true; + altDirty = true; + } + + public boolean isDirty(boolean isAlt) { + return isAlt ? altDirty : mainDirty; + } + + public void clearDirty(boolean isAlt) { + if (isAlt) altDirty = false; else mainDirty = false; } public int getMainTexture() { diff --git a/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java b/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java index 0b2490403..f5cddc69f 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java +++ b/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java @@ -3,10 +3,14 @@ package net.coderbot.iris.rendertarget; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import lombok.Getter; +import net.minecraft.client.Minecraft; +import net.minecraft.profiler.Profiler; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import net.coderbot.iris.gl.framebuffer.ParityFramebuffer; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; import net.coderbot.iris.gl.texture.DepthCopyStrategy; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; @@ -32,6 +36,8 @@ public class RenderTargets { private DepthCopyStrategy copyStrategy; private final List ownedFramebuffers; + private ParityFlipState parity; + private final List pendingParity = new ArrayList<>(); private int cachedWidth; private int cachedHeight; @@ -60,7 +66,8 @@ public class RenderTargets { }); this.currentDepthTexture = depthTexture; this.currentDepthFormat = depthFormat; - this.copyStrategy = DepthCopyStrategy.fastest(currentDepthFormat.isCombinedStencil()); + this.copyStrategy = DepthCopyStrategy.fastest(copyDepthFormat().isCombinedStencil()); + if (Tracy.ENABLED) Tracy.message("depth copy strategy: " + copyStrategy.getClass().getSimpleName()); this.cachedWidth = width; this.cachedHeight = height; @@ -74,8 +81,8 @@ public class RenderTargets { this.depthSourceFb = createFramebufferWritingToMain(new int[] {0}); - this.noTranslucents = new DepthTexture(width, height, currentDepthFormat); - this.noHand = new DepthTexture(width, height, currentDepthFormat); + this.noTranslucents = new DepthTexture(width, height, copyDepthFormat()); + this.noHand = new DepthTexture(width, height, copyDepthFormat()); this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[] {0}); this.noTranslucentsDestFb.addDepthAttachment(this.noTranslucents.getTextureId()); @@ -134,7 +141,8 @@ public class RenderTargets { if (depthFormatChanged) { currentDepthFormat = newDepthFormat; // Might need a new copy strategy - copyStrategy = DepthCopyStrategy.fastest(currentDepthFormat.isCombinedStencil()); + copyStrategy = DepthCopyStrategy.fastest(copyDepthFormat().isCombinedStencil()); + if (Tracy.ENABLED) Tracy.message("depth copy strategy: " + copyStrategy.getClass().getSimpleName()); } if (recreateDepth) { @@ -160,8 +168,8 @@ public class RenderTargets { if (depthFormatChanged || sizeChanged) { // Reallocate depth buffers - noTranslucents.resize(newWidth, newHeight, newDepthFormat); - noHand.resize(newWidth, newHeight, newDepthFormat); + noTranslucents.resize(newWidth, newHeight, copyDepthFormat()); + noHand.resize(newWidth, newHeight, copyDepthFormat()); this.translucentDepthDirty = true; this.handDepthDirty = true; } @@ -181,22 +189,28 @@ public class RenderTargets { } public void copyPreTranslucentDepth() { - if (translucentDepthDirty) { + if (translucentDepthDirty && !RenderSystem.isGLES()) { translucentDepthDirty = false; + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + profiler.startSection("iris_depth_realloc"); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, noTranslucents.getTextureId()); depthSourceFb.bindAsReadBuffer(); - RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, currentDepthFormat.getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); + RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, copyDepthFormat().getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); + profiler.endSection(); } else { copyStrategy.copy(depthSourceFb, getDepthTexture(), noTranslucentsDestFb, noTranslucents.getTextureId(), getCurrentWidth(), getCurrentHeight()); } } public void copyPreHandDepth() { - if (handDepthDirty) { + if (handDepthDirty && !RenderSystem.isGLES()) { handDepthDirty = false; + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + profiler.startSection("iris_depth_realloc"); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, noHand.getTextureId()); depthSourceFb.bindAsReadBuffer(); - RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, currentDepthFormat.getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); + RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, copyDepthFormat().getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); + profiler.endSection(); } else { copyStrategy.copy(depthSourceFb, getDepthTexture(), noHandDestFb, noHand.getTextureId(), getCurrentWidth(), getCurrentHeight()); } @@ -297,9 +311,31 @@ public class RenderTargets { throw new IllegalArgumentException("Framebuffer must have at least one color buffer"); } - final GlFramebuffer framebuffer = new GlFramebuffer(); - ownedFramebuffers.add(framebuffer); + if (parity == null || !parity.isEnabled()) { + final GlFramebuffer framebuffer = new GlFramebuffer(); + ownedFramebuffers.add(framebuffer); + attachColor(framebuffer, stageWritesToMain, drawBuffers, false); + return framebuffer; + } + final ParityFramebuffer framebuffer = new ParityFramebuffer(parity); + ownedFramebuffers.add(framebuffer); + attachColor(framebuffer, stageWritesToMain, drawBuffers, false); + if (!parity.isFinalized()) { + pendingParity.add(new PendingParityFramebuffer(framebuffer, stageWritesToMain, drawBuffers)); + } else if (parity.affectsAny(drawBuffers)) { + framebuffer.setOdd(buildOddVariant(stageWritesToMain, drawBuffers)); + } + return framebuffer; + } + + private GlFramebuffer buildOddVariant(ImmutableSet stageWritesToMain, int[] drawBuffers) { + final GlFramebuffer odd = new GlFramebuffer(); + attachColor(odd, stageWritesToMain, drawBuffers, true); + return odd; + } + + private void attachColor(GlFramebuffer framebuffer, ImmutableSet stageWritesToMain, int[] drawBuffers, boolean flipParityBuffers) { final int[] actualDrawBuffers = new int[drawBuffers.length]; for (int i = 0; i < drawBuffers.length; i++) { @@ -313,20 +349,61 @@ public class RenderTargets { final RenderTarget target = this.get(drawBuffers[i]); - final int textureId = stageWritesToMain.contains(drawBuffers[i]) ? target.getMainTexture() : target.getAltTexture(); - - framebuffer.addColorAttachment(i, textureId); + boolean writesToMain = stageWritesToMain.contains(drawBuffers[i]); + if (flipParityBuffers && parity.parityBuffers().contains(drawBuffers[i])) { + writesToMain = !writesToMain; + } + framebuffer.addColorAttachment(i, writesToMain ? target.getMainTexture() : target.getAltTexture()); } framebuffer.drawBuffers(actualDrawBuffers); framebuffer.readBuffer(0); - final int status = framebuffer.getStatus(); - if (status != GL30.GL_FRAMEBUFFER_COMPLETE) { - throw new IllegalStateException(String.format( "Unexpected error while creating framebuffer: glCheckFramebufferStatus=0x%X, size=%dx%d, drawBuffers=%d", status, cachedWidth, cachedHeight, drawBuffers.length)); + if (GLStateManager.framebufferCompletenessIsMeaningful()) { + final int status = framebuffer.getStatus(); + if (status != GL30.GL_FRAMEBUFFER_COMPLETE) { + throw new IllegalStateException(String.format("Unexpected error while creating framebuffer: glCheckFramebufferStatus=0x%X, size=%dx%d, drawBuffers=%d", status, cachedWidth, cachedHeight, drawBuffers.length)); + } } + } - return framebuffer; + public void setParityState(ParityFlipState parity) { + this.parity = parity; + } + + public ParityFlipState getParityState() { + return parity; + } + + public ImmutableSet parityResolve(ImmutableSet even) { + return parity != null ? parity.resolve(even) : even; + } + + public void finalizeParity() { + if (parity != null) { + for (PendingParityFramebuffer pending : pendingParity) { + if (parity.isEnabled() && parity.affectsAny(pending.drawBuffers)) { + final GlFramebuffer odd = buildOddVariant(pending.stageWritesToMain, pending.drawBuffers); + if (pending.framebuffer.hasDepthAttachment()) { + odd.addDepthAttachment(currentDepthTexture); + } + pending.framebuffer.setOdd(odd); + } + } + } + pendingParity.clear(); + } + + private static final class PendingParityFramebuffer { + final ParityFramebuffer framebuffer; + final ImmutableSet stageWritesToMain; + final int[] drawBuffers; + + PendingParityFramebuffer(ParityFramebuffer framebuffer, ImmutableSet stageWritesToMain, int[] drawBuffers) { + this.framebuffer = framebuffer; + this.stageWritesToMain = stageWritesToMain; + this.drawBuffers = drawBuffers; + } } public void destroyFramebuffer(GlFramebuffer framebuffer) { @@ -334,6 +411,10 @@ public class RenderTargets { ownedFramebuffers.remove(framebuffer); } + private DepthBufferFormat copyDepthFormat() { + return GLStateManager.capabilities.GL_ARB_copy_image ? currentDepthFormat : currentDepthFormat.stripStencil(); + } + public int getCurrentWidth() { return cachedWidth; } diff --git a/src/main/java/net/coderbot/iris/samplers/IrisImages.java b/src/main/java/net/coderbot/iris/samplers/IrisImages.java index 4b7f68531..9b11a15ee 100644 --- a/src/main/java/net/coderbot/iris/samplers/IrisImages.java +++ b/src/main/java/net/coderbot/iris/samplers/IrisImages.java @@ -3,7 +3,7 @@ package net.coderbot.iris.samplers; import com.google.common.collect.ImmutableSet; import net.coderbot.iris.gl.image.GlImage; import net.coderbot.iris.gl.image.ImageHolder; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.rendertarget.RenderTargets; import net.coderbot.iris.shadows.ShadowRenderTargets; diff --git a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java b/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java index d990fb794..473934a75 100644 --- a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java +++ b/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java @@ -10,7 +10,7 @@ import net.coderbot.iris.gl.sampler.GlSampler; import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.rendertarget.RenderTargets; @@ -33,6 +33,10 @@ public class IrisSamplers { // We need a way to restore these texture bindings. public static final ImmutableSet COMPOSITE_RESERVED_TEXTURE_UNITS = ImmutableSet.of(1); + public static final int USAGE_DEPTHTEX1 = 1; + public static final int USAGE_DEPTHTEX2 = 2; + public static final int USAGE_SHADOWTEX1 = 4; + private static GlSampler SHADOW_SAMPLER_NEAREST; private static GlSampler SHADOW_SAMPLER_LINEAR; @@ -120,8 +124,8 @@ public class IrisSamplers { return false; } - public static boolean addShadowSamplers(SamplerHolder samplers, ShadowRenderTargets shadowRenderTargets, ImmutableSet flipped, boolean separateHardwareSamplers) { - boolean usesShadows; + public static int addShadowSamplers(SamplerHolder samplers, ShadowRenderTargets shadowRenderTargets, ImmutableSet flipped, boolean separateHardwareSamplers) { + int usage = 0; // TODO: figure this out from parsing the shader source code to be 100% compatible with the legacy // shader packs that rely on this behavior. @@ -133,12 +137,15 @@ public class IrisSamplers { final GlSampler sampler1 = separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(1) ? (shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST) : null); if (waterShadowEnabled) { - usesShadows = true; samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "watershadow"); - samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1", "shadow"); + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1", "shadow")) { + usage |= USAGE_SHADOWTEX1; + } } else { - usesShadows = samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "shadow"); - usesShadows |= samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "shadow"); + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1")) { + usage |= USAGE_SHADOWTEX1; + } } // Shadow color textures with flip support @@ -174,10 +181,12 @@ public class IrisSamplers { if (shadowRenderTargets.isHardwareFiltered(1) && separateHardwareSamplers) { final GlSampler hwSampler1 = shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST; - samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, hwSampler1, "shadowtex1HW"); + if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, hwSampler1, "shadowtex1HW")) { + usage |= USAGE_SHADOWTEX1; + } } - return usesShadows; + return usage; } public static boolean hasPBRSamplers(SamplerHolder samplers) { @@ -202,16 +211,26 @@ public class IrisSamplers { samplers.addDynamicSampler(pipeline::getCurrentSpecularTexture, StateUpdateNotifiers.specularTextureChangeNotifier, "specular"); } - public static void addWorldDepthSamplers(SamplerHolder samplers, RenderTargets renderTargets) { + public static int addWorldDepthSamplers(SamplerHolder samplers, RenderTargets renderTargets) { + int usage = 0; samplers.addDynamicSampler(renderTargets::getDepthTexture, "depthtex0"); // TODO: Should depthtex2 be made available to gbuffer / shadow programs? - samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1"); + if (samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1")) { + usage |= USAGE_DEPTHTEX1; + } + return usage; } - public static void addCompositeSamplers(SamplerHolder samplers, RenderTargets renderTargets) { + public static int addCompositeSamplers(SamplerHolder samplers, RenderTargets renderTargets) { + int usage = 0; samplers.addDynamicSampler(renderTargets::getDepthTexture, "gdepthtex", "depthtex0"); - samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1"); - samplers.addDynamicSampler(renderTargets.getDepthTextureNoHand()::getTextureId, "depthtex2"); + if (samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1")) { + usage |= USAGE_DEPTHTEX1; + } + if (samplers.addDynamicSampler(renderTargets.getDepthTextureNoHand()::getTextureId, "depthtex2")) { + usage |= USAGE_DEPTHTEX2; + } + return usage; } public static void addCustomTextures(SamplerHolder samplers, Object2ObjectMap irisCustomTextures) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java b/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java index b1e368351..2044c32fe 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java +++ b/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java @@ -11,7 +11,7 @@ import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.buffer.ShaderStorageInfo; import net.coderbot.iris.gl.texture.TextureScaleOverride; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import net.coderbot.iris.helpers.Tri; import net.coderbot.iris.shaderpack.texture.TextureStage; import org.joml.Vector2i; @@ -19,6 +19,8 @@ import org.joml.Vector2i; import java.util.Optional; import java.util.Set; +import static org.joml.Math.clamp; + public class PackDirectives { @Getter private int noiseTextureResolution; @Getter private float sunPathRotation; @@ -188,17 +190,13 @@ public class PackDirectives { return dhCloudSetting; } - private static float clamp(float val, float lo, float hi) { - return Math.max(lo, Math.min(hi, val)); - } - public void acceptDirectivesFrom(DirectiveHolder directives) { renderTargetDirectives.acceptDirectives(directives); shadowDirectives.acceptDirectives(directives); directives.acceptConstIntDirective("noiseTextureResolution", noiseTextureResolution -> this.noiseTextureResolution = noiseTextureResolution); directives.acceptConstFloatDirective("sunPathRotation", sunPathRotation -> this.sunPathRotation = sunPathRotation); - directives.acceptConstFloatDirective("ambientOcclusionLevel", ambientOcclusionLevel -> this.ambientOcclusionLevel = clamp(ambientOcclusionLevel, 0.0f, 1.0f)); + directives.acceptConstFloatDirective("ambientOcclusionLevel", ambientOcclusionLevel -> this.ambientOcclusionLevel = clamp(0.0f, 1.0f, ambientOcclusionLevel)); directives.acceptConstFloatDirective("wetnessHalflife", wetnessHalfLife -> this.wetnessHalfLife = wetnessHalfLife); directives.acceptConstFloatDirective("drynessHalflife", wetnessHalfLife -> this.wetnessHalfLife = wetnessHalfLife); directives.acceptConstFloatDirective("eyeBrightnessHalflife", eyeBrightnessHalfLife -> this.eyeBrightnessHalfLife = eyeBrightnessHalfLife); diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java b/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java index 039f6f9e9..39587bc1f 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java +++ b/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java @@ -7,7 +7,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; import org.joml.Vector4f; import java.util.Collections; diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java b/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java index 55902a291..f7afaccd3 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java +++ b/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java @@ -3,7 +3,7 @@ package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableList; import lombok.Getter; import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; import org.joml.Vector4f; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java b/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java index 11c3f6f50..f5a63e9e1 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java +++ b/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java @@ -14,6 +14,8 @@ import net.coderbot.iris.features.FeatureFlags; import net.coderbot.iris.gl.buffer.ShaderStorageInfo; import net.coderbot.iris.gl.image.ImageInformation; import net.coderbot.iris.gl.texture.TextureDefinition; +import net.coderbot.iris.pipeline.transform.SamplerToStorageImageRewriter; +import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor; import net.coderbot.iris.shaderpack.include.AbsolutePackPath; import net.coderbot.iris.shaderpack.include.IncludeGraph; import net.coderbot.iris.shaderpack.include.IncludeProcessor; @@ -229,7 +231,7 @@ public class ShaderPack { } Iris.logger.info("Environment defines: {}", finalEnvironmentDefines.stream() .map(p -> p.getKey() + "=" + p.getValue()) - .collect(java.util.stream.Collectors.joining(", "))); + .collect(Collectors.joining(", "))); this.shaderProperties = Optional.ofNullable(readProperties(root, "shaders.properties")) .map(source -> new ShaderProperties(source, shaderPackOptions, finalEnvironmentDefines)) @@ -364,6 +366,9 @@ public class ShaderPack { this.customUniforms = shaderProperties.getCustomUniforms(); this.customImages = shaderProperties.getCustomImages(); this.bufferObjects = shaderProperties.getBufferObjects(); + + SamplerToStorageImageRewriter.setActiveCandidates(SamplerToStorageImageRewriter.buildCandidates(this.customImages.values())); + RwImageStoreExtractor.setActiveCustomImages(this.customImages); } private String getCurrentProfileName() { diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java index 7511d0092..5619077fb 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java +++ b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java @@ -12,15 +12,15 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.coderbot.iris.gl.buffer.ShaderStorageInfo; import net.coderbot.iris.gl.framebuffer.ViewportData; import net.coderbot.iris.gl.image.ImageInformation; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; import net.coderbot.iris.gl.texture.TextureDefinition; -import net.coderbot.iris.gl.texture.TextureType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.blending.AlphaTestFunction; +import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction; import net.coderbot.iris.gl.blending.AlphaTestOverride; import net.coderbot.iris.gl.blending.BlendModeFunction; import net.coderbot.iris.gl.blending.BlendModeOverride; diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java b/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java index 48196cb9a..4632dc32d 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java +++ b/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java @@ -2,7 +2,7 @@ package net.coderbot.iris.shaderpack.loading; import com.gtnewhorizons.angelica.glsm.states.BlendState; import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.blending.AlphaTestFunction; +import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction; import net.coderbot.iris.gl.blending.AlphaTestOverride; import net.coderbot.iris.gl.blending.BlendModeOverride; import org.lwjgl.opengl.GL11; @@ -32,7 +32,7 @@ public enum ProgramId { DamagedBlock(ProgramGroup.Gbuffers, "damagedblock", Terrain), Block(ProgramGroup.Gbuffers, "block", Terrain), - BlockTrans(ProgramGroup.Gbuffers, "block_translucent", Block, BlendModeOverride.OFF), + BlockTrans(ProgramGroup.Gbuffers, "block_translucent", Block), BeaconBeam(ProgramGroup.Gbuffers, "beaconbeam", Textured), Item(ProgramGroup.Gbuffers, "item", TexturedLit), diff --git a/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java b/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java index c607aaf8c..9fe9de111 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java +++ b/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java @@ -1,9 +1,9 @@ package net.coderbot.iris.shaderpack.texture; import lombok.Getter; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; public abstract class CustomTextureData { CustomTextureData() { diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java b/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java index afd43d9ec..fa8b9fcc3 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java @@ -3,8 +3,10 @@ package net.coderbot.iris.shadows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.features.FeatureFlags; import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder; @@ -21,7 +23,10 @@ import net.coderbot.iris.gl.texture.TextureAccess; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.pipeline.transform.PatchShaderType; +import net.coderbot.iris.pipeline.transform.PreRasterComputeDispatcher; +import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor; import net.coderbot.iris.pipeline.transform.TransformPatcher; +import org.lwjgl.opengl.GL20; import net.coderbot.iris.postprocess.FullScreenQuadRenderer; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.samplers.IrisImages; @@ -38,6 +43,7 @@ import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.shader.Framebuffer; +import net.minecraft.profiler.Profiler; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; @@ -51,6 +57,8 @@ import java.util.Set; public class ShadowCompositeRenderer { + private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS); + private final ShadowRenderTargets renderTargets; private final ImmutableList passes; @@ -64,6 +72,11 @@ public class ShadowCompositeRenderer { private final Set irisCustomImages; @Nullable private final ShaderStorageBufferHolder ssboHolder; + private int samplerUsage; + + public int getSamplerUsage() { + return samplerUsage; + } public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, ShadowRenderTargets renderTargets, @Nullable ShaderStorageBufferHolder ssboHolder, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier, @@ -101,6 +114,7 @@ public class ShadowCompositeRenderer { if (source == null || !source.isValid()) { if (computes[i] != null) { ComputeOnlyPass pass = new ComputeOnlyPass(); + pass.name = computeOnlyPassName(computes[i], i); pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets); passes.add(pass); } @@ -108,9 +122,26 @@ public class ShadowCompositeRenderer { } Pass pass = new Pass(); + pass.name = "iris_" + source.getName(); ProgramDirectives directives = source.getDirectives(); - pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, renderTargets); + final Map transformed = TransformPatcher.patchComposite( + source.getVertexSource().orElseThrow(NullPointerException::new), + source.getGeometrySource().orElse(null), + source.getTessControlSource().orElse(null), + source.getTessEvalSource().orElse(null), + source.getFragmentSource().orElseThrow(NullPointerException::new), + TextureStage.SHADOWCOMP, + pipeline.getTextureMap()); + pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, renderTargets); + final String preComputeSrc = transformed.get(PatchShaderType.COMPUTE); + if (preComputeSrc != null) { + pass.preRasterMode = RwImageStoreExtractor.parseSentinel(preComputeSrc); + if (pass.preRasterMode != null) { + pass.preRasterCompute = buildPreRasterCompute(source.getName(), preComputeSrc, + flipped, flippedAtLeastOnceSnapshot, renderTargets); + } + } pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets); int[] drawBuffers = directives.hasUnknownDrawBuffers() ? new int[] { 0, 1 } : directives.getDrawBuffers(); @@ -169,7 +200,15 @@ public class ShadowCompositeRenderer { // // Also note that this only applies to one of the two buffers in a render target buffer pair - making it // unlikely that this issue occurs in practice with most shader packs. - RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + if (Tracy.ENABLED) { + Tracy.beginZone(Z_GEN_MIPMAP); + Tracy.zoneValue(texture); + } + try { + RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, target.getInternalFormat().getPixelFormat().isInteger() ? GL11.GL_NEAREST_MIPMAP_NEAREST : GL11.GL_LINEAR_MIPMAP_LINEAR); } @@ -195,7 +234,11 @@ public class ShadowCompositeRenderer { FullScreenQuadRenderer.INSTANCE.begin(); + final Profiler profiler = Minecraft.getMinecraft().mcProfiler; + for (Pass renderPass : passes) { + profiler.startSection(renderPass.name); + GLDebug.pushGroup(renderPass.name); boolean ranCompute = false; for (ComputeProgram computeProgram : renderPass.computes) { if (computeProgram != null) { @@ -215,6 +258,8 @@ public class ShadowCompositeRenderer { Program.unbind(); if (renderPass instanceof ComputeOnlyPass) { + GLDebug.popGroup(); + profiler.endSection(); continue; } @@ -232,12 +277,18 @@ public class ShadowCompositeRenderer { int beginHeight = (int) (renderTargets.getResolution() * renderPass.viewportScale.viewportY()); GLStateManager.glViewport(beginWidth, beginHeight, (int) scaledWidth, (int) scaledHeight); + if (renderPass.preRasterCompute != null && renderPass.preRasterMode != null) { + dispatchPreRasterCompute(renderPass, (int) scaledWidth, (int) scaledHeight); + } + renderPass.framebuffer.bind(); renderPass.program.use(); this.customUniforms.push(renderPass.program); FullScreenQuadRenderer.INSTANCE.renderQuad(); + GLDebug.popGroup(); + profiler.endSection(); } FullScreenQuadRenderer.INSTANCE.end(); @@ -256,17 +307,9 @@ public class ShadowCompositeRenderer { } // TODO: Don't just copy this from DeferredWorldRenderingPipeline - private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, + private Program createProgramFromTransformed(ProgramSource source, Map transformed, + ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, ShadowRenderTargets targets) { - // TODO: Properly handle empty shaders - Map transformed = TransformPatcher.patchComposite( - source.getVertexSource().orElseThrow(NullPointerException::new), - source.getGeometrySource().orElse(null), - source.getTessControlSource().orElse(null), - source.getTessEvalSource().orElse(null), - source.getFragmentSource().orElseThrow(NullPointerException::new), - TextureStage.SHADOWCOMP, - pipeline.getTextureMap()); String vertex = transformed.get(PatchShaderType.VERTEX); String geometry = transformed.get(PatchShaderType.GEOMETRY); String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); @@ -295,7 +338,7 @@ public class ShadowCompositeRenderer { IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); IrisImages.addShadowColorImages(builder, targets, flipped); IrisImages.addCustomImages(builder, irisCustomImages); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, irisCustomImages); @@ -305,6 +348,36 @@ public class ShadowCompositeRenderer { return build; } + private ComputeProgram buildPreRasterCompute(String name, String computeSource, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, ShadowRenderTargets targets) { + PatchedShaderPrinter.debugPatchedShaders(name + "_pre_compute", null, null, null, computeSource); + final ProgramBuilder builder; + try { + builder = ProgramBuilder.beginCompute(name + "_pre", computeSource, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); + } catch (RuntimeException e) { + throw new RuntimeException("Pre-raster compute compilation failed for shadow composite " + name, e); + } + final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = + ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); + + CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); + this.customUniforms.assignTo(builder); + + IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); + IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); + IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + IrisImages.addShadowColorImages(builder, targets, flipped); + IrisImages.addCustomImages(builder, irisCustomImages); + IrisSamplers.addCustomImages(customTextureSamplerInterceptor, irisCustomImages); + + final ComputeProgram cp = builder.buildCompute(); + this.customUniforms.mapholderToPass(builder, cp); + return cp; + } + + private void dispatchPreRasterCompute(Pass pass, int width, int height) { + pass.preRasterTargetSizeLoc = PreRasterComputeDispatcher.dispatch(pass.preRasterCompute, pass.preRasterMode, pass.preRasterTargetSizeLoc, width, height, this.customUniforms); + } + private ComputeProgram[] createComputes(ComputeSource[] sources, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, ShadowRenderTargets targets) { if (sources == null) { @@ -340,7 +413,7 @@ public class ShadowCompositeRenderer { IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures); - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); + samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS)); IrisImages.addShadowColorImages(builder, targets, flipped); IrisImages.addCustomImages(builder, irisCustomImages); @@ -365,8 +438,18 @@ public class ShadowCompositeRenderer { } } + private static String computeOnlyPassName(ComputeSource[] computes, int index) { + for (ComputeSource compute : computes) { + if (compute != null) { + return "iris_" + compute.getName(); + } + } + return "iris_shadowcomp_compute" + index; + } + private static class Pass { + String name; Program program; GlFramebuffer framebuffer; ImmutableSet flippedAtLeastOnce; @@ -374,6 +457,9 @@ public class ShadowCompositeRenderer { ImmutableSet mipmappedBuffers; ViewportData viewportScale; ComputeProgram[] computes; + @Nullable ComputeProgram preRasterCompute; + @Nullable RwImageStoreExtractor.RwExtractMode preRasterMode; + int preRasterTargetSizeLoc = -2; protected void destroy() { this.program.destroy(); @@ -382,6 +468,10 @@ public class ShadowCompositeRenderer { compute.destroy(); } } + if (this.preRasterCompute != null) { + this.preRasterCompute.destroy(); + this.preRasterCompute = null; + } } } diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowGraphGate.java b/src/main/java/net/coderbot/iris/shadows/ShadowGraphGate.java new file mode 100644 index 000000000..41938e4a9 --- /dev/null +++ b/src/main/java/net/coderbot/iris/shadows/ShadowGraphGate.java @@ -0,0 +1,15 @@ +package net.coderbot.iris.shadows; + +public final class ShadowGraphGate { + + public static final float SHADOW_ANGLE_GRAPH_DELTA = 0.0005f; + + private ShadowGraphGate() {} + + public static boolean shouldMarkDirty(float last, float current) { + float delta = current - last; + if (delta > 0.5f) delta -= 1.0f; + if (delta < -0.5f) delta += 1.0f; + return Float.isNaN(last) || Math.abs(delta) > SHADOW_ANGLE_GRAPH_DELTA; + } +} diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java b/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java index e4b0c5400..30f5f3d82 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java +++ b/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java @@ -1,21 +1,26 @@ package net.coderbot.iris.shadows; import com.google.common.collect.ImmutableSet; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat; import net.coderbot.iris.gl.texture.DepthCopyStrategy; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; import net.coderbot.iris.rendertarget.DepthTexture; import net.coderbot.iris.features.FeatureFlags; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.shaderpack.PackShadowDirectives; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL30; +import java.nio.ByteBuffer; + import java.util.ArrayList; import java.util.List; @@ -26,6 +31,7 @@ public class ShadowRenderTargets { private final DepthTexture noTranslucents; private final GlFramebuffer depthSourceFb; private final GlFramebuffer noTranslucentsDestFb; + private final DepthCopyStrategy copyStrategy = DepthCopyStrategy.fastest(false); private final boolean[] flipped; private final List ownedFramebuffers; @@ -33,6 +39,12 @@ public class ShadowRenderTargets { private boolean fullClearRequired; private boolean translucentDepthDirty; + private DepthTexture terrainDepthCache; + private GlFramebuffer terrainDepthCacheFb; + private int[] terrainColorCache; + private GlFramebuffer[] terrainColorSrcFb; + private GlFramebuffer[] terrainColorCacheFb; + private boolean terrainSnapshotValid; private final boolean[] hardwareFiltered; private final boolean[] linearFiltered; private final InternalTextureFormat[] formats; @@ -93,6 +105,7 @@ public class ShadowRenderTargets { } fullClearRequired = true; + terrainSnapshotValid = false; } public void createIfEmpty(int index) { @@ -128,6 +141,17 @@ public class ShadowRenderTargets { mainDepth.destroy(); noTranslucents.destroy(); + if (terrainDepthCache != null) { + terrainDepthCache.destroy(); + terrainDepthCache = null; + } + if (terrainColorCache != null) { + for (int tex : terrainColorCache) { + if (tex != 0) GLStateManager.glDeleteTextures(tex); + } + terrainColorCache = null; + } + terrainSnapshotValid = false; } public int getRenderTargetCount() { @@ -160,11 +184,67 @@ public class ShadowRenderTargets { RenderSystem.blitFramebuffer(depthSourceFb.getId(), noTranslucentsDestFb.getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); } else { - DepthCopyStrategy.fastest(false).copy(depthSourceFb, mainDepth.getTextureId(), noTranslucentsDestFb, noTranslucents.getTextureId(), + copyStrategy.copy(depthSourceFb, mainDepth.getTextureId(), noTranslucentsDestFb, noTranslucents.getTextureId(), resolution, resolution); } } + public boolean isTerrainSnapshotValid() { + return terrainSnapshotValid; + } + + public void captureTerrainSnapshot() { + ensureTerrainCaches(); + RenderSystem.blitFramebuffer(depthSourceFb.getId(), terrainDepthCacheFb.getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + for (int i = 0; i < targets.length; i++) { + if (targets[i] == null) continue; + RenderSystem.blitFramebuffer(terrainColorSrcFb[i].getId(), terrainColorCacheFb[i].getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_COLOR_BUFFER_BIT, GL11.GL_NEAREST); + } + terrainSnapshotValid = true; + } + + public void restoreTerrainSnapshot() { + RenderSystem.blitFramebuffer(terrainDepthCacheFb.getId(), depthSourceFb.getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + for (int i = 0; i < targets.length; i++) { + if (targets[i] == null || terrainColorCacheFb == null || terrainColorCacheFb[i] == null) continue; + RenderSystem.blitFramebuffer(terrainColorCacheFb[i].getId(), terrainColorSrcFb[i].getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_COLOR_BUFFER_BIT, GL11.GL_NEAREST); + } + } + + private void ensureTerrainCaches() { + if (terrainDepthCache == null) { + terrainDepthCache = new DepthTexture(resolution, resolution, DepthBufferFormat.DEPTH); + terrainDepthCacheFb = new GlFramebuffer(); + ownedFramebuffers.add(terrainDepthCacheFb); + terrainDepthCacheFb.addDepthAttachment(terrainDepthCache.getTextureId()); + } + if (terrainColorCache == null) { + terrainColorCache = new int[targets.length]; + terrainColorSrcFb = new GlFramebuffer[targets.length]; + terrainColorCacheFb = new GlFramebuffer[targets.length]; + } + for (int i = 0; i < targets.length; i++) { + if (targets[i] == null || terrainColorCache[i] != 0) continue; + terrainColorCache[i] = createCacheTexture(formats[i]); + terrainColorSrcFb[i] = new GlFramebuffer(); + ownedFramebuffers.add(terrainColorSrcFb[i]); + terrainColorSrcFb[i].addColorAttachment(0, targets[i].getMainTexture()); + terrainColorCacheFb[i] = new GlFramebuffer(); + ownedFramebuffers.add(terrainColorCacheFb[i]); + terrainColorCacheFb[i].addColorAttachment(0, terrainColorCache[i]); + } + } + + private int createCacheTexture(InternalTextureFormat format) { + final int tex = GLStateManager.glGenTextures(); + RenderSystem.texImage2D(tex, GL11.GL_TEXTURE_2D, 0, format.getGlFormat(), resolution, resolution, 0, format.getPixelFormat().getGlFormat(), PixelType.UNSIGNED_BYTE.getGlFormat(), (ByteBuffer) null); + RenderSystem.texParameteri(tex, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + RenderSystem.texParameteri(tex, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + RenderSystem.texParameteri(tex, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + RenderSystem.texParameteri(tex, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); + return tex; + } + public boolean isFullClearRequired() { return fullClearRequired; } @@ -284,9 +364,11 @@ public class ShadowRenderTargets { framebuffer.drawBuffers(actualDrawBuffers); framebuffer.readBuffer(0); - final int status = framebuffer.getStatus(); - if (status != GL30.GL_FRAMEBUFFER_COMPLETE) { - throw new IllegalStateException(String.format( "Unexpected error while creating shadow framebuffer: glCheckFramebufferStatus=0x%X, resolution=%d, drawBuffers=%d", status, resolution, drawBuffers.length)); + if (GLStateManager.framebufferCompletenessIsMeaningful()) { + final int status = framebuffer.getStatus(); + if (status != GL30.GL_FRAMEBUFFER_COMPLETE) { + throw new IllegalStateException(String.format("Unexpected error while creating shadow framebuffer: glCheckFramebufferStatus=0x%X, resolution=%d, drawBuffers=%d", status, resolution, drawBuffers.length)); + } } return framebuffer; diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java b/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java index 208eceda5..3fcc7764f 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java +++ b/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java @@ -3,8 +3,15 @@ package net.coderbot.iris.shadows.frustum; import net.minecraft.util.AxisAlignedBB; public class BoxCuller { + private static final double SNAP = 16.0; + private static final double PAD = SNAP * 0.5; + private double maxDistance; + private double cameraX; + private double cameraY; + private double cameraZ; + private double minAllowedX; private double maxAllowedX; private double minAllowedY; @@ -12,21 +19,52 @@ public class BoxCuller { private double minAllowedZ; private double maxAllowedZ; + private double minRelX; + private double maxRelX; + private double minRelY; + private double maxRelY; + private double minRelZ; + private double maxRelZ; + public BoxCuller(double maxDistance) { this.maxDistance = maxDistance; } public void setMaxDistance(double maxDistance) { this.maxDistance = maxDistance; + computeBounds(); } public void setPosition(double cameraX, double cameraY, double cameraZ) { - this.minAllowedX = cameraX - maxDistance; - this.maxAllowedX = cameraX + maxDistance; - this.minAllowedY = cameraY - maxDistance; - this.maxAllowedY = cameraY + maxDistance; - this.minAllowedZ = cameraZ - maxDistance; - this.maxAllowedZ = cameraZ + maxDistance; + this.cameraX = cameraX; + this.cameraY = cameraY; + this.cameraZ = cameraZ; + computeBounds(); + } + + private void computeBounds() { + final double centerX = snap(cameraX); + final double centerY = snap(cameraY); + final double centerZ = snap(cameraZ); + final double half = maxDistance + PAD; + + this.minAllowedX = centerX - half; + this.maxAllowedX = centerX + half; + this.minAllowedY = centerY - half; + this.maxAllowedY = centerY + half; + this.minAllowedZ = centerZ - half; + this.maxAllowedZ = centerZ + half; + + this.minRelX = minAllowedX - cameraX; + this.maxRelX = maxAllowedX - cameraX; + this.minRelY = minAllowedY - cameraY; + this.maxRelY = maxAllowedY - cameraY; + this.minRelZ = minAllowedZ - cameraZ; + this.maxRelZ = maxAllowedZ - cameraZ; + } + + private static double snap(double v) { + return Math.floor(v / SNAP) * SNAP + SNAP * 0.5; } public boolean isCulled(AxisAlignedBB aabb) { @@ -48,14 +86,14 @@ public class BoxCuller { // View-relative coordinates version public boolean isCulledViewRelative(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - if (maxX < -this.maxDistance || minX > this.maxDistance) { + if (maxX < this.minRelX || minX > this.maxRelX) { return true; } - if (maxY < -this.maxDistance || minY > this.maxDistance) { + if (maxY < this.minRelY || minY > this.maxRelY) { return true; } - return maxZ < -this.maxDistance || minZ > this.maxDistance; + return maxZ < this.minRelZ || minZ > this.maxRelZ; } } diff --git a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java b/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java index 3cc8ed2a1..aa78ee1c9 100644 --- a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java +++ b/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java @@ -2,7 +2,6 @@ package net.coderbot.iris.texture.util; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -46,9 +45,6 @@ public class TextureManipulationUtil { textureId, level); GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); - if (Minecraft.isRunningOnMac) { - GLStateManager.glGetError(); - } GLStateManager.glFramebufferTexture2D( GL30.GL_FRAMEBUFFER, diff --git a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java index f308c24ca..8dac4d297 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java @@ -1,12 +1,12 @@ package net.coderbot.iris.uniforms; -import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.BlendState; import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.client.rendering.TextureTracker; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; +import net.coderbot.iris.Iris; import net.coderbot.iris.compat.dh.DHCompat; import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.gl.state.StateUpdateNotifiers; @@ -62,7 +62,7 @@ public final class CommonUniforms { IdMapUniforms.addIdMapUniforms(updateNotifier, uniforms, idMap, directives.isOldHandLight()); MatrixUniforms.addMatrixUniforms(uniforms, directives); - if (AngelicaConfig.enableHardcodedCustomUniforms) { + if (Iris.hardcodedCustomUniforms) { HardcodedCustomUniforms.addHardcodedCustomUniforms(uniforms, updateNotifier); } diff --git a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java index 02c51ee46..d6519c71f 100644 --- a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java +++ b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java @@ -29,6 +29,8 @@ public final class EntityIdHelper { private static final Object2IntMap> entityIdCache = new Object2IntOpenHashMap<>(); private static final Map, NamespacedId> entityNameCache = new IdentityHashMap<>(); private static Object2IntFunction cachedEntityIdMap; + private static int cachedCurrentPlayerId = -1; + private static int cachedConvertingVillagerId = -1; private static final Int2LongLinkedOpenHashMap entityNbtCache = new Int2LongLinkedOpenHashMap(); private static final int NBT_CACHE_INTERVAL_TICKS = 20; @@ -64,6 +66,8 @@ public final class EntityIdHelper { entityNameCache.clear(); entityNbtCache.clear(); cachedEntityIdMap = entityIdMap; + cachedCurrentPlayerId = entityIdMap.applyAsInt(CURRENT_PLAYER); + cachedConvertingVillagerId = entityIdMap.applyAsInt(CONVERTING_VILLAGER); } // Check NBT-conditional match first @@ -99,7 +103,7 @@ public final class EntityIdHelper { final int normalId = getNormalEntityId(entity, entityIdMap); // Check for special entity type overrides - final int specialId = getSpecialEntityId(entity, entityIdMap); + final int specialId = getSpecialEntityId(entity); if (specialId != -1) { return specialId; } @@ -110,20 +114,16 @@ public final class EntityIdHelper { /** * Check if the entity should use a special hardcoded entity ID. */ - private static int getSpecialEntityId(Entity entity, Object2IntFunction entityIdMap) { + private static int getSpecialEntityId(Entity entity) { // Check if this is the current player (3rd person only) - Entity cameraEntity = Minecraft.getMinecraft().renderViewEntity; - if (entity == cameraEntity && entity instanceof EntityPlayer) { - int currentPlayerId = entityIdMap.applyAsInt(CURRENT_PLAYER); - if (currentPlayerId != -1) { - return currentPlayerId; - } + if (cachedCurrentPlayerId != -1 && entity instanceof EntityPlayer && entity == Minecraft.getMinecraft().renderViewEntity) { + return cachedCurrentPlayerId; } // Check if this is a converting zombie villager if (entity instanceof EntityZombie zombie) { if (zombie.isConverting()) { - return entityIdMap.applyAsInt(CONVERTING_VILLAGER); + return cachedConvertingVillagerId; } } diff --git a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java b/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java index a047c0c51..3df3b6ef0 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java @@ -1,7 +1,7 @@ package net.coderbot.iris.uniforms; import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; public class ExternallyManagedUniforms { private ExternallyManagedUniforms() { diff --git a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java index 12a55429d..a5a8b9616 100644 --- a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java @@ -11,6 +11,8 @@ import net.minecraft.entity.Entity; import org.joml.Matrix4f; import org.joml.Matrix4fc; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; @@ -44,14 +46,14 @@ public final class MatrixUniforms { uniforms .uniformMatrix(PER_FRAME, "gbuffer" + name, supplier) .uniformMatrix(PER_FRAME, "gbuffer" + name + "Inverse", new Inverted(supplier)) - .uniformMatrix(PER_FRAME, "gbufferPrevious" + name, new Previous(supplier)); + .uniformMatrix(PER_FRAME, "gbufferPrevious" + name, Previous.shared("gbufferPrevious" + name, supplier)); } private static void addDHMatrix(UniformHolder uniforms, String name, Supplier supplier) { uniforms .uniformMatrix(PER_FRAME, "dh" + name, supplier) .uniformMatrix(PER_FRAME, "dh" + name + "Inverse", new Inverted(supplier)) - .uniformMatrix(PER_FRAME, "dhPrevious" + name, new Previous(supplier)); + .uniformMatrix(PER_FRAME, "dhPrevious" + name, Previous.shared("dhPrevious" + name, supplier)); } @@ -80,24 +82,31 @@ public final class MatrixUniforms { } - private static class Previous implements Supplier { + static final class Previous implements Supplier { + private static final Map INSTANCES = new ConcurrentHashMap<>(); + private final Supplier parent; - private Matrix4fc previous; + private final Matrix4f previous = new Matrix4f(); + private final Matrix4f current = new Matrix4f(); + private int lastFrame = -1; Previous(Supplier parent) { this.parent = parent; - this.previous = new Matrix4f(); + } + + static Previous shared(String name, Supplier parent) { + return INSTANCES.computeIfAbsent(name, k -> new Previous(parent)); } @Override - public Matrix4f get() { - // PERF: Don't copy + allocate these matrices every time? - final Matrix4f copy = new Matrix4f(parent.get()); - final Matrix4f prev = new Matrix4f(this.previous); - - this.previous = copy; - - return prev; + public Matrix4fc get() { + final int frame = SystemTimeUniforms.COUNTER.getAsInt(); + if (frame != lastFrame) { + lastFrame = frame; + previous.set(current); + current.set(parent.get()); + } + return previous; } } } diff --git a/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java b/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java new file mode 100644 index 000000000..342bdc204 --- /dev/null +++ b/src/main/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvester.java @@ -0,0 +1,90 @@ +package net.coderbot.iris.uniforms; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import net.coderbot.iris.Iris; +import net.coderbot.iris.gl.state.FogMode; +import net.coderbot.iris.gl.uniform.ManifestCollectingHolder; +import net.coderbot.iris.gl.uniform.UniformManifest; +import net.coderbot.iris.shaderpack.ProgramSet; +import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public final class PerFrameUniformBlockHarvester { + + private PerFrameUniformBlockHarvester() {} + + public static void clear() { + GLSMHooks.perFrameUniformBlock = null; + GLSMHooks.perPassUniformBlock = null; + } + + public static void harvest(ProgramSet programs) { + if (!BackendManager.RENDER_BACKEND.isSDLGPU()) { + clear(); + return; + } + try { + final UniformManifest primary = collect(programs, FogMode.PER_VERTEX); + final UniformManifest secondary = collect(programs, FogMode.OFF); + GLSMHooks.perFrameUniformBlock = toBlock(primary, secondary); + GLSMHooks.perPassUniformBlock = toPerPassBlock(primary, secondary); + } catch (Exception e) { + Iris.logger.error("Failed to harvest the shared uniform blocks; falling back to loose uniforms", e); + clear(); + } + } + + /** + * Declared PER_FRAME but not frame-global + */ + private static final Set LIVE_STATE_UNIFORMS = Set.of( + "gbufferModelView", "gbufferModelViewInverse", "gbufferPreviousModelView", + "gbufferProjection", "gbufferProjectionInverse", "gbufferPreviousProjection", + "fogColor", "iris_FogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity"); + + /** + * @param primary manifest whose entry order defines the block layout + * @param secondary same declarations under a different fog mode, used only to widen the exclusions + */ + static PerFrameUniformBlock toBlock(UniformManifest primary, UniformManifest secondary) { + return collectMembers(primary, secondary, false); + } + + static PerFrameUniformBlock toPerPassBlock(UniformManifest primary, UniformManifest secondary) { + return collectMembers(primary, secondary, true); + } + + private static PerFrameUniformBlock collectMembers(UniformManifest primary, UniformManifest secondary, boolean liveState) { + final Set excluded = new HashSet<>(); + excluded.addAll(primary.dynamicNames()); + excluded.addAll(secondary.dynamicNames()); + excluded.addAll(primary.externallyManagedNames()); + excluded.addAll(secondary.externallyManagedNames()); + + final List members = new ArrayList<>(); + for (UniformManifest.Entry e : primary.entries()) { + if (LIVE_STATE_UNIFORMS.contains(e.name()) != liveState) continue; + if (excluded.contains(e.name())) continue; + if (e.type() == null) continue; + members.add(new Member(e.name(), e.type())); + } + return new PerFrameUniformBlock(List.copyOf(members)); + } + + private static UniformManifest collect(ProgramSet programs, FogMode fogMode) { + final ManifestCollectingHolder holder = new ManifestCollectingHolder(); + final FrameUpdateNotifier notifier = new FrameUpdateNotifier(); + CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), notifier); + CommonUniforms.addDynamicUniforms(holder, fogMode); + BuiltinReplacementUniforms.addBuiltinReplacementUniforms(holder); + return holder.build(); + } + +} diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java index f3e55031e..b374d5460 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java +++ b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java @@ -6,7 +6,7 @@ import kroppeb.stareval.function.Type; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.uniform.FloatSupplier; import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform; import net.coderbot.iris.uniforms.custom.cached.CachedUniform; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java index 6050d8d10..99d0c42ff 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java @@ -2,8 +2,11 @@ package net.coderbot.iris.uniforms.custom; import com.github.bsideup.jabel.Desugar; import com.google.common.collect.ImmutableMap; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -25,6 +28,7 @@ import net.coderbot.iris.parsing.VectorType; import net.coderbot.iris.uniforms.custom.cached.CachedUniform; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.OptionalInt; @@ -38,11 +42,33 @@ public class CustomUniforms implements FunctionContext { private final Map variablesExpressions = new Object2ObjectLinkedOpenHashMap<>(); private final CustomUniformFixedInputUniformsHolder inputHolder; private final List uniformOrder; - private final Map> locationMap = new Object2ObjectOpenHashMap<>(); + private final Map locationMap = new Object2ObjectOpenHashMap<>(); private final Map> dependsOn; + private final Object2LongOpenHashMap lastPushedGen = new Object2LongOpenHashMap<>(); + private long generation; + + private static final long PLOT_CUSTOM_PUSHED = Tracy.ENABLED ? Tracy.plotHandle("iris.customPushed") : 0; + private static final long PLOT_CUSTOM_SKIPPED = Tracy.ENABLED ? Tracy.plotHandle("iris.customSkipped") : 0; + private int pushedThisFrame; + private int skippedThisFrame; + + private static final class PassUniforms { + final CachedUniform[] uniforms; + final int[] locations; + final int[] lastPushedValueGen; + + PassUniforms(CachedUniform[] uniforms, int[] locations) { + this.uniforms = uniforms; + this.locations = locations; + this.lastPushedValueGen = new int[uniforms.length]; + Arrays.fill(lastPushedValueGen, -1); + } + } + private CustomUniforms(CustomUniformFixedInputUniformsHolder inputHolder, Map variables) { this.inputHolder = inputHolder; + this.lastPushedGen.defaultReturnValue(-1); ExpressionResolver resolver = new ExpressionResolver( IrisFunctions.functions, (name) -> { @@ -188,18 +214,20 @@ public class CustomUniforms implements FunctionContext { } public void assignTo(LocationalUniformHolder targetHolder) { - Object2IntMap locations = new Object2IntOpenHashMap<>(); + final List uniforms = new ObjectArrayList<>(); + final IntArrayList locations = new IntArrayList(); for (CachedUniform uniform : this.uniformOrder) { try { OptionalInt location = targetHolder.location(uniform.getName(), Type.convert(uniform.getType())); if (location.isPresent()) { - locations.put(uniform, location.getAsInt()); + uniforms.add(uniform); + locations.add(location.getAsInt()); } } catch (Exception e) { throw new RuntimeException(uniform.getName(), e); } } - this.locationMap.put(targetHolder, locations); + this.locationMap.put(targetHolder, new PassUniforms(uniforms.toArray(new CachedUniform[0]), locations.toIntArray())); } public void mapholderToPass(LocationalUniformHolder holder, Object pass) { @@ -208,15 +236,38 @@ public class CustomUniforms implements FunctionContext { public void update() { - for (CachedUniform value : this.uniformOrder) { - value.update(); + if (Tracy.ENABLED) { + Tracy.plotInt(PLOT_CUSTOM_PUSHED, pushedThisFrame); + Tracy.plotInt(PLOT_CUSTOM_SKIPPED, skippedThisFrame); + pushedThisFrame = 0; + skippedThisFrame = 0; + } + generation++; + final List ordered = this.uniformOrder; + for (int i = 0, n = ordered.size(); i < n; i++) { + ordered.get(i).update(); } } public void push(Object pass) { - Object2IntMap uniforms = this.locationMap.get(pass); - if (uniforms != null) { - uniforms.forEach(CachedUniform::pushIfChanged); + final PassUniforms pu = this.locationMap.get(pass); + if (pu == null) return; + if (lastPushedGen.getLong(pass) == generation) { + return; + } + lastPushedGen.put(pass, generation); + final CachedUniform[] uniforms = pu.uniforms; + final int[] locations = pu.locations; + final int[] gens = pu.lastPushedValueGen; + for (int i = 0; i < uniforms.length; i++) { + final int gen = uniforms[i].valueGen(); + if (gens[i] != gen) { + uniforms[i].push(locations[i]); + gens[i] = gen; + if (Tracy.ENABLED) pushedThisFrame++; + } else if (Tracy.ENABLED) { + skippedThisFrame++; + } } } @@ -250,10 +301,9 @@ public class CustomUniforms implements FunctionContext { } } - // Count the times a pass depends on a uniform - // ensures they wont ever be removed - for (Object2IntMap map : this.locationMap.values()) { - for (CachedUniform cachedUniform : map.keySet()) { + // Count the times a pass depends on a uniform ensures they wont ever be removed + for (PassUniforms pu : this.locationMap.values()) { + for (CachedUniform cachedUniform : pu.uniforms) { dependedByCount.mergeInt(cachedUniform, 1, Integer::sum); } } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java b/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java index 83183df36..d591d2afe 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java +++ b/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java @@ -14,7 +14,7 @@ import org.joml.Vector4f; public abstract class CachedUniform implements VariableExpression { private final String name; private final UniformUpdateFrequency updateFrequency; - private boolean changed = true; + private int valueGen; public CachedUniform(String name, UniformUpdateFrequency updateFrequency) { this.name = name; @@ -59,27 +59,18 @@ public abstract class CachedUniform implements VariableExpression { } } - public void markUnchanged() { - this.changed = false; + public void update() { + if (doUpdate()) valueGen++; } - public void update() { - doUpdate(); - // TODO: Works around a logic error / architectural flaw - there's no way to - // know when a uniform has been uploaded to all programs, so we can never - // safely change this to false with the current design. - this.changed = true; + public int valueGen() { + return valueGen; } protected abstract boolean doUpdate(); public abstract void push(int location); - public void pushIfChanged(int location) { - if (this.changed) - push(location); - } - @Override public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { this.writeTo(functionReturn); diff --git a/src/main/java/net/coderbot/iris/vertices/NormalHelper.java b/src/main/java/net/coderbot/iris/vertices/NormalHelper.java index 619603538..1c5286684 100644 --- a/src/main/java/net/coderbot/iris/vertices/NormalHelper.java +++ b/src/main/java/net/coderbot/iris/vertices/NormalHelper.java @@ -13,30 +13,14 @@ public abstract class NormalHelper { * The extra value is for use by shaders. */ public static int packNormal(float x, float y, float z, float w) { - x = Math.clamp(x, -1, 1); - y = Math.clamp(y, -1, 1); - z = Math.clamp(z, -1, 1); - w = Math.clamp(w, -1, 1); + x = Math.clamp(-1f, 1f, x); + y = Math.clamp(-1f, 1f, y); + z = Math.clamp(-1f, 1f, z); + w = Math.clamp(-1f, 1f, w); return ((int) (x * 127) & 0xFF) | (((int) (y * 127) & 0xFF) << 8) | (((int) (z * 127) & 0xFF) << 16) | (((int) (w * 127) & 0xFF) << 24); } - /** - * Version of {@link #packNormal(float, float, float, float)} that accepts a vector type. - */ - public static int packNormal(Vector3f normal, float w) { - return packNormal(normal.x, normal.y, normal.z, w); - } - - /** - * Retrieves values packed by {@link #packNormal(float, float, float, float)}. - * - *

Components are x, y, z, w - zero based. - */ - public static float getPackedNormalComponent(int packedNormal, int component) { - return ((byte) (packedNormal >> (8 * component))) / 127f; - } - /** * Computes the face normal of the given quad and saves it in the provided non-null vector. * diff --git a/src/main/resources/assets/angelica/lang/en_US.lang b/src/main/resources/assets/angelica/lang/en_US.lang index 97779c51d..8dfb50dcc 100644 --- a/src/main/resources/assets/angelica/lang/en_US.lang +++ b/src/main/resources/assets/angelica/lang/en_US.lang @@ -66,6 +66,8 @@ sodium.options.use_fog_occlusion.name=Fog Occlusion sodium.options.use_fog_occlusion.tooltip=If enabled, chunks which are determined to be fully hidden by fog effects will not be rendered, helping to improve performance. The improvement can be more dramatic when fog effects are heavier (such as while underwater), but it may cause undesirable visual artifacts between the sky and fog in some scenarios. sodium.options.use_entity_culling.name=Entity Culling sodium.options.use_entity_culling.tooltip=If enabled, entities determined not to be in any visible chunks will be skipped during rendering. This can help improve performance by avoiding the rendering of entities located underground or behind walls. +sodium.options.section_gated_tesr_culling.name=Section-Gated TESR Culling +sodium.options.section_gated_tesr_culling.tooltip=If enabled, tile entities are frustum-culled one chunk section at a time instead of one tile entity at a time. sodium.options.use_particle_culling.name=Particle Culling sodium.options.use_particle_culling.tooltip=If enabled, only particles which are determined to be visible will be rendered. This can provide a significant improvement to frame rates when many particles are nearby. sodium.options.animate_only_visible_textures.name=Animate Only Visible Textures @@ -223,6 +225,10 @@ options.angelica.itemdisplaylistcount=Item Renderer Cache Limit options.angelica.itemdisplaylistcount.tooltip=The upper limit of VBO's to cache in the optimized item renderer. Higher values will significantly increase performance, but may result in increased VRAM usage. options.angelica.threadedChunkBuilding=Threaded Chunk Building options.angelica.threadedChunkBuilding.tooltip=If enabled, chunk meshing will be performed on multiple threads in parallel, significantly improving chunk build speed. Disable if you experience rendering issues with mods that have custom block renderers. Requires renderer reload to take effect. +options.angelica.gpuCullingMode=GPU Culling Mode +options.angelica.gpuCullingMode.tooltip=Selects the chunk culling pipeline. CPU Only uses the CPU emitter. Compute runs frustum culling on the GPU. Requires GL 4.3 / ARB_compute_shader + SSBO + Indirect Multi-Draw. +options.angelica.gpuCullingMode.cpu_only=CPU Only +options.angelica.gpuCullingMode.compute=Compute pack.iris.select.title=Select pack.iris.configure.title=Configure @@ -256,7 +262,7 @@ options.angelica.texteffects.ampersand_conversion=Ampersand Conversion options.angelica.texteffects.ampersand_conversion.tooltip=Convert %s prefix codes to formatting codes at render time sodium.options.multidraw_mode.name=Multi-Draw Mode -sodium.options.multidraw_mode.tooltip=Controls how draw commands are dispatched for terrain rendering. §lDirect§r uses glMultiDrawElementsBaseVertex (default, GL 3.2+). §lIndirect§r uses GPU indirect rendering (GL 4.3+), may reduce CPU overhead on some hardware. §lIndividual§r issues individual draw calls. +sodium.options.multidraw_mode.tooltip=Controls how draw commands are dispatched for terrain rendering. §lDirect§r uses glMultiDrawElementsBaseVertex (default, GL 3.2+). §lIndirect§r uses GPU indirect rendering (GL 4.3+), may reduce CPU overhead on some hardware, and is required for GPU / Hi-Z culling. §lIndividual§r issues individual draw calls. sodium.options.multidraw_mode.direct=Direct sodium.options.multidraw_mode.indirect=Indirect sodium.options.multidraw_mode.individual=Individual diff --git a/src/main/resources/assets/angelica/shaders/culling/chunk_cull.csh b/src/main/resources/assets/angelica/shaders/culling/chunk_cull.csh new file mode 100644 index 000000000..86dbc8886 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/culling/chunk_cull.csh @@ -0,0 +1,108 @@ +#version 430 core + +layout(local_size_x = 64) in; + +struct Section { + ivec4 origin; // x, y, z (block coords), sliceMask + uvec4 posts0; // vertex fence posts 0..3 + uvec4 posts1; // vertex fence posts 4..7; facing f spans posts [f, f+1) + uvec4 extra; // .x = section index base in elements (0 when unsorted), .yzw unused +}; + +uint post(Section s, uint i) { + return i < 4u ? s.posts0[i] : s.posts1[i - 4u]; +} + +struct DrawElementsIndirectCommand { + uint count; + uint instanceCount; + uint firstIndex; + int baseVertex; + uint baseInstance; +}; + +layout(std430, binding = 0) readonly buffer VisibleIds { + uvec2 entries[]; +} visible; + +layout(std430, binding = 1) readonly buffer SectionMeta { + Section sections[]; +} meta; + +layout(std430, binding = 2) writeonly buffer IndirectCmds { + DrawElementsIndirectCommand cmds[]; +} indirect; + +layout(std140, binding = 0) uniform Frustum { + vec4 planes[6]; // camera-relative planes from `proj * mv` (no translate baked in) + // control.x = visibleCount (iteration bound) + // control.y = indexPointerMask (0 non-sorted -> firstIndex masked to 0; 0xFFFFFFFF sorted) + // control.z = bypassFrustum (shadow passes; renderLists already carry the caster set) + uvec4 control; + // cameraWorld.xyz = current-frame camera (subtract from world AABB for frustum test) + vec4 cameraWorld; + // batch.x = visible-list entryBase for this dispatch (batched culls) + uvec4 batch; + // pyr.zw = vertices and index elements per primitive, from ChunkPrimitiveType (exact as floats) + vec4 pyr; +} frustum; + +bool insideFrustum(vec3 minP, vec3 maxP) { + // Planes are camera-relative; reduce world AABB to camera-relative before the n-vertex test. + vec3 cam = frustum.cameraWorld.xyz; + vec3 minR = minP - cam; + vec3 maxR = maxP - cam; + for (int i = 0; i < 6; i++) { + vec4 p = frustum.planes[i]; + vec3 ext = vec3(p.x > 0.0 ? maxR.x : minR.x, + p.y > 0.0 ? maxR.y : minR.y, + p.z > 0.0 ? maxR.z : minR.z); + if (dot(p.xyz, ext) + p.w < 0.0) return false; + } + return true; +} + +void main() { + uint gid = gl_GlobalInvocationID.x; + if (gid >= frustum.control.x) return; + + uint entryIdx = frustum.batch.x + gid; + uvec2 entry = visible.entries[entryIdx]; + uint slot = entry.x; + uint packedEntry = entry.y; + uint facingMask = packedEntry & 0xFFu; + uint outputBase = packedEntry >> 8; + + Section s = meta.sections[slot]; + vec3 minP = vec3(s.origin.xyz); + vec3 maxP = minP + vec3(16.0); + + bool inside = (frustum.control.z != 0u) || insideFrustum(minP, maxP); + + uint indexMask = frustum.control.y; + uint vertsPerPrim = uint(frustum.pyr.z); + uint elemsPerPrim = uint(frustum.pyr.w); + uint sectionBase = post(s, 0u); + + bool mergeRuns = indexMask == 0u; + uint mask = facingMask & 0x7Fu; + + uint localIdx = 0u; + while (mask != 0u) { + uint first = uint(findLSB(mask)); + uint length = mergeRuns ? uint(findLSB(~(mask >> first))) : 1u; + uint startV = post(s, first); + uint endV = post(s, first + length); + + DrawElementsIndirectCommand c; + c.count = inside ? ((endV - startV) / vertsPerPrim) * elemsPerPrim : 0u; + c.instanceCount = inside ? 1u : 0u; + c.firstIndex = (s.extra.x + ((startV - sectionBase) / vertsPerPrim) * elemsPerPrim) & indexMask; + c.baseVertex = int(startV); + c.baseInstance = 0u; + indirect.cmds[outputBase + localIdx] = c; + localIdx++; + + mask &= ~(((1u << length) - 1u) << first); + } +} diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.fsh b/src/main/resources/assets/angelica/shaders/fontFilter.fsh index 642a19a94..e4d2ac3e0 100644 --- a/src/main/resources/assets/angelica/shaders/fontFilter.fsh +++ b/src/main/resources/assets/angelica/shaders/fontFilter.fsh @@ -20,12 +20,12 @@ float totalWt; float txSample(vec2 uv, float du, float dv, float factorU, float factorV) { float distSquared = sqrt(du * du + dv * dv); - float weight = exp(-distSquared / 6); + float weight = exp(-distSquared / 6.0); totalWt += weight; float finalU = uv.x + factorU * du; float finalV = uv.y + factorV * dv; if (finalU < tB.x || finalU > tB.y || finalV < tB.z || finalV > tB.w) { - return 0.0f; + return 0.0; } return weight * texture(sampler, vec2(finalU, finalV)).a; } @@ -33,38 +33,38 @@ float txSample(vec2 uv, float du, float dv, float factorU, float factorV) { void main() { vec4 col = color; float original_alpha = col.a; - if (texCoord.s != 0 || texCoord.t != 0) { + if (texCoord.s != 0.0 || texCoord.t != 0.0) { if (aaMode == 0) { // No AA - single texture sample col.a = original_alpha * texture(sampler, texCoord).a; } else { vec2 texScaled = texCoord * strength; - float res = 0; + float res = 0.0; float fu = abs(dFdx(texScaled.x)) + abs(dFdy(texScaled.x)); float fv = abs(dFdx(texScaled.y)) + abs(dFdy(texScaled.y)); - totalWt = 0; + totalWt = 0.0; if (aaMode == 1) { - res += txSample(texCoord, 2, 6, fu, fv); - res += txSample(texCoord, 6, -2, fu, fv); - res += txSample(texCoord, -2, -6, fu, fv); - res += txSample(texCoord, -6, 2, fu, fv); + res += txSample(texCoord, 2.0, 6.0, fu, fv); + res += txSample(texCoord, 6.0, -2.0, fu, fv); + res += txSample(texCoord, -2.0, -6.0, fu, fv); + res += txSample(texCoord, -6.0, 2.0, fu, fv); } else { - res += txSample(texCoord, 1, 1, fu, fv); - res += txSample(texCoord, -1, -3, fu, fv); - res += txSample(texCoord, -3, 2, fu, fv); - res += txSample(texCoord, 4, -1, fu, fv); - res += txSample(texCoord, -5, -2, fu, fv); - res += txSample(texCoord, 2, 5, fu, fv); - res += txSample(texCoord, 5, 3, fu, fv); - res += txSample(texCoord, 3, -5, fu, fv); - res += txSample(texCoord, -2, 6, fu, fv); - res += txSample(texCoord, 0, -7, fu, fv); - res += txSample(texCoord, -4, -6, fu, fv); - res += txSample(texCoord, -6, 4, fu, fv); - res += txSample(texCoord, -8, 0, fu, fv); - res += txSample(texCoord, 7, -4, fu, fv); - res += txSample(texCoord, 6, 7, fu, fv); - res += txSample(texCoord, -7, -8, fu, fv); + res += txSample(texCoord, 1.0, 1.0, fu, fv); + res += txSample(texCoord, -1.0, -3.0, fu, fv); + res += txSample(texCoord, -3.0, 2.0, fu, fv); + res += txSample(texCoord, 4.0, -1.0, fu, fv); + res += txSample(texCoord, -5.0, -2.0, fu, fv); + res += txSample(texCoord, 2.0, 5.0, fu, fv); + res += txSample(texCoord, 5.0, 3.0, fu, fv); + res += txSample(texCoord, 3.0, -5.0, fu, fv); + res += txSample(texCoord, -2.0, 6.0, fu, fv); + res += txSample(texCoord, 0.0, -7.0, fu, fv); + res += txSample(texCoord, -4.0, -6.0, fu, fv); + res += txSample(texCoord, -6.0, 4.0, fu, fv); + res += txSample(texCoord, -8.0, 0.0, fu, fv); + res += txSample(texCoord, 7.0, -4.0, fu, fv); + res += txSample(texCoord, 6.0, 7.0, fu, fv); + res += txSample(texCoord, -7.0, -8.0, fu, fv); } res /= totalWt; col.a = original_alpha * res; diff --git a/src/main/resources/assets/angelica/shaders/sdlgpu/clear_image3d.csh b/src/main/resources/assets/angelica/shaders/sdlgpu/clear_image3d.csh new file mode 100644 index 000000000..2e7ab31e6 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/sdlgpu/clear_image3d.csh @@ -0,0 +1,13 @@ +#version 460 core + +layout(local_size_x = 4, local_size_y = 4, local_size_z = 4) in; + +layout(binding = 0) writeonly uniform uimage3D u_target; + +uniform ivec3 u_extent; + +void main() { + ivec3 texel = ivec3(gl_GlobalInvocationID); + if (any(greaterThanEqual(texel, u_extent))) return; + imageStore(u_target, texel, uvec4(0u)); +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinFMLClientHandler.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinFMLClientHandler.java index 97c6fac21..c6a1f0d9d 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinFMLClientHandler.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinFMLClientHandler.java @@ -1,8 +1,12 @@ package com.gtnewhorizons.angelica.mixins.early.angelica; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import cpw.mods.fml.client.FMLClientHandler; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = FMLClientHandler.class, remap = false) public class MixinFMLClientHandler { @@ -24,4 +28,10 @@ public class MixinFMLClientHandler { return false; } + @Inject(method = "processWindowMessages", at = @At("RETURN")) + private void angelica$fireLoadingCheckpoint(CallbackInfo ci) { + if (GLSMHooks.LOADING_CHECKPOINT.hasListeners()) { + GLSMHooks.LOADING_CHECKPOINT.post(GLSMHooks.loadingCheckpointEvent); + } + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java index 458e797ae..290846059 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java @@ -37,7 +37,7 @@ public abstract class MixinForgeHooksClient_CoreProfile { /** * @author Angelica - * @reason Request highest GL version with core profile context + * @reason Request highest GL version with core profile context, or GL ES 3.2 when requested */ @Overwrite public static void createDisplay() throws LWJGLException { @@ -47,6 +47,19 @@ public abstract class MixinForgeHooksClient_CoreProfile { final PixelFormat format = new PixelFormat().withDepthBits(24).withStencilBits(stencilBits); + final AngelicaConfig.GLProfile profile = AngelicaConfig.getEffectiveGlProfile(); + + if (profile == AngelicaConfig.GLProfile.ES) { + final Exception e = angelica$tryCreateES(); + if (e == null) { + LOGGER.info("Created GL ES 3.2 context"); + return; + } + angelica$reportContextFailure(e); + if (e instanceof LWJGLException lwjgl) throw lwjgl; + throw new LWJGLException("Failed to create OpenGL ES 3.2 context", e); + } + final ContextAttribs attribs = new ContextAttribs(3, 3).withProfileCore(true).withForwardCompatible(true).withDebug(AngelicaMod.lwjglDebug); final MethodHandle setMajor, setMinor; try { @@ -125,6 +138,19 @@ public abstract class MixinForgeHooksClient_CoreProfile { return clamped; } + @Unique + private static Exception angelica$tryCreateES() { + final PixelFormat esFormat = new PixelFormat().withDepthBits(24).withStencilBits(stencilBits); + final ContextAttribs esAttribs = new ContextAttribs(3, 2).withProfileES(true).withDebug(AngelicaMod.lwjglDebug); + try { + Display.create(esFormat, esAttribs); + return null; + } catch (LWJGLException | RuntimeException e) { + try { Display.destroy(); } catch (Exception ignored) {} + return e; + } + } + @Unique private static Exception angelica$tryCreate(ContextAttribs attribs, PixelFormat format, MethodHandle setMajor, MethodHandle setMinor, int major, int minor) throws RuntimeException { try { @@ -161,7 +187,7 @@ public abstract class MixinForgeHooksClient_CoreProfile { AngelicaConfig.pinnedGLVersion = version; try { ConfigurationManager.save(AngelicaConfig.class); - LOGGER.info("Pinned OpenGL version to {}.{} — set pinnedGLVersion=0 to re-probe, or disableGLVersionPinning=true to never pin", version / 10, version % 10); + LOGGER.info("Pinned OpenGL version to {}.{} - set pinnedGLVersion=0 to re-probe, or disableGLVersionPinning=true to never pin", version / 10, version % 10); } catch (Exception e) { LOGGER.warn("Failed to save pinned GL version: {}", e.getMessage()); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft.java index 819cb9db4..2672b6bb3 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft.java @@ -1,6 +1,8 @@ package com.gtnewhorizons.angelica.mixins.early.angelica; import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import com.gtnewhorizons.angelica.mixins.interfaces.IGameSettingsExt; import com.gtnewhorizons.angelica.proxy.ClientProxy; @@ -17,6 +19,7 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Minecraft.class) @@ -97,6 +100,16 @@ public abstract class MixinMinecraft { angelica$lastFrameTime = time; } + @Redirect(method = {"startGame", "toggleFullscreen"}, at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/Display;setVSyncEnabled(Z)V", remap = false)) + private void angelica$redirectVSync(boolean sync) { + GLStateManager.setVSyncEnabled(sync); + } + + @Inject(method = "startGame", at = @At("RETURN")) + private void angelica$markSplashCompleteOnStartGame(CallbackInfo ci) { + GLStateManager.markSplashComplete("startGame"); + } + @WrapWithCondition(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/Display;sync(I)V", remap = false)) private boolean angelica$noopFPSLimiter(int fps) { return false; @@ -122,8 +135,10 @@ public abstract class MixinMinecraft { } } - @Inject(method = "runTick", at = @At("RETURN")) + @Inject(method = "runGameLoop", at = @At("RETURN")) private void angelica$streamingBufferEndFrame(CallbackInfo ci) { TessellatorStreamingDrawer.endFrame(); + BatchingFontRenderer.endFrame(); + ShaderManager.endFrame(); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java index 719c27f6c..e997379c1 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java @@ -1,40 +1,77 @@ package com.gtnewhorizons.angelica.mixins.early.angelica; +import com.gtnewhorizons.angelica.glsm.CaptureGate; import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** - * Hooks frame boundaries and shutdown in Minecraft's game loop to notify the active render backend. + * Hooks frame boundaries and shutdown in Minecraft to notify the active render backend. * - * Frame begin: at the start of runGameLoop (before any rendering) - * Frame end: after framebuffer blit and before Display.update (func_147120_f) - * Shutdown: at the start of shutdownMinecraftApplet (cleanup GPU resources) + * Frame end: at the start of func_147120_f[resetSize] (before Display.update) -- universal, covers + * all callers including LoadingScreenRenderer, drawSplashScreen, toggleFullscreen. + * Frame begin: at the end of func_147120_f (after Display.update), but only once the game loop has started. + * Bootstrap: one-shot at the start of the first runGameLoop call to start the first frame. + * Shutdown: at the start of shutdownMinecraftApplet (cleanup GPU resources). */ @Mixin(Minecraft.class) public class MixinMinecraft_FrameHook { + @Unique private static boolean angelica$gameLoopStarted; + @Unique private static long angelica$frameCounter; + @Unique private static boolean angelica$frameGroupActive; + @Inject(method = "runGameLoop", at = @At("HEAD")) - private void angelica$onFrameBegin(CallbackInfo ci) { + private void angelica$bootstrapFirstFrame(CallbackInfo ci) { DisplayListManager.abortIfLeaked(); - RENDER_BACKEND.onFrameBegin(); + if (!angelica$gameLoopStarted) { + angelica$gameLoopStarted = true; + RENDER_BACKEND.onFrameBegin(); + angelica$pushFrameGroup(); + } } - @Inject( - method = "runGameLoop", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;func_147120_f()V") - ) + @Inject(method = "func_147120_f"/*resetSize*/, at = @At("HEAD")) private void angelica$onFrameEnd(CallbackInfo ci) { + angelica$popFrameGroup(); RENDER_BACKEND.onFrameEnd(); } + @Inject(method = "func_147120_f"/*resetSize*/, at = @At("RETURN")) + private void angelica$onFrameBegin(CallbackInfo ci) { + if (angelica$gameLoopStarted) { + RENDER_BACKEND.onFrameBegin(); + angelica$pushFrameGroup(); + } + } + + @Unique + private static void angelica$pushFrameGroup() { + CaptureGate.refresh(); + GLDebug.pushGroup("frame:" + angelica$frameCounter); + angelica$frameGroupActive = true; + } + + @Unique + private static void angelica$popFrameGroup() { + if (angelica$frameGroupActive) { + GLDebug.popGroup(); + angelica$frameGroupActive = false; + angelica$frameCounter++; + } + } + @Inject(method = "shutdownMinecraftApplet", at = @At("HEAD")) private void angelica$onShutdown(CallbackInfo ci) { + GpuCulling.shutdown(); BackendManager.shutdown(); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_SkipEndFrameFlush.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_SkipEndFrameFlush.java new file mode 100644 index 000000000..2f513f11a --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_SkipEndFrameFlush.java @@ -0,0 +1,14 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica; + +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; + +@Mixin(Minecraft.class) +public class MixinMinecraft_SkipEndFrameFlush { + + @Redirect(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glFlush()V", remap = false)) + private void angelica$skipEndOfFrameFlush() { + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinSimpleReloadableResourceManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinSimpleReloadableResourceManager.java new file mode 100644 index 000000000..d177faead --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinSimpleReloadableResourceManager.java @@ -0,0 +1,24 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica; + +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import net.minecraft.client.resources.IResourcePack; +import net.minecraft.client.resources.SimpleReloadableResourceManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +@Mixin(SimpleReloadableResourceManager.class) +public class MixinSimpleReloadableResourceManager { + + @Inject(method = "reloadResources", at = @At("RETURN")) + private void angelica$fireSyncCheckpointOnReload(List packs, CallbackInfo ci) { + if (GLSMHooks.LOADING_CHECKPOINT.hasListeners()) { + GLSMHooks.loadingCheckpointEvent.requiresSync = true; + GLSMHooks.LOADING_CHECKPOINT.post(GLSMHooks.loadingCheckpointEvent); + GLSMHooks.loadingCheckpointEvent.requiresSync = false; + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinChatLine.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinChatLine.java new file mode 100644 index 000000000..ac2379a2b --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinChatLine.java @@ -0,0 +1,24 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.chat; + +import com.gtnewhorizons.angelica.mixins.interfaces.ChatLineFormattedAccessor; +import net.minecraft.client.gui.ChatLine; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(ChatLine.class) +public class MixinChatLine implements ChatLineFormattedAccessor { + + @Unique private String angelica$formatted; + @Unique private long angelica$formattedEpoch = Long.MIN_VALUE; + + @Override + public String angelica$getFormatted(long epoch) { + return angelica$formattedEpoch == epoch ? angelica$formatted : null; + } + + @Override + public void angelica$setFormatted(String formatted, long epoch) { + angelica$formatted = formatted; + angelica$formattedEpoch = epoch; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinGuiNewChat.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinGuiNewChat.java new file mode 100644 index 000000000..93961146a --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/chat/MixinGuiNewChat.java @@ -0,0 +1,29 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.chat; + +import com.gtnewhorizons.angelica.mixins.interfaces.ChatLineFormattedAccessor; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.gui.ChatLine; +import net.minecraft.client.gui.GuiNewChat; +import net.minecraft.util.IChatComponent; +import net.minecraft.util.StatCollector; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(GuiNewChat.class) +public class MixinGuiNewChat { + + @WrapOperation( + method = "drawChat", + at = @At(value = "INVOKE", target = "Lnet/minecraft/util/IChatComponent;getFormattedText()Ljava/lang/String;")) + private String angelica$cacheFormattedText(IChatComponent component, Operation original, @Local ChatLine line) { + final long epoch = StatCollector.getLastTranslationUpdateTimeInMilliseconds(); + final ChatLineFormattedAccessor cache = (ChatLineFormattedAccessor) line; + final String cached = cache.angelica$getFormatted(epoch); + if (cached != null) return cached; + final String formatted = original.call(component); + cache.angelica$setFormatted(formatted, epoch); + return formatted; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinProfiler.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinProfiler.java index c42459106..4486067f0 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinProfiler.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinProfiler.java @@ -1,17 +1,30 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.debug; import com.gtnewhorizons.angelica.glsm.GLDebug; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.minecraft.profiler.Profiler; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Profiler.class) public class MixinProfiler { + + @Unique private static final Reference2ObjectOpenHashMap angelica$groupNames = new Reference2ObjectOpenHashMap<>(); + @Unique private static final int ANGELICA$GROUP_NAMES_CAP = 2048; + @Inject(method = "startSection(Ljava/lang/String;)V", at = @At("HEAD")) private void debugStartSection(String name, CallbackInfo ci) { - GLDebug.pushGroup("minecraft:" + name); + if (!GLDebug.isActive()) return; + String group = angelica$groupNames.get(name); + if (group == null) { + group = "minecraft:" + name; + if (angelica$groupNames.size() > ANGELICA$GROUP_NAMES_CAP) angelica$groupNames.clear(); + angelica$groupNames.put(name, group); + } + GLDebug.pushGroup(group); } @Inject(method = "endSection()V", at = @At("HEAD")) diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java index 38567fae9..44f683231 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java @@ -5,8 +5,10 @@ import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource; import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer; +import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; @@ -36,6 +38,8 @@ public abstract class MixinEntity implements IDynamicLightSource { public abstract float getEyeHeight(); @Shadow public boolean isDead; + @Shadow + public int ticksExisted; @Unique protected int angelica$luminance = 0; @@ -51,6 +55,10 @@ public abstract class MixinEntity implements IDynamicLightSource { private LongOpenHashSet angelica$trackedLitChunkPos = null; @Unique private LongOpenHashSet angelica$prevTrackedLitChunkPos = null; + @Unique + private int angelica$cachedStackLum; + @Unique + private int angelica$lumRecheckTick; @Override public double angelica$getDynamicLightX() { @@ -84,7 +92,11 @@ public abstract class MixinEntity implements IDynamicLightSource { if (isDead) { angelica$setDynamicLightEnabled(false); } else { - angelica$dynamicLightTick(); + if (EntityLightConfig.isEntityTypeEnabled(this)) { + angelica$dynamicLightTick(); + } else { + this.angelica$luminance = 0; + } DynamicLights.updateTracking(this); } } @@ -92,7 +104,16 @@ public abstract class MixinEntity implements IDynamicLightSource { @Override public void angelica$dynamicLightTick() { - this.angelica$luminance = DynamicLights.getLuminanceFromEntity((Entity) (Object) this); + final Entity self = (Entity) (Object) this; + if (self instanceof EntityItem item) { + if (ticksExisted >= this.angelica$lumRecheckTick) { + this.angelica$cachedStackLum = DynamicLights.getLuminanceFromItemStack(item.getEntityItem()); + this.angelica$lumRecheckTick = ticksExisted + 4; + } + this.angelica$luminance = DynamicLights.getLuminanceFromEntityItem(item, this.angelica$cachedStackLum); + } else { + this.angelica$luminance = DynamicLights.getLuminanceFromEntity(self); + } } @Override diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelRenderer.java new file mode 100644 index 000000000..938beb1d9 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelRenderer.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import net.minecraft.client.model.ModelRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(ModelRenderer.class) +public abstract class MixinModelRenderer { + + @Redirect(method = {"render", "renderWithRotation"}, at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glCallList(I)V", remap = false)) + private void angelica$batchPart(int list, float scale) { + if (!ModelPartBatcher.partDraw((ModelRenderer) (Object) this, scale, null)) { + GLStateManager.glCallList(list); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityBatch.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityBatch.java new file mode 100644 index 000000000..253da4ae5 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityBatch.java @@ -0,0 +1,29 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import net.minecraft.client.renderer.RenderGlobal; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(RenderGlobal.class) +public abstract class MixinRenderGlobal_EntityBatch { + private static final Tracy.ZoneId Z_ENTITY_MODEL_PARTS = Tracy.zoneId("entityModelParts", Tracy.COLOR_CLIENT); + + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=entities")) + private void angelica$beginEntityBatch(CallbackInfo ci) { + ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.ENTITIES); + } + + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=blockentities")) + private void angelica$flushEntityBatch(CallbackInfo ci) { + if (Tracy.ENABLED) Tracy.beginZone(Z_ENTITY_MODEL_PARTS); + try { + ModelPartBatcher.INSTANCE.flush(); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinTextureManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinTextureManager.java new file mode 100644 index 000000000..d4fed53df --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinTextureManager.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.util.ResourceLocation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(TextureManager.class) +public abstract class MixinTextureManager { + + @Inject(method = "bindTexture", at = @At("RETURN")) + private void angelica$trackBind(ResourceLocation location, CallbackInfo ci) { + ModelPartBatcher.onTextureBind(location, GLStateManager.getBoundTextureForServerState()); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java index 641bf76d6..f6fa10136 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java @@ -17,7 +17,6 @@ public class MixinTessellator_CoreProfile { @Inject(method = "draw", at = @At(value = "FIELD", target = "Lnet/minecraft/client/renderer/Tessellator;isDrawing:Z", opcode = Opcodes.GETFIELD), cancellable = true) private void angelica$coreProfileDraw(CallbackInfoReturnable cir) { - // Injecting after HEAD because GTNHLib's shouldInterceptDraw() takes priority cir.setReturnValue(TessellatorStreamingDrawer.draw((Tessellator) (Object) this)); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinGuiIngameForge.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinGuiIngameForge.java index 1754bd240..30a186619 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinGuiIngameForge.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinGuiIngameForge.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; import net.minecraft.client.gui.FontRenderer; import net.minecraftforge.client.GuiIngameForge; @@ -26,11 +27,36 @@ public class MixinGuiIngameForge { fra.angelica$getBatcher().beginBatch(); } + // ordinal 1 = "forgeHudText"; ordinal 0 ends "debug" before beginBatch runs. @Inject( method = "renderHUDText", - at = @At(value = "INVOKE", target = "net/minecraft/profiler/Profiler.endSection()V")) + at = @At(value = "INVOKE", target = "net/minecraft/profiler/Profiler.endSection()V", ordinal = 1)) private void angelica$endF3TextBatching(int width, int height, CallbackInfo ci) { FontRendererAccessor fra = (FontRendererAccessor) (Object) fontrenderer; + + final boolean depthWasEnabled = GLStateManager.getDepthTest().isEnabled(); + GLStateManager.disableDepthTest(); fra.angelica$getBatcher().endBatch(); + if (depthWasEnabled) { + GLStateManager.enableDepthTest(); + } + } + + @Inject(method = "renderHotbar", at = @At("HEAD"), remap = false) + private void angelica$startHotbarTextBatching(int width, int height, float partialTicks, CallbackInfo ci) { + final FontRendererAccessor fra = (FontRendererAccessor) (Object) fontrenderer; + fra.angelica$getBatcher().beginBatch(); + } + + @Inject(method = "renderHotbar", at = @At("RETURN"), remap = false) + private void angelica$endHotbarTextBatching(int width, int height, float partialTicks, CallbackInfo ci) { + final FontRendererAccessor fra = (FontRendererAccessor) (Object) fontrenderer; + + final boolean depthWasEnabled = GLStateManager.getDepthTest().isEnabled(); + GLStateManager.disableDepthTest(); + fra.angelica$getBatcher().endBatch(); + if (depthWasEnabled) { + GLStateManager.enableDepthTest(); + } } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java index 8101722e4..67716d5eb 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java @@ -1,30 +1,14 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.glsm; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -/** - * Controls GLSM cache tracking based on which GL context is active during splash screen lifecycle. - * - * Two GL contexts exist during splash: - * - SharedDrawable: Isolated context used by Client thread during splash, discarded after - * - DrawableGL: Main Display context that survives into the game (splash thread renders here) - * - * We only want to cache state changes made on DrawableGL, since SharedDrawable's state is irrelevant - * to the main game loop. - * - * GLStateManager.makeCurrent() automatically handles caching based on whether the drawable - * is DrawableGL or not. DrawableGL is captured early in OpenGlHelper.initializeTextures(). - */ @SuppressWarnings("deprecation") @Mixin(value = cpw.mods.fml.client.SplashProgress.class, remap = false) public class MixinSplashProgressCaching { - private static final Logger LOGGER = LogManager.getLogger("Angelica"); // VAOs aren't shared across GL contexts; the SharedDrawable the client thread just swapped // onto has none. Core profile (macOS) rejects glValidateProgram without one. @@ -32,10 +16,4 @@ public class MixinSplashProgressCaching { private static void angelica$bindSharedDrawableVAO(CallbackInfo ci) { GLStateManager.glBindVertexArray(GLStateManager.glGenVertexArrays()); } - - @Inject(method = "finish", at = @At("RETURN")) - private static void angelica$enableCachingOnFinish(CallbackInfo ci) { - GLStateManager.markSplashComplete(); - LOGGER.info("Splash Complete"); - } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/startup/MixinInitGLStateManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/startup/MixinInitGLStateManager.java index 55a536a51..cef5af5b5 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/startup/MixinInitGLStateManager.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/startup/MixinInitGLStateManager.java @@ -4,6 +4,7 @@ import com.gtnewhorizon.gtnhlib.core.GTNHLibCore; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.client.rendering.TextureTracker; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import com.gtnewhorizons.angelica.compat.DriverCompatabilityCheck; import com.gtnewhorizons.angelica.glsm.GLStateManager; @@ -11,9 +12,10 @@ import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.GLSMInitConfig; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.render.SelectionBoxRenderer; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUDisplayBridge; +import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.launchwrapper.Launch; import org.lwjgl.opengl.Display; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -23,11 +25,20 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = OpenGlHelper.class, priority = 100) public class MixinInitGLStateManager { + @Inject(method = "initializeTextures", at = @At("HEAD")) + private static void angelica$installSDLDrawable(CallbackInfo ci) { + SDLGPUDisplayBridge.ensureDrawableInstalled(); + } + @Inject(method = "initializeTextures", at = @At("RETURN")) private static void angelica$initializeGLStateManager(CallbackInfo ci) { final Minecraft mc = Minecraft.getMinecraft(); mc.gameSettings.fboEnable = true; // Angelica & many other GTNH features require FBO's GLStateManager.setDrawableGL(Display.getDrawable()); + if (AngelicaMod.lwjglDebug) { + System.setProperty(SystemProperties.KEY_CELERITAS_ENABLE_GL_DEBUG, "true"); + GLDebug.reloadDebugState(); + } GLStateManager.initialize(GLSMInitConfig.builder() .displaySize(mc.displayWidth, mc.displayHeight) .lwjglDebug(AngelicaMod.lwjglDebug) @@ -39,10 +50,6 @@ public class MixinInitGLStateManager { .postInitCallback(SelectionBoxRenderer::init) .build()); - if (Launch.blackboard != null && Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment"))) { - System.setProperty("angelica.dumpShaders", "true"); - } - GLSMHooks.LIGHTMAP_COORDS.addListener(event -> { OpenGlHelper.lastBrightnessX = event.x; OpenGlHelper.lastBrightnessY = event.y; diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityBeaconRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityBeaconRenderer.java new file mode 100644 index 000000000..8db20b7fd --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityBeaconRenderer.java @@ -0,0 +1,20 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.rendering.tesr.BeaconBeamMeshes; +import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer; +import net.minecraft.tileentity.TileEntityBeacon; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(TileEntityBeaconRenderer.class) +public class MixinTileEntityBeaconRenderer { + + @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityBeacon;DDDF)V", at = @At("HEAD"), cancellable = true) + private void angelica$batchBeam(TileEntityBeacon beacon, double x, double y, double z, float partialTicks, CallbackInfo ci) { + if (BeaconBeamMeshes.render(beacon, x, y, z, partialTicks)) { + ci.cancel(); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityChestRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityChestRenderer.java new file mode 100644 index 000000000..deb58e616 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityChestRenderer.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.rendering.tesr.VanillaModelMeshes; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.model.ModelChest; +import net.minecraft.client.model.ModelLargeChest; +import net.minecraft.client.renderer.tileentity.TileEntityChestRenderer; +import net.minecraft.tileentity.TileEntityChest; +import net.minecraft.util.ResourceLocation; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(TileEntityChestRenderer.class) +public abstract class MixinTileEntityChestRenderer { + + @Shadow @Final private static ResourceLocation field_147507_b; // trapped_double + @Shadow @Final private static ResourceLocation field_147508_c; // christmas_double + @Shadow @Final private static ResourceLocation field_147505_d; // normal_double + @Shadow @Final private static ResourceLocation field_147506_e; // trapped + @Shadow @Final private static ResourceLocation field_147503_f; // christmas + @Shadow @Final private static ResourceLocation field_147504_g; // normal + @Shadow private boolean field_147509_j; // Christmas season flag + + @WrapOperation(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityChest;DDDF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelChest;renderAll()V")) + private void angelica$cachedRenderAll(ModelChest model, Operation original, @Local(argsOnly = true) TileEntityChest chest) { + if (!AngelicaConfig.enableTESRChestCache || chest.getWorldObj() == null) { + original.call(model); + return; + } + final boolean isDouble = model instanceof ModelLargeChest; + final boolean trapped = chest.func_145980_j() == 1; + final ResourceLocation texture = isDouble + ? (trapped ? field_147507_b : field_147509_j ? field_147508_c : field_147505_d) + : (trapped ? field_147506_e : field_147509_j ? field_147503_f : field_147504_g); + VanillaModelMeshes.renderChest(model, texture, isDouble); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityEnderChestRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityEnderChestRenderer.java new file mode 100644 index 000000000..112867bd2 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityEnderChestRenderer.java @@ -0,0 +1,30 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.rendering.tesr.VanillaModelMeshes; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.model.ModelChest; +import net.minecraft.client.renderer.tileentity.TileEntityEnderChestRenderer; +import net.minecraft.tileentity.TileEntityEnderChest; +import net.minecraft.util.ResourceLocation; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(TileEntityEnderChestRenderer.class) +public abstract class MixinTileEntityEnderChestRenderer { + + @Shadow @Final private static ResourceLocation field_147520_b; // ender + + @WrapOperation(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityEnderChest;DDDF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelChest;renderAll()V")) + private void angelica$cachedRenderAll(ModelChest model, Operation original, @Local(argsOnly = true) TileEntityEnderChest chest) { + if (!AngelicaConfig.enableTESRChestCache || chest.getWorldObj() == null) { + original.call(model); + return; + } + VanillaModelMeshes.renderChest(model, field_147520_b, false); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityRendererDispatcher.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityRendererDispatcher.java new file mode 100644 index 000000000..566e399be --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntityRendererDispatcher.java @@ -0,0 +1,20 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.rendering.tesr.TesrProviderDispatch; +import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.tileentity.TileEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(TileEntityRendererDispatcher.class) +public class MixinTileEntityRendererDispatcher { + + @Redirect(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/tileentity/TileEntitySpecialRenderer;renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V")) + private void angelica$dispatchTesrProvider(TileEntitySpecialRenderer renderer, TileEntity te, double x, double y, double z, float partialTicks) { + if (!TesrProviderDispatch.tryRender(renderer, te, x, y, z)) { + renderer.renderTileEntityAt(te, x, y, z, partialTicks); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySignRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySignRenderer.java new file mode 100644 index 000000000..a28db987d --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySignRenderer.java @@ -0,0 +1,40 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; +import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; +import com.gtnewhorizons.angelica.rendering.tesr.VanillaModelMeshes; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.model.ModelSign; +import net.minecraft.client.renderer.tileentity.TileEntitySignRenderer; +import net.minecraft.tileentity.TileEntitySign; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(TileEntitySignRenderer.class) +public abstract class MixinTileEntitySignRenderer { + + @Redirect(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntitySign;DDDF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelSign;renderSign()V")) + private void angelica$renderBoardCached(ModelSign model) { + VanillaModelMeshes.renderSign(model); + } + + @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntitySign;DDDF)V", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glDepthMask(Z)V", ordinal = 0, remap = false, shift = At.Shift.AFTER)) + private void angelica$beginSignTextBatch(TileEntitySign sign, double x, double y, double z, float partialTicks, CallbackInfo ci, @Local(ordinal = 0) FontRenderer fontRenderer) { + final BatchingFontRenderer batcher = ((FontRendererAccessor) fontRenderer).angelica$getBatcher(); + if (batcher != null) { + batcher.beginDeferredBatch(); + } + } + + @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntitySign;DDDF)V", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glDepthMask(Z)V", ordinal = 1, remap = false, shift = At.Shift.BEFORE)) + private void angelica$endSignTextBatch(TileEntitySign sign, double x, double y, double z, float partialTicks, CallbackInfo ci, @Local(ordinal = 0) FontRenderer fontRenderer) { + final BatchingFontRenderer batcher = ((FontRendererAccessor) fontRenderer).angelica$getBatcher(); + if (batcher != null) { + batcher.endDeferredBatch(); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySkullRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySkullRenderer.java new file mode 100644 index 000000000..9a1c9ded8 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tesr/MixinTileEntitySkullRenderer.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tesr; + +import com.gtnewhorizons.angelica.rendering.tesr.VanillaModelMeshes; +import net.minecraft.client.model.ModelSkeletonHead; +import net.minecraft.client.renderer.tileentity.TileEntitySkullRenderer; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.entity.Entity; +import net.minecraft.util.ResourceLocation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(TileEntitySkullRenderer.class) +public abstract class MixinTileEntitySkullRenderer extends TileEntitySpecialRenderer { + + @Unique + private ResourceLocation angelica$skullTexture; + + @Redirect(method = "func_152674_a(FFFIFILcom/mojang/authlib/GameProfile;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/tileentity/TileEntitySkullRenderer;bindTexture(Lnet/minecraft/util/ResourceLocation;)V")) + private void angelica$captureSkullTexture(TileEntitySkullRenderer self, ResourceLocation texture) { + angelica$skullTexture = texture; + this.bindTexture(texture); + } + + @Redirect(method = "func_152674_a(FFFIFILcom/mojang/authlib/GameProfile;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelSkeletonHead;render(Lnet/minecraft/entity/Entity;FFFFFF)V")) + private void angelica$renderSkullCached(ModelSkeletonHead model, Entity entity, float limbSwing, float limbYaw, float age, float yaw, float pitch, float scale) { + if (!VanillaModelMeshes.renderSkull(model, angelica$skullTexture, yaw, pitch, scale)) { + model.render(entity, limbSwing, limbYaw, age, yaw, pitch, scale); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil.java index 07da817e4..c8a57f65a 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil.java @@ -1,10 +1,14 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.textures; +import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.minecraft.client.renderer.texture.TextureUtil; +import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -22,4 +26,47 @@ public class MixinTextureUtil { private static void angelica$setMaxLevel(int textureId, int mipmapLevels, int width, int height, float anisotropicFiltering, CallbackInfo ci) { GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, mipmapLevels); } + + @Unique private static int angelica$savedFilterTextureId; + + @Inject(method = "func_152777_a(ZZF)V", at = @At("HEAD")) + private static void angelica$captureSaveBoundId(boolean blurred, boolean mipmap, float aniso, CallbackInfo ci) { + angelica$savedFilterTextureId = GLStateManager.getBoundTextureForServerState(); + } + + @Redirect(method = "func_147945_b()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureUtil;func_147952_b(II)V")) + private static void angelica$restoreFilterOnSavedTexture(int min, int mag) { + final int id = angelica$savedFilterTextureId; + if (id != 0) { + if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.NONE) { + RenderSystem.texParameteri(id, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, min); + RenderSystem.texParameteri(id, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag); + } else { + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, min); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag); + } + } else { + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, min); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag); + } + } + + @Redirect(method = "func_147945_b()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureUtil;func_152778_a(F)V")) + private static void angelica$restoreAnisoOnSavedTexture(float aniso) { + final int id = angelica$savedFilterTextureId; + if (id != 0) { + if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.NONE) { + RenderSystem.texParameterf(id, GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); + } else { + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); + } + } else { + GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); + } + } + + @Inject(method = "func_147945_b()V", at = @At("RETURN")) + private static void angelica$clearSavedAfterRestore(CallbackInfo ci) { + angelica$savedFilterTextureId = 0; + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil_OptimizeMipmap.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil_OptimizeMipmap.java deleted file mode 100644 index d6d2a427f..000000000 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/textures/MixinTextureUtil_OptimizeMipmap.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.gtnewhorizons.angelica.mixins.early.angelica.textures; - -import com.gtnewhorizons.angelica.utils.Mipmaps; -import net.minecraft.client.renderer.texture.TextureUtil; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(TextureUtil.class) -public class MixinTextureUtil_OptimizeMipmap { - - /** - * @author SuperCoder79 - * @reason Rewrite mipmap color math to use memoized value array instead of using Math.pow directly - */ - @Overwrite - private static int func_147943_a(int one, int two, int three, int four, boolean alpha) { - if (!alpha) { - final int a = Mipmaps.getColorComponent(one, two, three, four, 24); - final int r = Mipmaps.getColorComponent(one, two, three, four, 16); - final int g = Mipmaps.getColorComponent(one, two, three, four, 8); - final int b = Mipmaps.getColorComponent(one, two, three, four, 0); - return a << 24 | r << 16 | g << 8 | b; - } else { - float a = 0.0F; - float r = 0.0F; - float g = 0.0F; - float b = 0.0F; - if (one >> 24 != 0) { - a += Mipmaps.get(one >> 24); - r += Mipmaps.get(one >> 16); - g += Mipmaps.get(one >> 8); - b += Mipmaps.get(one >> 0); - } - - if (two >> 24 != 0) { - a += Mipmaps.get(two >> 24); - r += Mipmaps.get(two >> 16); - g += Mipmaps.get(two >> 8); - b += Mipmaps.get(two >> 0); - } - - if (three >> 24 != 0) { - a += Mipmaps.get(three >> 24); - r += Mipmaps.get(three >> 16); - g += Mipmaps.get(three >> 8); - b += Mipmaps.get(three >> 0); - } - - if (four >> 24 != 0) { - a += Mipmaps.get(four >> 24); - r += Mipmaps.get(four >> 16); - g += Mipmaps.get(four >> 8); - b += Mipmaps.get(four >> 0); - } - - a /= 4.0F; - r /= 4.0F; - g /= 4.0F; - b /= 4.0F; - int ia = (int) (Math.pow((double) a, 0.45454545454545453) * 255.0); - final int ir = (int) (Math.pow((double) r, 0.45454545454545453) * 255.0); - final int ig = (int) (Math.pow((double) g, 0.45454545454545453) * 255.0); - final int ib = (int) (Math.pow((double) b, 0.45454545454545453) * 255.0); - if (ia < 96) { - ia = 0; - } - - return ia << 24 | ir << 16 | ig << 8 | ib; - } - } -} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraftServer_Tracy.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraftServer_Tracy.java new file mode 100644 index 000000000..eb0f6c717 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraftServer_Tracy.java @@ -0,0 +1,25 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tracy; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import net.minecraft.server.MinecraftServer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MinecraftServer.class) +public class MixinMinecraftServer_Tracy { + private static final long P_MSPT = Tracy.plotHandle("mspt"); + private static final long P_ALLOC_RATE_SV = Tracy.plotHandle("allocRateSv", TracyBackend.PLOT_FORMAT_MEMORY); + + @Shadow private int tickCounter; + + @Inject(method = "tick", at = @At("RETURN")) + private void angelica$tracyServerTick(CallbackInfo ci) { + Tracy.frameMark("server tick"); + Tracy.plot(P_MSPT, ((MinecraftServer) (Object) this).tickTimeArray[tickCounter % 100] / 1.0e6); + Tracy.plotAllocRate(P_ALLOC_RATE_SV); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraft_Tracy.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraft_Tracy.java new file mode 100644 index 000000000..0d9872cba --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinMinecraft_Tracy.java @@ -0,0 +1,52 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tracy; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.profiling.GpuFrameLagMeter; +import com.gtnewhorizons.angelica.profiling.TracyFramePlots; +import net.minecraft.client.Minecraft; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Minecraft.class) +public class MixinMinecraft_Tracy { + private static final Tracy.ZoneId Z_SWAP_BUFFERS = Tracy.zoneId("swapBuffers", Tracy.COLOR_SWAP); + + @Inject(method = "runGameLoop", at = @At("RETURN")) + private void angelica$tracyFrameMark(CallbackInfo ci) { + TracyFramePlots.onFrame((Minecraft) (Object) this); + GpuFrameLagMeter.onFrame(); + Tracy.frameMark(); + Tracy.gpuCollect(); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runTick()V")) + private void angelica$tracyGpuOffForTick(CallbackInfo ci) { + Tracy.setGpuZonesEnabled(false); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runTick()V", shift = At.Shift.AFTER)) + private void angelica$tracyGpuOnAfterTick(CallbackInfo ci) { + Tracy.setGpuZonesEnabled(true); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;func_147120_f()V")) + private void angelica$tracySwapBegin(CallbackInfo ci) { + Tracy.beginZone(Z_SWAP_BUFFERS); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;func_147120_f()V", shift = At.Shift.AFTER)) + private void angelica$tracySwapEnd(CallbackInfo ci) { + Tracy.endZone(); + } + + // runGameLoop opens a second "root" section after the render phase; renaming it keeps + // client statistics from merging two different scopes under one srcloc. + @ModifyConstant(method = "runGameLoop", constant = @Constant(stringValue = "root", ordinal = 1)) + private String angelica$tracyRenameSecondRoot(String constant) { + return "root2"; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinNetHandlerPlayServer_Tracy.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinNetHandlerPlayServer_Tracy.java new file mode 100644 index 000000000..71af215f1 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinNetHandlerPlayServer_Tracy.java @@ -0,0 +1,21 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tracy; + +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.server.MinecraftServer; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +// Vanilla onNetworkTick opens startSection("keepAlive") and never ends it. +@Mixin(NetHandlerPlayServer.class) +public class MixinNetHandlerPlayServer_Tracy { + @Shadow @Final private MinecraftServer serverController; + + @Inject(method = "onNetworkTick", at = @At("RETURN")) + private void angelica$tracyBalanceKeepAlive(CallbackInfo ci) { + this.serverController.theProfiler.endSection(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinProfiler_Tracy.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinProfiler_Tracy.java new file mode 100644 index 000000000..14f146e5e --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinProfiler_Tracy.java @@ -0,0 +1,21 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tracy; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import net.minecraft.profiler.Profiler; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Profiler.class) +public class MixinProfiler_Tracy { + @Inject(method = "startSection(Ljava/lang/String;)V", at = @At("HEAD")) + private void angelica$tracyStartSection(String name, CallbackInfo ci) { + Tracy.beginSection(name); + } + + @Inject(method = "endSection()V", at = @At("HEAD")) + private void angelica$tracyEndSection(CallbackInfo ci) { + Tracy.endZone(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinRenderGlobal_Tracy.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinRenderGlobal_Tracy.java new file mode 100644 index 000000000..62fc98fc7 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/tracy/MixinRenderGlobal_Tracy.java @@ -0,0 +1,43 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.tracy; + +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.profiling.RenderClassTimings; +import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.renderer.RenderGlobal; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(RenderGlobal.class) +public class MixinRenderGlobal_Tracy { + private static final Tracy.ZoneId Z_ENTITY_DISPATCH = Tracy.zoneId("entityDispatch", Tracy.COLOR_CLIENT); + + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=entities", shift = At.Shift.AFTER)) + private void angelica$beginEntityDispatchZone(CallbackInfo ci) { + Tracy.beginZone(Z_ENTITY_DISPATCH); + } + + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=blockentities")) + private void angelica$endEntityDispatchZone(CallbackInfo ci) { + Tracy.endZone(); + } + + @WrapOperation(method = "renderEntities", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z")) + private boolean angelica$timeEntityRender(RenderManager instance, Entity entity, float partialTicks, Operation original) { + final long start = System.nanoTime(); + if (TesrAttribution.currentRenderable == null && entity != null) { + TesrAttribution.currentRenderable = entity.getClass(); + } + try { + return original.call(instance, entity, partialTicks); + } finally { + TesrAttribution.currentRenderable = null; + RenderClassTimings.ENTITY.add(entity.getClass(), System.nanoTime() - start); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/vbo/MixinFramebuffer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/vbo/MixinFramebuffer.java index 644f24c21..9dff12f3f 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/vbo/MixinFramebuffer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/vbo/MixinFramebuffer.java @@ -33,6 +33,7 @@ public abstract class MixinFramebuffer { GLStateManager.disableLighting(); GLStateManager.disableAlphaTest(); GLStateManager.disableBlend(); + GLStateManager.disableCull(); GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, framebufferTexture); PostProcessingHelper.bindFullscreenVAO(); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/debug/MixinGLDebug.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/debug/MixinGLDebug.java new file mode 100644 index 000000000..b3cf7dbce --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/debug/MixinGLDebug.java @@ -0,0 +1,17 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.debug; + +import org.embeddedt.embeddium.impl.gl.debug.GLDebug; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(value = GLDebug.class, remap = false) +public class MixinGLDebug { + + @Inject(method = "nameObject", at = @At("HEAD")) + private static void angelica$bridgeToBackendLabels(int id, int object, String name, CallbackInfo ci) { + // Stupid name collisions + com.gtnewhorizons.angelica.glsm.GLDebug.nameObject(id, object, name); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/frustum/MixinFrustrum.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/frustum/MixinFrustrum.java index 3427684ba..085fd6eef 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/frustum/MixinFrustrum.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/frustum/MixinFrustrum.java @@ -5,6 +5,7 @@ import net.minecraft.client.renderer.culling.ClippingHelper; import net.minecraft.client.renderer.culling.Frustrum; import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider; +import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum; import org.joml.FrustumIntersection; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Final; @@ -31,9 +32,9 @@ public abstract class MixinFrustrum implements ViewportProvider { @Override public Viewport sodium$createViewport() { // Shadow frustum subclasses override this via their own ViewportProvider impl. - // This default handles vanilla Frustrum only, using the per-instance snapshot + // This default handles vanilla Frustrum only, using the per-instance snapshot. return new Viewport( - this.celeritas$snapshot::testAab, + new SimpleFrustum(this.celeritas$snapshot), new Vector3d(this.xPosition, this.yPosition, this.zPosition) ); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkRenderer.java new file mode 100644 index 000000000..c32ce4fcc --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkRenderer.java @@ -0,0 +1,202 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.culling.FrustumExtractor; +import com.gtnewhorizons.angelica.rendering.culling.GpuIndirectMultiDrawEmitter; +import com.gtnewhorizons.angelica.mixins.interfaces.SectionRenderDataStorageRegionAccessor; +import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaRenderPassConfiguration; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import net.coderbot.iris.pipeline.ShadowRenderer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; +import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices; +import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer; +import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.nio.ByteBuffer; +import java.util.Iterator; + +@Mixin(value = DefaultChunkRenderer.class, remap = false) +public abstract class MixinDefaultChunkRenderer { + + @Shadow @Final private MultiDrawEmitter emitter; + + @Shadow protected abstract boolean useBlockFaceCulling(); + + @Unique private ByteBuffer angelica$frustumUboBytes; + @Unique private Matrix4f angelica$mvp; + @Unique private Matrix4f angelica$mvNoTranslation; + @Unique private int angelica$passOutputBase; + @Unique private ChunkPrimitiveType angelica$primitiveType; + + @Inject(method = "render", at = @At("HEAD")) + private void angelica$gpuPreWalkPass(ChunkRenderMatrices matrices, CommandList commandList, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, CallbackInfo ci) { + if (!(emitter instanceof GpuIndirectMultiDrawEmitter gpu)) return; + + if (renderPass == AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS && renderLists.hasPass(renderPass) && gpu.selectPreparedSecondPass()) { + return; + } + if (!renderLists.hasPass(renderPass)) return; + + final boolean combined = renderPass == AngelicaRenderPassConfiguration.SOLID_PASS && AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS); + + final int indexPointerMask = renderPass.isSorted() ? 0xFFFFFFFF : 0; + if (combined) { + gpu.beginCombinedPasses(0, 0); + } else { + gpu.beginCullPass(indexPointerMask); + } + angelica$passOutputBase = 0; + angelica$primitiveType = null; + + if (!gpu.isComputeActiveThisPass()) { + return; + } + + if (angelica$frustumUboBytes == null) { + angelica$frustumUboBytes = FrustumExtractor.allocateUboByteBuffer(); + } + final boolean shadow = ShadowRenderer.ACTIVE; + final Matrix4fc proj = matrices.projection(); + final Matrix4fc mv = matrices.modelView(); + if (angelica$mvp == null) angelica$mvp = new Matrix4f(); + if (angelica$mvNoTranslation == null) angelica$mvNoTranslation = new Matrix4f(); + angelica$mvNoTranslation.set(mv).setTranslation(0f, 0f, 0f); + proj.mul(angelica$mvNoTranslation, angelica$mvp); + final float camX = (float) camera.intX + camera.fracX; + final float camY = (float) camera.intY + camera.fracY; + final float camZ = (float) camera.intZ + camera.fracZ; + FrustumExtractor.writeStd140(angelica$mvp, 0, 0, angelica$frustumUboBytes); + FrustumExtractor.patchCameraWorld(camX, camY, camZ, angelica$frustumUboBytes); + FrustumExtractor.patchBypassFrustum(shadow, angelica$frustumUboBytes); + + gpu.setFrustumUboBytes(angelica$frustumUboBytes); + + gpu.syncSectionMetaIfDirty(); + + angelica$walkPass(gpu, renderLists, renderPass, occlusionCamera); + if (combined) { + gpu.startSecondPass(); + angelica$walkPass(gpu, renderLists, AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS, occlusionCamera); + gpu.finishCombinedBuild(); + } + + if (angelica$primitiveType != null) { + FrustumExtractor.patchPrimitiveRatio(angelica$primitiveType.getVerticesPerPrimitive(), + angelica$primitiveType.getIndexBufferElementsPerPrimitive(), angelica$frustumUboBytes); + } + } + + @Unique + private void angelica$walkPass(GpuIndirectMultiDrawEmitter gpu, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera) { + final boolean useFaceCulling = useBlockFaceCulling() && !renderPass.isSorted(); + final boolean reverse = renderPass.isReverseOrder(); + final boolean mergeRuns = !renderPass.isSorted(); + final Iterator it = renderLists.iterator(reverse); + while (it.hasNext()) { + final ChunkRenderList list = it.next(); + final RenderRegion region = list.getRegion(); + final SectionRenderDataStorage storage = region.getStorage(renderPass); + if (storage == null) continue; + final byte[] sections = list.getSectionsWithGeometry(); + final int sectionCount = list.getSectionsWithGeometryCount(); + if (sectionCount == 0) continue; + final SectionRenderDataUnsafe.Strategy layout = storage.getStorageStrategy(); + final ChunkPrimitiveType primitiveType = storage.getPrimitiveType(); + if (angelica$primitiveType == null) { + angelica$primitiveType = primitiveType; + } else if (angelica$primitiveType.getVerticesPerPrimitive() != primitiveType.getVerticesPerPrimitive() || angelica$primitiveType.getIndexBufferElementsPerPrimitive() != primitiveType.getIndexBufferElementsPerPrimitive()) { + throw new IllegalStateException("Batched cull dispatch spans passes with differing primitive ratios: " + angelica$primitiveType + " vs " + primitiveType); + } + final SectionRenderDataStorageRegionAccessor accessor = (SectionRenderDataStorageRegionAccessor) storage; + final int[] slotCache = accessor.angelica$getSlotCache(); + if (slotCache == null) continue; + + gpu.reserveSections(list.getSectionsWithGeometryCount()); + + final int regionOriginX = region.getChunkX(); + final int regionOriginY = region.getChunkY(); + final int regionOriginZ = region.getChunkZ(); + + final int regionDrawStart = angelica$passOutputBase; + int regionDrawCount = 0; + int regionMaxElems = 0; + int regionEntryStart = -1; + int regionEntryCount = 0; + + int cursor = reverse ? sectionCount - 1 : 0; + final int step = reverse ? -1 : 1; + + for (int i = 0; i < sectionCount; i++, cursor += step) { + final int sectionIndex = sections[cursor] & 0xFF; + final int chunkX = regionOriginX + LocalSectionIndex.unpackX(sectionIndex); + final int chunkY = regionOriginY + LocalSectionIndex.unpackY(sectionIndex); + final int chunkZ = regionOriginZ + LocalSectionIndex.unpackZ(sectionIndex); + + final long pMeshData = storage.getDataPointer(sectionIndex); + int slices = useFaceCulling ? BatchAssembler.getVisibleFaces(occlusionCamera.intX, occlusionCamera.intY, occlusionCamera.intZ, chunkX, chunkY, chunkZ) : ModelQuadFacing.ALL; + slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData); + if (slices == 0) continue; + + final int slot = slotCache[sectionIndex]; + if (slot < 0) continue; + + final long runs = mergeRuns ? BatchAssembler.packRuns(slices & 0x7F) : 0L; + final int sectionDraws = mergeRuns ? BatchAssembler.runCount(runs) : Integer.bitCount(slices & 0x7F); + final int entryIdx = gpu.appendSection(slot, slices, angelica$passOutputBase); + if (regionEntryStart < 0) regionEntryStart = entryIdx; + regionEntryCount++; + angelica$passOutputBase += sectionDraws; + regionDrawCount += sectionDraws; + + int maxElems = 0; + if (mergeRuns) { + for (int run = 0; run < sectionDraws; run++) { + final int startVertex = layout.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run)); + final int endVertex = layout.getRunVertexEnd(pMeshData, BatchAssembler.runLast(runs, run), primitiveType); + final int ec = SectionRenderDataUnsafe.elementsForVertices(endVertex - startVertex, primitiveType); + if (ec > maxElems) maxElems = ec; + } + } else { + for (int f = 0; f < ModelQuadFacing.COUNT; f++) { + final int ec = layout.getElementCount(pMeshData, f, primitiveType); + if (ec > maxElems) maxElems = ec; + } + } + if (maxElems > regionMaxElems) regionMaxElems = maxElems; + } + + if (regionDrawCount > 0) { + gpu.recordRegion(region, regionDrawStart, regionDrawCount, regionEntryStart, regionEntryCount, regionMaxElems); + } + } + } + + @Inject(method = "render", at = @At("RETURN")) + private void angelica$gpuEndPass(ChunkRenderMatrices matrices, CommandList commandList, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, CallbackInfo ci) { + if (emitter instanceof GpuIndirectMultiDrawEmitter gpu) { + gpu.endPass(); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkShaderInterface.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkShaderInterface.java new file mode 100644 index 000000000..ca29a3345 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinDefaultChunkShaderInterface.java @@ -0,0 +1,84 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizons.angelica.rendering.celeritas.SectionAgeMath; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloatArray; +import org.embeddedt.embeddium.impl.render.chunk.shader.DefaultChunkShaderInterface; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.util.WeakHashMap; + +/** Skips section-age uniform uploads that cannot have changed; see {@link SectionAgeMath} */ +@Mixin(value = DefaultChunkShaderInterface.class, remap = false) +public abstract class MixinDefaultChunkShaderInterface { + + @Shadow @Final private GlUniformFloatArray uniformChunkAges; + + /** Per-region {@link SectionAgeMath} skip state. */ + @Unique private final WeakHashMap angelica$ageState = new WeakHashMap<>(); + + @Unique private FloatBuffer angelica$ageScratch; + + public void setSectionAges(long timestamp, long[] loadTimes, long newestLoadTime) { + final int n = loadTimes.length; + if (this.uniformChunkAges == null || n == 0) return; + + final long tsQ = SectionAgeMath.quantize(timestamp); + long[] state = angelica$ageState.get(loadTimes); + if (state != null && SectionAgeMath.canSkip(state, newestLoadTime, tsQ)) { + return; + } + + final boolean allSaturated = angelica$buildAndUpload(tsQ, loadTimes, n); + + if (state == null) { + state = SectionAgeMath.newState(); + angelica$ageState.put(loadTimes, state); + } + SectionAgeMath.record(state, newestLoadTime, tsQ, allSaturated); + } + + /** + * @author Angelica + * @reason reused direct buffer + */ + @Overwrite + public void setSectionAges(long timestamp, long[] loadTimes) { + final int n = loadTimes.length; + if (this.uniformChunkAges == null || n == 0) return; + angelica$buildAndUpload(timestamp, loadTimes, n); + } + + @Unique + private boolean angelica$buildAndUpload(long timestamp, long[] loadTimes, int n) { + FloatBuffer buf = angelica$ageScratch; + if (buf == null || buf.capacity() < n) { + buf = ByteBuffer.allocateDirect(n * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); + angelica$ageScratch = buf; + } + long ptr = MemoryUtilities.memAddress(buf); + boolean allSaturated = true; + for (int i = 0; i < n; i++) { + final long ageMs = (timestamp - loadTimes[i]) / 1_000_000L; + final float v; + if (ageMs >= 30000L) { + v = 30000f; + } else { + v = (float) ageMs; + allSaturated = false; + } + MemoryUtilities.memPutFloat(ptr, v); + ptr += 4; + } + buf.position(0).limit(n); + this.uniformChunkAges.set(buf); + return allSaturated; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java index efd17763e..17122ff89 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java @@ -4,12 +4,14 @@ import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.event.RenderChunkEvent; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.mixins.interfaces.IRenderGlobalExt; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import net.coderbot.iris.Iris; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.pipeline.HandRenderer; @@ -53,9 +55,18 @@ import static org.joml.Math.lerp; */ @Mixin(value = RenderGlobal.class, priority = 900) public class MixinRenderGlobal implements IRenderGlobalExt { + @Unique private static final long P_BLOCK_ENTITIES_RENDERED = Tracy.plotHandle("blockEntitiesRendered"); + @Unique private static final Tracy.ZoneId Z_MT_QUEUE = Tracy.zoneId("mtQueue", Tracy.COLOR_TERRAIN); + @Shadow public Minecraft mc; @Shadow @Final private TextureManager renderEngine; + @Unique private static final String SECTION_SOLID = "draw_chunk_layer_solid"; + @Unique private static final String SECTION_CUTOUT_MIPPED = "draw_chunk_layer_cutout_mipped"; + @Unique private static final String SECTION_TRANSLUCENT = "draw_chunk_layer_translucent"; + @Unique private static final String SECTION_SHADOW_SOLID = "shadow_draw_chunk_layer_solid"; + @Unique private static final String SECTION_SHADOW_CUTOUT_MIPPED = "shadow_draw_chunk_layer_cutout_mipped"; + @Unique private static final String SECTION_SHADOW_TRANSLUCENT = "shadow_draw_chunk_layer_translucent"; @Unique private CeleritasWorldRenderer celeritas$renderer; @Unique private int celeritas$frame; @Unique private float celeritas$lastFov; @@ -156,14 +167,15 @@ public class MixinRenderGlobal implements IRenderGlobalExt { final double camY = lerp(entity.lastTickPosY, entity.posY, partialTicks) + entity.getEyeHeight(); final double camZ = lerp(entity.lastTickPosZ, entity.posZ, partialTicks); + final boolean shadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); try { if (pass == 0) { - mc.mcProfiler.endStartSection("draw_chunk_layer_solid"); + mc.mcProfiler.endStartSection(shadow ? SECTION_SHADOW_SOLID : SECTION_SOLID); this.celeritas$renderer.drawChunkLayer(BlockRenderLayer.SOLID, camX, camY, camZ); - mc.mcProfiler.endStartSection("draw_chunk_layer_cutout_mipped"); + mc.mcProfiler.endStartSection(shadow ? SECTION_SHADOW_CUTOUT_MIPPED : SECTION_CUTOUT_MIPPED); this.celeritas$renderer.drawChunkLayer(BlockRenderLayer.CUTOUT_MIPPED, camX, camY, camZ); } else { - mc.mcProfiler.endStartSection("draw_chunk_layer_translucent"); + mc.mcProfiler.endStartSection(shadow ? SECTION_SHADOW_TRANSLUCENT : SECTION_TRANSLUCENT); this.celeritas$renderer.drawChunkLayer(BlockRenderLayer.TRANSLUCENT, camX, camY, camZ); RenderChunkEvent.post(); } @@ -249,7 +261,8 @@ public class MixinRenderGlobal implements IRenderGlobalExt { GbufferPrograms.beginBlockEntities(); GbufferPrograms.setBlockEntityDefaults(); } - this.celeritas$renderer.renderBlockEntities(partialTicks); + final int blockEntitiesRendered = this.celeritas$renderer.renderBlockEntities(partialTicks); + if (Tracy.ENABLED) Tracy.plotInt(P_BLOCK_ENTITIES_RENDERED, blockEntitiesRendered); if (Iris.enabled) { GbufferPrograms.endBlockEntities(); } @@ -281,13 +294,25 @@ public class MixinRenderGlobal implements IRenderGlobalExt { final long startTime = System.nanoTime(); int tasksRan = 0; - while (System.nanoTime() - startTime < BUDGET_NS) { - if (AngelicaRenderQueue.processTasks(1) == 0) - break; - tasksRan++; + long longestTaskNs = 0; + + if (Tracy.ENABLED) Tracy.beginZone(Z_MT_QUEUE); + try { + long taskStart = startTime; + while (taskStart - startTime < BUDGET_NS) { + if (AngelicaRenderQueue.processTasks(1) == 0) + break; + tasksRan++; + final long taskEnd = System.nanoTime(); + final long elapsed = taskEnd - taskStart; + if (elapsed > longestTaskNs) longestTaskNs = elapsed; + taskStart = taskEnd; + } + } finally { + if (Tracy.ENABLED) Tracy.endZone(); } - AngelicaRenderQueue.recordFrameStats(tasksRan, System.nanoTime() - startTime); + AngelicaRenderQueue.recordFrameStats(tasksRan, System.nanoTime() - startTime, longestTaskNs); return true; } @@ -297,6 +322,7 @@ public class MixinRenderGlobal implements IRenderGlobalExt { HandRenderer.INSTANCE.renderSolid(camera.getPartialTicks(), camera, mc.renderGlobal, pipeline); mc.mcProfiler.endStartSection("iris_pre_translucent"); pipeline.beginTranslucents(); + TesrBatchRenderer.INSTANCE.flushAfterDeferred(); } @Redirect(method = "renderEntities", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;isInRangeToRender3d(DDD)Z")) diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderListManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderListManager.java new file mode 100644 index 000000000..263f6b72e --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderListManager.java @@ -0,0 +1,21 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; + +import com.gtnewhorizons.angelica.mixins.interfaces.RenderListManagerAccessor; +import org.embeddedt.embeddium.impl.render.chunk.lists.RenderListManager; +import org.embeddedt.embeddium.impl.render.chunk.lists.VisibleChunkCollector; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.concurrent.CompletableFuture; + +@Mixin(value = RenderListManager.class, remap = false) +public class MixinRenderListManager implements RenderListManagerAccessor { + + @Shadow + private CompletableFuture currentOcclusionFuture; + + @Override + public boolean angelica$hasOcclusionFutureInFlight() { + return currentOcclusionFuture != null; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderRegion.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderRegion.java new file mode 100644 index 000000000..5cc935f76 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderRegion.java @@ -0,0 +1,25 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; + +import com.gtnewhorizons.angelica.rendering.culling.RenderPassIndex; +import com.gtnewhorizons.angelica.mixins.interfaces.SectionRenderDataStorageRegionAccessor; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = RenderRegion.class, remap = false) +public abstract class MixinRenderRegion { + + @Inject(method = "createStorage", at = @At("RETURN")) + private void angelica$tagStorageWithRegion(TerrainRenderPass pass, RenderPassConfiguration renderPassConfiguration, CallbackInfoReturnable cir) { + final SectionRenderDataStorage storage = cir.getReturnValue(); + if (storage instanceof SectionRenderDataStorageRegionAccessor a) { + a.angelica$setRegion((RenderRegion) (Object) this); + a.angelica$setPassIndex(RenderPassIndex.indexOf(pass)); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderSectionManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderSectionManager.java index 6e13210ef..5d943539e 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderSectionManager.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderSectionManager.java @@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor import it.unimi.dsi.fastutil.longs.Long2ReferenceMap; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSectionManager; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -13,13 +14,16 @@ import java.util.concurrent.ConcurrentLinkedDeque; @Mixin(value = RenderSectionManager.class, remap = false) public class MixinRenderSectionManager implements RenderSectionManagerAccessor { - @Shadow - @Final - private Long2ReferenceMap sectionByPosition; + @Shadow @Final private Long2ReferenceMap sectionByPosition; + + @Shadow @Final private ConcurrentLinkedDeque asyncSubmittedTasks; + + @Shadow @Final private RenderRegionManager regions; @Shadow - @Final - private ConcurrentLinkedDeque asyncSubmittedTasks; + private float getSearchDistance() { + throw new AssertionError(); + } @Override public Long2ReferenceMap angelica$getSectionByPosition() { @@ -30,4 +34,14 @@ public class MixinRenderSectionManager implements RenderSectionManagerAccessor { public ConcurrentLinkedDeque angelica$getAsyncSubmittedTasks() { return asyncSubmittedTasks; } + + @Override + public RenderRegionManager angelica$getRegions() { + return regions; + } + + @Override + public float angelica$getSearchDistance() { + return getSearchDistance(); + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinSectionRenderDataStorage.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinSectionRenderDataStorage.java new file mode 100644 index 000000000..a27ca87a1 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinSectionRenderDataStorage.java @@ -0,0 +1,105 @@ +package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; + +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.mixins.interfaces.SectionRenderDataStorageRegionAccessor; +import org.embeddedt.embeddium.impl.gl.arena.GlBufferSegment; +import org.embeddedt.embeddium.impl.gl.util.VertexRange; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Arrays; +import java.util.Map; + +@Mixin(value = SectionRenderDataStorage.class, remap = false) +public abstract class MixinSectionRenderDataStorage implements SectionRenderDataStorageRegionAccessor { + + @Unique private RenderRegion angelica$region; + @Unique private int angelica$passIndex = -1; + @Unique private volatile int[] angelica$slotCache; + + @Override public RenderRegion angelica$getRegion() { return angelica$region; } + @Override public void angelica$setRegion(RenderRegion region) { this.angelica$region = region; } + @Override public int angelica$getPassIndex() { return angelica$passIndex; } + @Override public void angelica$setPassIndex(int passIndex) { this.angelica$passIndex = passIndex; } + @Override public int[] angelica$getSlotCache() { return angelica$slotCache; } + + @Shadow public abstract long getDataPointer(int sectionIndex); + + @Shadow public abstract SectionRenderDataUnsafe.Strategy getStorageStrategy(); + + @Shadow public abstract ChunkPrimitiveType getPrimitiveType(); + + @Inject(method = "setMeshes", at = @At("RETURN")) + private void angelica$onSetMeshes(int localSectionIndex, GlBufferSegment allocation, GlBufferSegment indexAllocation, Map ranges, CallbackInfo ci) { + angelica$pushUpdate(localSectionIndex); + } + + @Inject(method = "replaceIndexBuffer", at = @At("RETURN")) + private void angelica$onReplaceIndexBuffer(int localSectionIndex, GlBufferSegment indexAllocation, CallbackInfo ci) { + angelica$pushUpdate(localSectionIndex); + } + + @Inject(method = "removeMeshes", at = @At("RETURN")) + private void angelica$onRemoveMeshes(int localSectionIndex, CallbackInfo ci) { + final RenderRegion r = angelica$region; + if (r == null) return; + GpuCulling.sectionMeta().remove(angelica$passIndex, r.getOriginX(), r.getOriginY(), r.getOriginZ(), localSectionIndex); + if (angelica$slotCache != null) angelica$slotCache[localSectionIndex] = -1; + } + + @Inject(method = "updateMeshes", at = @At("RETURN")) + private void angelica$onUpdateMeshes(int sectionIndex, CallbackInfo ci) { + angelica$pushUpdate(sectionIndex); + } + + @Inject(method = "delete", at = @At("HEAD")) + private void angelica$onDelete(CallbackInfo ci) { + final int[] cache = angelica$slotCache; + final RenderRegion r = angelica$region; + if (cache == null || r == null) return; + for (int i = 0; i < cache.length; i++) { + if (cache[i] < 0) continue; + cache[i] = -1; + GpuCulling.sectionMeta().remove(angelica$passIndex, r.getOriginX(), r.getOriginY(), r.getOriginZ(), i); + } + } + + @Unique + private void angelica$pushUpdate(int localSectionIndex) { + final RenderRegion r = angelica$region; + if (r == null) return; + final long dataPtr = getDataPointer(localSectionIndex); + if (SectionRenderDataUnsafe.getSliceMask(dataPtr) == 0) { + angelica$releaseSlot(r, localSectionIndex); + return; + } + final int slot = GpuCulling.sectionMeta().update(angelica$passIndex, r.getOriginX(), r.getOriginY(), r.getOriginZ(), localSectionIndex, dataPtr, getStorageStrategy(), getPrimitiveType()); + if (slot < 0) return; + int[] cache = angelica$slotCache; + if (cache == null) { + cache = new int[RenderRegion.REGION_SIZE]; + Arrays.fill(cache, -1); + cache[localSectionIndex] = slot; + angelica$slotCache = cache; + } else { + cache[localSectionIndex] = slot; + } + } + + @Unique + private void angelica$releaseSlot(RenderRegion r, int localSectionIndex) { + final int[] cache = angelica$slotCache; + if (cache == null || cache[localSectionIndex] < 0) return; + cache[localSectionIndex] = -1; + GpuCulling.sectionMeta().remove(angelica$passIndex, r.getOriginX(), r.getOriginY(), r.getOriginZ(), localSectionIndex); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_DisplayLists.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_DisplayLists.java deleted file mode 100644 index 0755d9b64..000000000 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_DisplayLists.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.gtnewhorizons.angelica.mixins.early.mcpatcherforge.renderpass; - -import net.minecraft.client.renderer.GLAllocation; -import net.minecraft.client.renderer.RenderGlobal; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -/** - * RenderPass display list allocation increase - increases from 3 to 5 display lists per chunk. - * Only the constructor modification - separated for compatibility with Sodium. - */ -@Mixin(RenderGlobal.class) -public abstract class MixinRenderGlobal_DisplayLists { - - @Redirect( - method = "(Lnet/minecraft/client/Minecraft;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GLAllocation;generateDisplayLists(I)I", ordinal = 0)) - private int modifyRenderGlobal(int n) { - return GLAllocation.generateDisplayLists(n / 3 * 5); - } -} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_Features.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_Features.java deleted file mode 100644 index b30722e82..000000000 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/renderpass/MixinRenderGlobal_Features.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.gtnewhorizons.angelica.mixins.early.mcpatcherforge.renderpass; - -import net.minecraft.client.renderer.EntityRenderer; -import net.minecraft.client.renderer.RenderGlobal; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.world.IWorldAccess; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import com.prupe.mcpatcher.renderpass.RenderPass; -import com.prupe.mcpatcher.renderpass.RenderPassMap; - -/** - * RenderPass feature hooks - loadRenderers, sortAndRender, renderAllRenderLists. - * Separated from display list allocation for compatibility with Sodium. - */ -@Mixin(RenderGlobal.class) -public abstract class MixinRenderGlobal_Features implements IWorldAccess { - - @ModifyVariable( - method = "loadRenderers()V", - at = @At( - value = "INVOKE", - target = "Ljava/util/List;add(Ljava/lang/Object;)Z", - remap = false, - shift = At.Shift.AFTER), - ordinal = 1) - private int modifyLoadRenderers(int input) { - return input + 2; - } - - // Order important here! - - @Inject( - method = "sortAndRender(Lnet/minecraft/entity/EntityLivingBase;ID)I", - at = @At(value = "HEAD"), - cancellable = true) - private void modifySortAndRender1(EntityLivingBase entity, int map18To17, double partialTickTime, - CallbackInfoReturnable cir) { - if (!RenderPass.preRenderPass(RenderPassMap.map17To18(map18To17))) { - cir.setReturnValue(RenderPass.postRenderPass(0)); - } - } - - @ModifyVariable( - method = "sortAndRender(Lnet/minecraft/entity/EntityLivingBase;ID)I", - at = @At(value = "HEAD"), - ordinal = 0, - argsOnly = true) - private int modifySortAndRender2(int map18To17) { - return RenderPassMap.map18To17(map18To17); - } - - @Inject( - method = "sortAndRender(Lnet/minecraft/entity/EntityLivingBase;ID)I", - at = @At(value = "RETURN"), - cancellable = true) - private void modifySortAndRender3(EntityLivingBase entity, int renderPass, double partialTickTime, - CallbackInfoReturnable cir) { - cir.setReturnValue(RenderPass.postRenderPass(cir.getReturnValue())); - } - - @Redirect( - method = "renderAllRenderLists(ID)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/EntityRenderer;enableLightmap(D)V")) - private void modifyRenderAllRenderLists(EntityRenderer instance, double partialTick) { - RenderPass.enableDisableLightmap(instance, partialTick); - } -} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinTileEntity.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinTileEntity.java index c6579368f..6346f122c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinTileEntity.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinTileEntity.java @@ -53,6 +53,7 @@ public abstract class MixinTileEntity implements ITileEntityBoundingBoxCache { @Unique private Block angelica$cachedBBBlockType = null; @Unique private AxisAlignedBB angelica$cachedRenderBB = null; @Unique private byte angelica$boundsClassCached = 0; // 0 = unchecked, otherwise STATIC/INFINITE/DYNAMIC + @Unique private byte angelica$passClassCached = 0; // 0 = unchecked, otherwise PASS0_ONLY/PASS_OVERRIDES /** * @author mitchej123 @@ -85,7 +86,7 @@ public abstract class MixinTileEntity implements ITileEntityBoundingBoxCache { @Override public AxisAlignedBB angelica$getCachedRenderBoundingBox() { if (angelica$cachedRenderBB != null && angelica$cachedBBX == this.xCoord && angelica$cachedBBY == this.yCoord && angelica$cachedBBZ == this.zCoord - && angelica$cachedBBMetadata == this.blockMetadata && angelica$cachedBBBlockType == this.blockType) + && getBlockType() == angelica$cachedBBBlockType && getBlockMetadata() == angelica$cachedBBMetadata) { return angelica$cachedRenderBB; } @@ -95,8 +96,8 @@ public abstract class MixinTileEntity implements ITileEntityBoundingBoxCache { this.angelica$cachedBBX = this.xCoord; this.angelica$cachedBBY = this.yCoord; this.angelica$cachedBBZ = this.zCoord; - this.angelica$cachedBBMetadata = this.blockMetadata; - this.angelica$cachedBBBlockType = this.blockType; + this.angelica$cachedBBMetadata = getBlockMetadata(); + this.angelica$cachedBBBlockType = getBlockType(); if (computed == TileEntity.INFINITE_EXTENT_AABB) { this.angelica$cachedRenderBB = computed; @@ -120,4 +121,12 @@ public abstract class MixinTileEntity implements ITileEntityBoundingBoxCache { } return angelica$boundsClassCached; } + + @Override + public byte angelica$passClass() { + if (angelica$passClassCached == 0) { + angelica$passClassCached = TileEntityRenderBoundsRegistry.classifyPass((TileEntity) (Object) this); + } + return angelica$passClassCached; + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinDefaultChunkRenderer_ShadowVoxelization.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinDefaultChunkRenderer_ShadowVoxelization.java new file mode 100644 index 000000000..a0b4e1d59 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinDefaultChunkRenderer_ShadowVoxelization.java @@ -0,0 +1,68 @@ +package com.gtnewhorizons.angelica.mixins.early.sdlgpu; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink; +import com.gtnewhorizons.angelica.rendering.voxelization.ShadowVoxelizer; +import net.coderbot.iris.Iris; +import net.coderbot.iris.gl.program.ComputeProgram; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.shadows.ShadowRenderingState; +import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices; +import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.apache.logging.log4j.LogManager; +import org.lwjgl.opengl.GL20; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.HashSet; +import java.util.Set; + +/** SDL_GPU allows read-write image access only in a compute pass, so the shadow VSH stores are replayed here. */ +@Mixin(value = DefaultChunkRenderer.class, remap = false) +public abstract class MixinDefaultChunkRenderer_ShadowVoxelization { + + @Shadow protected abstract boolean useBlockFaceCulling(); + + @Unique private static final ShadowVoxelizer angelica$voxelizer = new ShadowVoxelizer(); + @Unique private static final SdlShadowVoxelizationSink angelica$sink = new SdlShadowVoxelizationSink(); + + @Unique private static final Set angelica$loggedBails = new HashSet<>(); + + @Unique + private static void angelica$bail(String reason) { + if (angelica$loggedBails.add(reason)) { + LogManager.getLogger("Angelica").info("shadow voxelization skipped: {}", reason); + } + } + + @Inject(method = "render", at = @At("HEAD")) + private void angelica$voxelizeShadowTerrain(ChunkRenderMatrices matrices, CommandList commandList, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, CallbackInfo ci) { + if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return; + if (!ShadowRenderingState.areShadowsCurrentlyBeingRendered()) return; + if (!renderLists.hasPass(renderPass)) { angelica$bail("pass has no render lists"); return; } + + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (!(pipeline instanceof DeferredWorldRenderingPipeline deferred)) { angelica$bail("no deferred pipeline"); return; } + final ComputeProgram voxelCompute = deferred.getShadowVoxelizationCompute(); + if (voxelCompute == null) { angelica$bail("pack declares no shadow voxelization"); return; } + + final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); + voxelCompute.use(); + deferred.prepareShadowVoxelizationCompute(matrices.modelView()); + try { + angelica$voxelizer.walkPass(renderLists, renderPass, renderPass.vertexType().getVertexFormat(), camera, occlusionCamera, useBlockFaceCulling() && !renderPass.isSorted(), angelica$sink); + } finally { + if (prevProgram != 0) GLStateManager.glUseProgram(prevProgram); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinForgeHooksClient_SDLGPUDisplay.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinForgeHooksClient_SDLGPUDisplay.java new file mode 100644 index 000000000..6aaa2d8bc --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/sdlgpu/MixinForgeHooksClient_SDLGPUDisplay.java @@ -0,0 +1,45 @@ +package com.gtnewhorizons.angelica.mixins.early.sdlgpu; + +import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; +import cpw.mods.fml.common.FMLCommonHandler; +import net.minecraftforge.client.ForgeHooksClient; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.LWJGLException; +import org.lwjgl.opengl.PixelFormat; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import javax.imageio.ImageIO; + +@Mixin(value = ForgeHooksClient.class, remap = false) +public abstract class MixinForgeHooksClient_SDLGPUDisplay { + + @Unique private static final Logger LOGGER = LogManager.getLogger("Angelica/SDLGPU"); + + @Shadow static int stencilBits; + + @Inject(method = "createDisplay", at = @At("HEAD"), cancellable = true) + private static void angelicaSdl$createDisplay(CallbackInfo ci) throws LWJGLException { + ImageIO.setUseCache(false); + stencilBits = 8; + + final PixelFormat format = new PixelFormat().withDepthBits(24).withStencilBits(stencilBits); + try { + SDLGPUGate.createSDLGPUDisplay(format, null, AngelicaMod.lwjglDebug); + if (SDLGPUGate.isFatalInit()) { + FMLCommonHandler.instance().exitJava(1, false); + } + LOGGER.info("Created SDL GPU window"); + ci.cancel(); + } catch (RuntimeException e) { + LOGGER.error("FATAL: Failed to create SDL GPU window: {}", e.getMessage()); + throw new LWJGLException("Failed to create SDL GPU window", e); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java index 04f689a97..1066486d9 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java @@ -40,6 +40,7 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/culling/ClippingHelperImpl;getInstance()Lnet/minecraft/client/renderer/culling/ClippingHelper;", shift = At.Shift.AFTER, ordinal = 0), method = "renderWorld(FJ)V") private void iris$beginRender(float partialTicks, long startTime, CallbackInfo ci, @Share("pipeline") LocalRef pipeline) { + mc.mcProfiler.endStartSection("iris_begin"); DHCompat.checkFrame(); Iris.tryLoadShaderpackWhenPossible(); @@ -49,7 +50,9 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe Program.unbind(); + mc.mcProfiler.startSection("iris_prepare_pipeline"); pipeline.set(Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimensionName())); + mc.mcProfiler.endSection(); GLStateManager.setShaderColor(1f, 1f, 1f, 1f); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinModelBiped.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinModelBiped.java index 193d2b2de..b9d88d39c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinModelBiped.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinModelBiped.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.rendering.PlayerReflectionCapture; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.model.ModelBox; @@ -20,6 +21,8 @@ import java.util.Arrays; @Mixin(ModelBiped.class) public abstract class MixinModelBiped { + @Unique private static final Tracy.ZoneId Z_PLAYER_REFLECTION_CAPTURE = Tracy.zoneId("playerReflectionCapture", Tracy.COLOR_IRIS); + @Unique private static final Matrix4f angelica$mat = new Matrix4f(); @Unique private static final Vector3f angelica$vec = new Vector3f(); @@ -34,22 +37,27 @@ public abstract class MixinModelBiped { final ModelBiped model = (ModelBiped) (Object) this; final float[] data = PlayerReflectionCapture.vertexScratch(); - // Six 48-vertex blocks = body parts, each base box + overlay box - int o = 0; - o = angelica$emitBox(model.bipedHead, data, o, scale); - o = angelica$emitBox(model.bipedHeadwear, data, o, scale); - o = angelica$emitBox(model.bipedRightArm, data, o, scale); - o = angelica$emitBox(model.bipedRightArm, data, o, scale); - o = angelica$emitBox(model.bipedLeftLeg, data, o, scale); - o = angelica$emitBox(model.bipedLeftLeg, data, o, scale); - o = angelica$emitBox(model.bipedLeftArm, data, o, scale); - o = angelica$emitBox(model.bipedLeftArm, data, o, scale); - o = angelica$emitBox(model.bipedRightLeg, data, o, scale); - o = angelica$emitBox(model.bipedRightLeg, data, o, scale); - o = angelica$emitBox(model.bipedBody, data, o, scale); - angelica$emitBox(model.bipedBody, data, o, scale); + if (Tracy.ENABLED) Tracy.beginZone(Z_PLAYER_REFLECTION_CAPTURE); + try { + // Six 48-vertex blocks = body parts, each base box + overlay box + int o = 0; + o = angelica$emitBox(model.bipedHead, data, o, scale); + o = angelica$emitBox(model.bipedHeadwear, data, o, scale); + o = angelica$emitBox(model.bipedRightArm, data, o, scale); + o = angelica$emitBox(model.bipedRightArm, data, o, scale); + o = angelica$emitBox(model.bipedLeftLeg, data, o, scale); + o = angelica$emitBox(model.bipedLeftLeg, data, o, scale); + o = angelica$emitBox(model.bipedLeftArm, data, o, scale); + o = angelica$emitBox(model.bipedLeftArm, data, o, scale); + o = angelica$emitBox(model.bipedRightLeg, data, o, scale); + o = angelica$emitBox(model.bipedRightLeg, data, o, scale); + o = angelica$emitBox(model.bipedBody, data, o, scale); + angelica$emitBox(model.bipedBody, data, o, scale); - PlayerReflectionCapture.drawPlayerCapture(data); + PlayerReflectionCapture.drawPlayerCapture(data); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } } private static int angelica$emitBox(ModelRenderer part, float[] out, int o, float scale) { diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java index 1d6660826..5eef038b2 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java @@ -10,8 +10,6 @@ import net.coderbot.iris.Iris; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.pipeline.WorldRenderingPhase; import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.EntityIdHelper; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderManager; @@ -126,17 +124,19 @@ public class MixinRenderGlobal { GbufferPrograms.endOutline(); } + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=global")) + private void iris$beginEntityLoop(CallbackInfo ci) { + GbufferPrograms.beginEntityLoop(); + } + + @Inject(method = "renderEntities", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=blockentities")) + private void iris$endEntityLoop(CallbackInfo ci) { + GbufferPrograms.endEntityLoop(); + } + @WrapOperation(method="renderEntities", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z")) private boolean angelica$renderEntitySimple(RenderManager instance, Entity entity, float partialTicks, Operation original) { - int entityId = EntityIdHelper.getEntityId(entity); - - CapturedRenderingState.INSTANCE.setCurrentEntity(entityId); - GbufferPrograms.beginEntities(); - try { - return original.call(instance, entity, partialTicks); - } finally { - CapturedRenderingState.INSTANCE.setCurrentEntity(-1); - GbufferPrograms.endEntities(); - } + GbufferPrograms.onEntityRenderBoundary(); + return original.call(instance, entity, partialTicks); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java index 51dbd85a8..f57329db3 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; @@ -27,6 +28,7 @@ public class MixinRenderManager { private void iris$wrapDoRender(Render render, Entity entity, double x, double y, double z, float entityYaw, float partialTicks, Operation original) { int entityId = EntityIdHelper.getEntityId(entity); CapturedRenderingState.INSTANCE.setCurrentEntity(entityId); + TesrAttribution.currentRenderable = entity != null ? entity.getClass() : null; final boolean lightning = EntityIdHelper.isLightningBolt(entity); if (lightning) { GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.LIGHTNING); @@ -36,5 +38,6 @@ public class MixinRenderManager { GbufferPrograms.teardownSpecialRenderCondition(); } CapturedRenderingState.INSTANCE.setCurrentEntity(-1); + TesrAttribution.currentRenderable = null; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinTileEntityRendererDispatcher.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinTileEntityRendererDispatcher.java index 02024d3c5..0c7e7e9b4 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinTileEntityRendererDispatcher.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinTileEntityRendererDispatcher.java @@ -1,11 +1,10 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizons.angelica.rendering.tesr.PassRebindGate; +import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; +import com.gtnewhorizons.angelica.rendering.tesr.TesrProviderDispatch; import com.prupe.mcpatcher.ctm.CTMUtils; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.minecraft.block.Block; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.tileentity.TileEntity; import org.spongepowered.asm.mixin.Mixin; @@ -19,36 +18,21 @@ public class MixinTileEntityRendererDispatcher { @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", at = @At("HEAD")) private void iris$setBlockEntityId(TileEntity te, double x, double y, double z, float partialTicks, CallbackInfo ci) { CTMUtils.clearCurrentCompact(); - if (te == null) { - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); - return; - } - Block block = te.getBlockType(); - if (block == null) { - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); - return; - } + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(iris$resolveBlockEntityId(te)); + TesrAttribution.currentRenderable = te != null ? te.getClass() : null; - Reference2ObjectMap blockMetaMatches = BlockRenderingSettings.INSTANCE.getBlockMetaMatches(); - if (blockMetaMatches == null) { - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); - return; - } + // Rebind Iris's pass in case the previous TESR changed it + PassRebindGate.rebindIfDirty(); + } - Int2IntMap metaMap = blockMetaMatches.get(block); - if (metaMap == null) { - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); - return; - } - - int meta = te.getBlockMetadata(); - int id = metaMap.get(meta); - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(Math.max(0, id)); + private static int iris$resolveBlockEntityId(TileEntity te) { + return TesrProviderDispatch.resolveBlockEntityId(te); } @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", at = @At("RETURN")) private void iris$resetBlockEntityId(TileEntity te, double x, double y, double z, float partialTicks, CallbackInfo ci) { CTMUtils.clearCurrentCompact(); CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0); + TesrAttribution.currentRenderable = null; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/biomesoplenty/MixinFogHandlerBiomeCache.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/biomesoplenty/MixinFogHandlerBiomeCache.java new file mode 100644 index 000000000..ec97021df --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/biomesoplenty/MixinFogHandlerBiomeCache.java @@ -0,0 +1,108 @@ +package com.gtnewhorizons.angelica.mixins.late.client.biomesoplenty; + +import biomesoplenty.client.fog.FogHandler; +import com.gtnewhorizons.angelica.compat.bop.BopFogBlend; +import com.gtnewhorizons.angelica.compat.bop.BopFogColorSource; +import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.GameSettings; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.MathHelper; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.ForgeModContainer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(value = FogHandler.class, remap = false) +public class MixinFogHandlerBiomeCache { + + @Unique private static final float[] angelica$sums = new float[4]; + + @Shadow + private static Vec3 postProcessColor(World world, EntityLivingBase player, float r, float g, float b, double renderPartialTicks) { + throw new AssertionError(); + } + + @Redirect( + method = "getFogBlendColorWater", + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getBiomeGenForCoords(II)Lnet/minecraft/world/biome/BiomeGenBase;", remap = true)) + private static BiomeGenBase angelica$cachedBiomeLookup(World world, int x, int z) { + return FogBiomeCache.get(world, x, z); + } + + /** + * @author Angelica + * @reason Cache the interior sum and walk only the border strips + */ + @Overwrite + private static Vec3 getFogBlendColour(World world, EntityLivingBase playerEntity, int playerX, int playerY, int playerZ, float defR, float defG, float defB, double renderPartialTicks) { + final GameSettings settings = Minecraft.getMinecraft().gameSettings; + final int[] ranges = ForgeModContainer.blendRanges; + int distance = 6; + if (settings.fancyGraphics && settings.renderDistanceChunks >= 0 && settings.renderDistanceChunks < ranges.length) { + distance = ranges[settings.renderDistanceChunks]; + } + + final float[] sums = angelica$sums; + BopFogBlend.accumulate(world, FogBiomeCache.generation(), BopFogColorSource.INSTANCE.forWorld(world), + playerEntity.posX, playerEntity.posZ, playerX, playerY, playerZ, distance, sums); + + float rBiomeFog = sums[0]; + float gBiomeFog = sums[1]; + float bBiomeFog = sums[2]; + final float weightBiomeFog = sums[3]; + + if (weightBiomeFog == 0 || distance == 0) { + return Vec3.createVectorHelper(defR, defG, defB); + } + + rBiomeFog /= 255f; + gBiomeFog /= 255f; + bBiomeFog /= 255f; + + final float celestialAngle = world.getCelestialAngle((float) renderPartialTicks); + final float baseScale = MathHelper.clamp_float(MathHelper.cos(celestialAngle * (float) Math.PI * 2.0F) * 2.0F + 0.5F, 0, 1); + + float rScale = baseScale * 0.94F + 0.06F; + float gScale = baseScale * 0.94F + 0.06F; + float bScale = baseScale * 0.91F + 0.09F; + + final float rainStrength = world.getRainStrength((float) renderPartialTicks); + if (rainStrength > 0) { + rScale *= 1 - rainStrength * 0.5f; + gScale *= 1 - rainStrength * 0.5f; + bScale *= 1 - rainStrength * 0.4f; + } + + final float thunderStrength = world.getWeightedThunderStrength((float) renderPartialTicks); + if (thunderStrength > 0) { + rScale *= 1 - thunderStrength * 0.5f; + gScale *= 1 - thunderStrength * 0.5f; + bScale *= 1 - thunderStrength * 0.5f; + } + + rBiomeFog *= rScale / weightBiomeFog; + gBiomeFog *= gScale / weightBiomeFog; + bBiomeFog *= bScale / weightBiomeFog; + + final Vec3 processedColor = postProcessColor(world, playerEntity, rBiomeFog, gBiomeFog, bBiomeFog, renderPartialTicks); + rBiomeFog = (float) processedColor.xCoord; + gBiomeFog = (float) processedColor.yCoord; + bBiomeFog = (float) processedColor.zCoord; + + final float weightMixed = (distance * 2) * (distance * 2); + final float weightDefault = weightMixed - weightBiomeFog; + + processedColor.xCoord = (rBiomeFog * weightBiomeFog + defR * weightDefault) / weightMixed; + processedColor.yCoord = (gBiomeFog * weightBiomeFog + defG * weightDefault) / weightMixed; + processedColor.zCoord = (bBiomeFog * weightBiomeFog + defB * weightDefault) / weightMixed; + + return processedColor; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileJarRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileJarRenderer.java new file mode 100644 index 000000000..2f44081d3 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileJarRenderer.java @@ -0,0 +1,51 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.Tc4JarMeshes; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.renderer.RenderBlocks; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import thaumcraft.api.aspects.Aspect; +import thaumcraft.client.lib.UtilsFX; +import thaumcraft.client.renderers.tile.TileJarRenderer; +import thaumcraft.common.tiles.TileJar; +import thaumcraft.common.tiles.TileJarFillable; + +@Mixin(value = TileJarRenderer.class, remap = false) +public abstract class MixinTileJarRenderer { + + @Shadow(remap = false) + abstract void renderLiquid(TileJarFillable te, double x, double y, double z, float f); + + @Redirect(method = "renderTileEntityAt(Lthaumcraft/common/tiles/TileJar;DDDF)V", at = @At(value = "INVOKE", target = "Lthaumcraft/client/renderers/tile/TileJarRenderer;renderLiquid(Lthaumcraft/common/tiles/TileJarFillable;DDDF)V")) + private void angelica$renderLiquidCached(TileJarRenderer self, TileJarFillable te, double x, double y, double z, float f) { + if (!Tc4JarMeshes.renderLiquid(te)) { + this.renderLiquid(te, x, y, z, f); + } + } + + @Redirect(method = "renderLiquid", at = @At(value = "NEW", target = "net/minecraft/client/renderer/RenderBlocks")) + private RenderBlocks angelica$reuseRenderBlocks() { + return Tc4JarMeshes.fallbackRenderBlocks(); + } + + @Redirect(method = "renderTileEntityAt(Lthaumcraft/common/tiles/TileJar;DDDF)V", at = @At(value = "INVOKE", target = "Lthaumcraft/client/lib/UtilsFX;renderQuadCenteredFromTexture(Ljava/lang/String;FFFFIIF)V")) + private void angelica$cachedLabelBacking(String texture, float scale, float red, float green, float blue, int brightness, int blend, float opacity, @Local(argsOnly = true) TileJar jar) { + if ("textures/models/label.png".equals(texture) && scale == 0.5f && blend == 771 && opacity == 1.0f) { + Tc4JarMeshes.renderLabelBacking(jar); + } else { + UtilsFX.renderQuadCenteredFromTexture(texture, scale, red, green, blue, brightness, blend, opacity); + } + } + + @Redirect(method = "renderTileEntityAt(Lthaumcraft/common/tiles/TileJar;DDDF)V", at = @At(value = "INVOKE", target = "Lthaumcraft/client/lib/UtilsFX;drawTag(IILthaumcraft/api/aspects/Aspect;)V")) + private void angelica$cachedLabelTag(int x, int y, Aspect aspect, @Local(argsOnly = true) TileJar jar) { + if (x == -8 && y == -8 && aspect != null) { + Tc4JarMeshes.renderLabelTag(aspect, jar); + } else { + UtilsFX.drawTag(x, y, aspect); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterialInternTest.java b/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterialInternTest.java new file mode 100644 index 000000000..62fa100af --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterialInternTest.java @@ -0,0 +1,39 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +class TesrMaterialInternTest { + + @Test + void equalSettingsBuildSameInstance() { + final TesrMaterial a = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().stream().build(); + final TesrMaterial b = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().stream().build(); + assertSame(a, b); + } + + @Test + void differingSettingsBuildDistinctInstances() { + final TesrMaterial a = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).translucent().build(); + final TesrMaterial b = TesrMaterial.builder().color(1f, 0.5f, 0.25f, 1f).additive().build(); + assertNotSame(a, b); + } + + @Test + void defaultsFoldToCurrentState() { + assertSame(TesrMaterial.CURRENT_STATE, TesrMaterial.builder().build()); + } + + @Test + void shaderIdentitySplitsOtherwiseEqualMaterials() { + final TesrShader s1 = TesrShaders.register("test:intern_a", () -> {}, () -> {}); + final TesrShader s2 = TesrShaders.register("test:intern_b", () -> {}, () -> {}); + final TesrMaterial a = TesrMaterial.builder().translucent().shader(s1).build(); + final TesrMaterial b = TesrMaterial.builder().translucent().shader(s2).build(); + final TesrMaterial c = TesrMaterial.builder().translucent().shader(s1).build(); + assertNotSame(a, b); + assertSame(a, c); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrShadersTest.java b/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrShadersTest.java new file mode 100644 index 000000000..878a15a40 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/api/tesr/TesrShadersTest.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.api.tesr; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class TesrShadersTest { + + private static final Runnable NOOP = () -> {}; + + @Test + void registerReturnsHandleWithAccessors() { + final Runnable bind = () -> {}; + final Runnable release = () -> {}; + final TesrShader shader = TesrShaders.register("test:accessors", bind, release); + assertEquals("test:accessors", shader.name()); + assertSame(bind, shader.bind()); + assertSame(release, shader.release()); + } + + @Test + void duplicateNameThrows() { + TesrShaders.register("test:duplicate", NOOP, NOOP); + assertThrows(IllegalStateException.class, () -> TesrShaders.register("test:duplicate", NOOP, NOOP)); + } + + @Test + void malformedNamesThrow() { + assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("nonamespace", NOOP, NOOP)); + assertThrows(IllegalArgumentException.class, () -> TesrShaders.register(":path", NOOP, NOOP)); + assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("ns:", NOOP, NOOP)); + assertThrows(IllegalArgumentException.class, () -> TesrShaders.register("a:b:c", NOOP, NOOP)); + } + + @Test + void nullRunnablesThrow() { + assertThrows(NullPointerException.class, () -> TesrShaders.register("test:null_bind", null, NOOP)); + assertThrows(NullPointerException.class, () -> TesrShaders.register("test:null_release", NOOP, null)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/arch/SDLGPUEncapsulationTest.java b/src/test/java/com/gtnewhorizons/angelica/arch/SDLGPUEncapsulationTest.java new file mode 100644 index 000000000..096c5e2be --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/arch/SDLGPUEncapsulationTest.java @@ -0,0 +1,53 @@ +package com.gtnewhorizons.angelica.arch; + +import com.tngtech.archunit.base.DescribedPredicate; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.lang.ArchRule; +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +/** + * Enforces the :sdl-gpu module boundary + */ +class SDLGPUEncapsulationTest { + + private static final String SDLGPU_ROOT = "com.gtnewhorizons.angelica.sdlgpu"; + + private static final Set PUBLIC_ENTRIES = Set.of( + SDLGPU_ROOT + ".SDLGPURenderBackend", // ServiceLoader + SDLGPU_ROOT + ".SDLGPULWJGLService", // ServiceLoader + SDLGPU_ROOT + ".SDLGPUGate", // Mixins, MixinInitGLStateManager + SDLGPU_ROOT + ".SDLGPUDisplayBridge", // MixinForgeHooksClient_SDLGPUDisplay + SDLGPU_ROOT + ".device.SDLDrawable", // MixinForgeHooksClient_SDLGPUDisplay + SDLGPU_ROOT + ".shader.ShaderManager" // Iris, IrisGLSMBridge + ); + + private static final DescribedPredicate SDLGPU_INTERNAL = + new DescribedPredicate<>("sdlgpu internals (anything under " + SDLGPU_ROOT + " not on the allow-list)") { + @Override + public boolean test(JavaClass c) { + final String name = c.getName(); + return name.startsWith(SDLGPU_ROOT + ".") && !PUBLIC_ENTRIES.contains(name); + } + }; + + private static final JavaClasses CLASSES = new ClassFileImporter() + .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) + .importPaths("build/classes/java/main", "build/classes/java/mixin"); + + private static final ArchRule NO_SDLGPU_INTERNALS_FROM_OUTSIDE = noClasses() + .that().resideOutsideOfPackage(SDLGPU_ROOT + "..") + .should().dependOnClassesThat(SDLGPU_INTERNAL) + .because("only the allow-listed classes may be referenced by name from outside :sdl-gpu"); + + @Test + void noSdlGpuInternalsFromOutside() { + NO_SDLGPU_INTERNALS_FROM_OUTSIDE.check(CLASSES); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/client/ChatLineFormattedCacheTest.java b/src/test/java/com/gtnewhorizons/angelica/client/ChatLineFormattedCacheTest.java new file mode 100644 index 000000000..153cf69fa --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/client/ChatLineFormattedCacheTest.java @@ -0,0 +1,66 @@ +package com.gtnewhorizons.angelica.client; + +import com.gtnewhorizons.angelica.mixins.interfaces.ChatLineFormattedAccessor; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class ChatLineFormattedCacheTest { + + private static final class Line implements ChatLineFormattedAccessor { + private String formatted; + private long formattedEpoch = Long.MIN_VALUE; + + @Override + public String angelica$getFormatted(long epoch) { + return formattedEpoch == epoch ? formatted : null; + } + + @Override + public void angelica$setFormatted(String formatted, long epoch) { + this.formatted = formatted; + this.formattedEpoch = epoch; + } + } + + @Test + void aFreshLineHasNothingCached() { + assertNull(new Line().angelica$getFormatted(0L)); + } + + @Test + void theSameEpochReturnsTheCachedInstance() { + final Line line = new Line(); + final String formatted = "§ahello"; + line.angelica$setFormatted(formatted, 1234L); + assertSame(formatted, line.angelica$getFormatted(1234L)); + } + + @Test + void aTranslationEpochChangeInvalidates() { + final Line line = new Line(); + line.angelica$setFormatted("§aold locale", 1234L); + assertNull(line.angelica$getFormatted(5678L), "a language reload must force a rebuild"); + + line.angelica$setFormatted("§anew locale", 5678L); + assertEquals("§anew locale", line.angelica$getFormatted(5678L)); + assertNull(line.angelica$getFormatted(1234L), "the stale epoch never comes back"); + } + + @Test + void obfuscatedCodesAreCachedVerbatim() { + final Line line = new Line(); + final String formatted = "§kMAGIC§r plain"; + line.angelica$setFormatted(formatted, 7L); + assertEquals(formatted, line.angelica$getFormatted(7L)); + } + + @Test + void zeroIsAUsableEpoch() { + final Line line = new Line(); + line.angelica$setFormatted("x", 0L); + assertEquals("x", line.angelica$getFormatted(0L)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/client/rendering/DeferredDrawBatcherTest.java b/src/test/java/com/gtnewhorizons/angelica/client/rendering/DeferredDrawBatcherTest.java index aa15002b9..1b074536d 100644 --- a/src/test/java/com/gtnewhorizons/angelica/client/rendering/DeferredDrawBatcherTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/client/rendering/DeferredDrawBatcherTest.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.client.rendering; +import java.util.ArrayList; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; @@ -57,7 +58,7 @@ class DeferredDrawBatcherTest { // Create entries with interleaved keys: A, B, A, B, A final int flags = VertexFlags.convertToFlags(true, true, false, true); - var entries = new java.util.ArrayList(); + var entries = new ArrayList(); entries.add(new DeferredBatchTessellator.DrawRange(keyA, 0, 128, 4, GL11.GL_QUADS, flags)); entries.add(new DeferredBatchTessellator.DrawRange(keyB, 128, 128, 4, GL11.GL_QUADS, flags)); entries.add(new DeferredBatchTessellator.DrawRange(keyA, 256, 128, 4, GL11.GL_QUADS, flags)); @@ -97,7 +98,7 @@ class DeferredDrawBatcherTest { long key = DeferredDrawBatcher.packStateKey(1, 0x0302, 0x0001, true, true, true, true); final int flags = VertexFlags.convertToFlags(true, true, false, true); - var entries = new java.util.ArrayList(); + var entries = new ArrayList(); entries.add(new DeferredBatchTessellator.DrawRange(key, 0, 128, 4, GL11.GL_QUADS, flags)); entries.add(new DeferredBatchTessellator.DrawRange(key, 128, 256, 8, GL11.GL_QUADS, flags)); entries.add(new DeferredBatchTessellator.DrawRange(key, 384, 128, 4, GL11.GL_QUADS, flags)); @@ -119,7 +120,7 @@ class DeferredDrawBatcherTest { long key = DeferredDrawBatcher.packStateKey(1, 0x0302, 0x0001, true, true, true, true); final int flags = VertexFlags.convertToFlags(true, true, false, true); - var entries = new java.util.ArrayList(); + var entries = new ArrayList(); entries.add(new DeferredBatchTessellator.DrawRange(key, 0, 128, 4, GL11.GL_QUADS, flags)); entries.add(new DeferredBatchTessellator.DrawRange(key, 128, 128, 4, GL11.GL_TRIANGLES, flags)); entries.add(new DeferredBatchTessellator.DrawRange(key, 256, 128, 4, GL11.GL_QUADS, flags)); @@ -194,7 +195,7 @@ class DeferredDrawBatcherTest { final int flags = VertexFlags.convertToFlags(true, true, false, true); // Simulate sequential byte offsets as would be produced by interceptDraw - var ranges = new java.util.ArrayList(); + var ranges = new ArrayList(); int offset = 0; for (int i = 0; i < 5; i++) { int byteLen = (i + 1) * 128; // 128, 256, 384, 512, 640 diff --git a/src/test/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlendTest.java b/src/test/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlendTest.java new file mode 100644 index 000000000..6d79bab3f --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/compat/bop/BopFogBlendTest.java @@ -0,0 +1,201 @@ +package com.gtnewhorizons.angelica.compat.bop; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BopFogBlendTest { + + private static final float EPSILON = 1e-4f; + + private static float[] reference(BopFogBlend.ColorSource source, double posX, double posZ, int playerX, + int playerY, int playerZ, int distance) { + + float rBiomeFog = 0, gBiomeFog = 0, bBiomeFog = 0, weightBiomeFog = 0; + for (int x = -distance; x <= distance; ++x) { + for (int z = -distance; z <= distance; ++z) { + final int fogColour = source.fogColour(playerX + x, playerY, playerZ + z); + if (fogColour == BopFogBlend.NO_FOG) continue; + + float rPart = (fogColour & 0xFF0000) >> 16; + float gPart = (fogColour & 0x00FF00) >> 8; + float bPart = fogColour & 0x0000FF; + float weightPart = 1; + + if (x == -distance) { + final double xDiff = 1 - (posX - playerX); + rPart *= xDiff; + gPart *= xDiff; + bPart *= xDiff; + weightPart *= xDiff; + } else if (x == distance) { + final double xDiff = posX - playerX; + rPart *= xDiff; + gPart *= xDiff; + bPart *= xDiff; + weightPart *= xDiff; + } + + if (z == -distance) { + final double zDiff = 1 - (posZ - playerZ); + rPart *= zDiff; + gPart *= zDiff; + bPart *= zDiff; + weightPart *= zDiff; + } else if (z == distance) { + final double zDiff = posZ - playerZ; + rPart *= zDiff; + gPart *= zDiff; + bPart *= zDiff; + weightPart *= zDiff; + } + + rBiomeFog += rPart; + gBiomeFog += gPart; + bBiomeFog += bPart; + weightBiomeFog += weightPart; + } + } + return new float[] { rBiomeFog, gBiomeFog, bBiomeFog, weightBiomeFog }; + } + + /** Deterministic pseudo-random grid: every column is either a fog biome with a stable colour, or plain. */ + private record Grid(long seed, int fogPercent) implements BopFogBlend.ColorSource { + + @Override + public int fogColour(int x, int y, int z) { + long h = seed; + h = h * 31 + x; + h = h * 31 + y; + h = h * 31 + z; + h ^= h >>> 27; + h *= 0x9E3779B97F4A7C15L; + h ^= h >>> 31; + if (Math.floorMod(h, 100) >= fogPercent) return BopFogBlend.NO_FOG; + return (int) (h >>> 8) & 0xFFFFFF; + } + } + + private final float[] out = new float[4]; + private final Object world = new Object(); + + @BeforeEach + void reset() { + BopFogBlend.invalidate(); + } + + private void assertMatchesReference(BopFogBlend.ColorSource source, double posX, double posZ, int px, int py, + int pz, int distance, int generation) { + + final float[] expected = reference(source, posX, posZ, px, py, pz, distance); + BopFogBlend.accumulate(world, generation, source, posX, posZ, px, py, pz, distance, out); + for (int i = 0; i < 4; i++) { + final float tolerance = Math.max(EPSILON, Math.abs(expected[i]) * EPSILON); + assertEquals(expected[i], out[i], tolerance, "component " + i); + } + } + + @Test + void matchesReferenceOverRandomGridsAndPositions() { + final Random random = new Random(12345); + for (int iteration = 0; iteration < 200; iteration++) { + final Grid grid = new Grid(random.nextLong(), random.nextInt(101)); + final int px = random.nextInt(4000) - 2000; + final int py = random.nextInt(256); + final int pz = random.nextInt(4000) - 2000; + final double posX = px + random.nextDouble(); + final double posZ = pz + random.nextDouble(); + final int distance = random.nextInt(21); + assertMatchesReference(grid, posX, posZ, px, py, pz, distance, iteration); + } + } + + @Test + void noFogBiomesAccumulateNothing() { + final BopFogBlend.ColorSource none = (x, y, z) -> BopFogBlend.NO_FOG; + BopFogBlend.accumulate(world, 0, none, 10.5, 20.25, 10, 64, 20, 20, out); + assertArrayEquals(new float[] { 0, 0, 0, 0 }, out); + } + + @Test + void fullCoverageMatchesReference() { + final BopFogBlend.ColorSource all = (x, y, z) -> 0x203040; + assertMatchesReference(all, 10.5, 20.5, 10, 64, 20, 20, 0); + } + + @Test + void borderOnlyCoverageMatchesReference() { + final int distance = 12; + final BopFogBlend.ColorSource borderOnly = (x, y, z) -> { + final int dx = Math.abs(x - 100); + final int dz = Math.abs(z - 200); + return (dx == distance || dz == distance) ? 0xFF8040 : BopFogBlend.NO_FOG; + }; + assertMatchesReference(borderOnly, 100.75, 200.125, 100, 64, 200, distance, 0); + } + + @Test + void interiorIsReusedAcrossSubBlockMovementAndRebuiltOnCrossing() { + final Grid grid = new Grid(99, 60); + for (double frac = 0.05; frac < 1.0; frac += 0.1) { + assertMatchesReference(grid, 40 + frac, 80 + frac, 40, 64, 80, 16, 7); + } + assertMatchesReference(grid, 41.5, 80.5, 41, 64, 80, 16, 7); + assertMatchesReference(grid, 41.5, 80.5, 41, 65, 80, 16, 7); + assertMatchesReference(grid, 41.5, 80.5, 41, 65, 80, 12, 7); + } + + @Test + void onlyTheBorderIsWalkedWhileTheBlockPositionHolds() { + final int distance = 20; + final int[] lookups = { 0 }; + final BopFogBlend.ColorSource counting = (x, y, z) -> { + lookups[0]++; + return 0x102030; + }; + + BopFogBlend.accumulate(world, 0, counting, 100.1, 200.1, 100, 64, 200, distance, out); + assertEquals((2 * distance + 1) * (2 * distance + 1), lookups[0], "first call must walk every column"); + + lookups[0] = 0; + BopFogBlend.accumulate(world, 0, counting, 100.9, 200.9, 100, 64, 200, distance, out); + assertEquals(8 * distance, lookups[0], "a sub-block move must only re-walk the border strips"); + } + + @Test + void aNewGenerationRebuildsTheInterior() { + final int[] answer = { 0x101010 }; + final BopFogBlend.ColorSource shifting = (x, y, z) -> answer[0]; + + BopFogBlend.accumulate(world, 1, shifting, 0.5, 0.5, 0, 64, 0, 8, out); + final float firstInteriorRed = out[0]; + + answer[0] = 0x202020; + BopFogBlend.accumulate(world, 2, shifting, 0.5, 0.5, 0, 64, 0, 8, out); + assertEquals(firstInteriorRed * 2, out[0], firstInteriorRed * EPSILON, + "a generation bump must rebuild the cached interior, not serve the stale sum"); + } + + @Test + void aNewWorldRebuildsTheInterior() { + final int[] answer = { 0x101010 }; + final BopFogBlend.ColorSource shifting = (x, y, z) -> answer[0]; + + BopFogBlend.accumulate(world, 0, shifting, 0.5, 0.5, 0, 64, 0, 8, out); + final float firstInteriorRed = out[0]; + + answer[0] = 0x202020; + BopFogBlend.accumulate(new Object(), 0, shifting, 0.5, 0.5, 0, 64, 0, 8, out); + assertEquals(firstInteriorRed * 2, out[0], firstInteriorRed * EPSILON); + } + + @Test + void zeroDistanceMatchesReference() { + final BopFogBlend.ColorSource all = (x, y, z) -> 0x804020; + assertMatchesReference(all, 5.5, 6.25, 5, 64, 6, 0, 0); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCacheTest.java b/src/test/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCacheTest.java new file mode 100644 index 000000000..c5028ae2e --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/compat/bop/FogBiomeCacheTest.java @@ -0,0 +1,68 @@ +package com.gtnewhorizons.angelica.compat.bop; + +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraft.world.chunk.IChunkProvider; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class FogBiomeCacheTest { + + private static World worldWith(BiomeGenBase biome, boolean chunkLoaded) { + final World world = Mockito.mock(World.class); + final IChunkProvider provider = Mockito.mock(IChunkProvider.class); + when(world.getBiomeGenForCoords(anyInt(), anyInt())).thenReturn(biome); + when(world.getChunkProvider()).thenReturn(provider); + when(provider.chunkExists(anyInt(), anyInt())).thenReturn(chunkLoaded); + return world; + } + + @Test + void repeatLookupsHitTheCache() { + final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class); + final World world = worldWith(biome, true); + + assertSame(biome, FogBiomeCache.get(world, 100, -7)); + assertSame(biome, FogBiomeCache.get(world, 100, -7)); + verify(world, times(1)).getBiomeGenForCoords(anyInt(), anyInt()); + } + + @Test + void unloadedChunksAreNotCached() { + final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class); + final World world = worldWith(biome, false); + + FogBiomeCache.get(world, 5000, 5000); + FogBiomeCache.get(world, 5000, 5000); + verify(world, times(2)).getBiomeGenForCoords(anyInt(), anyInt()); + } + + @Test + void worldChangeClearsTheCache() { + final BiomeGenBase a = Mockito.mock(BiomeGenBase.class); + final BiomeGenBase b = Mockito.mock(BiomeGenBase.class); + final World worldA = worldWith(a, true); + final World worldB = worldWith(b, true); + + assertSame(a, FogBiomeCache.get(worldA, 0, 0)); + assertSame(b, FogBiomeCache.get(worldB, 0, 0), "same coords in a new world must re-resolve"); + assertSame(a, FogBiomeCache.get(worldA, 0, 0), "switching back re-resolves rather than serving worldB state"); + } + + @Test + void negativeCoordinatesDoNotCollide() { + final BiomeGenBase biome = Mockito.mock(BiomeGenBase.class); + final World world = worldWith(biome, true); + + FogBiomeCache.get(world, -1, 0); + FogBiomeCache.get(world, 0, -1); + FogBiomeCache.get(world, -1, -1); + verify(world, times(3)).getBiomeGenForCoords(anyInt(), anyInt()); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/OverridesMethodTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/OverridesMethodTest.java new file mode 100644 index 000000000..a03d54921 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/OverridesMethodTest.java @@ -0,0 +1,70 @@ +package com.gtnewhorizons.angelica.rendering; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class OverridesMethodTest { + + static class Base { + public double dist(double x, double y, double z) { return 0; } + public boolean pass(int p) { return p == 0; } + } + + static class Plain extends Base {} + + static class Direct extends Base { + @Override public double dist(double x, double y, double z) { return 1; } + } + + static class Inherited extends Direct {} + + interface DefaultDist { + default double dist(double x, double y, double z) { return 2; } + } + + static class WithInterfaceDefault extends Base implements DefaultDist {} + + private static final String[] DIST = { "dist" }; + private static final String[] PASS = { "pass" }; + private static final Class[] DIST_PARAMS = { double.class, double.class, double.class }; + + @Test + void baseDeclarationIsNotAnOverride() { + assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Base.class, Base.class, DIST, DIST_PARAMS)); + assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, DIST, DIST_PARAMS)); + assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, PASS, int.class)); + } + + @Test + void directOverrideDetected() { + assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Direct.class, Base.class, DIST, DIST_PARAMS)); + } + + @Test + void inheritedOverrideDetected() { + assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Inherited.class, Base.class, DIST, DIST_PARAMS)); + } + + @Test + void classMethodBeatsInterfaceDefault() { + assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(WithInterfaceDefault.class, Base.class, DIST, DIST_PARAMS)); + } + + @Test + void unresolvableNameTreatedAsOverriding() { + assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, new String[] { "func_145835_a" }, DIST_PARAMS)); + } + + @Test + void wrongParametersTreatedAsOverriding() { + assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, DIST, double.class)); + } + + @Test + void firstMatchingCandidateNameWins() { + assertTrue(TileEntityRenderBoundsRegistry.overridesMethod(Direct.class, Base.class, new String[] { "func_145835_a", "dist" }, DIST_PARAMS)); + assertFalse(TileEntityRenderBoundsRegistry.overridesMethod(Plain.class, Base.class, new String[] { "func_145835_a", "dist" }, DIST_PARAMS)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMathTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMathTest.java new file mode 100644 index 000000000..f0d4b935b --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionAgeMathTest.java @@ -0,0 +1,58 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import org.junit.jupiter.api.Test; + +import static com.gtnewhorizons.angelica.rendering.celeritas.SectionAgeMath.STEP_NANOS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SectionAgeMathTest { + + @Test + void quantizeRoundsDownToStep() { + assertEquals(0L, SectionAgeMath.quantize(0L)); + assertEquals(0L, SectionAgeMath.quantize(STEP_NANOS - 1)); + assertEquals(STEP_NANOS, SectionAgeMath.quantize(STEP_NANOS)); + assertEquals(7 * STEP_NANOS, SectionAgeMath.quantize(7 * STEP_NANOS + 42)); + + assertEquals(-STEP_NANOS, SectionAgeMath.quantize(-1L)); + assertEquals(-2 * STEP_NANOS, SectionAgeMath.quantize(-STEP_NANOS - 1)); + assertEquals(-STEP_NANOS, SectionAgeMath.quantize(-STEP_NANOS)); + } + + @Test + void freshStateNeverSkips() { + final long[] state = SectionAgeMath.newState(); + assertFalse(SectionAgeMath.canSkip(state, 0L, 0L)); + assertFalse(SectionAgeMath.canSkip(state, 123L, SectionAgeMath.quantize(456L))); + } + + @Test + void unsaturatedSkipsOnlyWithinTheSameStep() { + final long[] state = SectionAgeMath.newState(); + final long newest = 1_000L; + final long tsQ = SectionAgeMath.quantize(50 * STEP_NANOS + 3); + SectionAgeMath.record(state, newest, tsQ, false); + + assertTrue(SectionAgeMath.canSkip(state, newest, tsQ)); + assertFalse(SectionAgeMath.canSkip(state, newest, tsQ + STEP_NANOS), "next step must rebuild"); + assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ), "newer section load must rebuild"); + } + + @Test + void saturatedSkipsAcrossStepsUntilNewestChanges() { + final long[] state = SectionAgeMath.newState(); + final long newest = 1_000L; + final long tsQ = SectionAgeMath.quantize(400 * STEP_NANOS); + SectionAgeMath.record(state, newest, tsQ, true); + + assertTrue(SectionAgeMath.canSkip(state, newest, tsQ)); + assertTrue(SectionAgeMath.canSkip(state, newest, tsQ + 10_000 * STEP_NANOS), "saturation is time-independent"); + assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ), "a new section load ends saturation"); + + SectionAgeMath.record(state, newest + 1, tsQ + STEP_NANOS, false); + assertTrue(SectionAgeMath.canSkip(state, newest + 1, tsQ + STEP_NANOS)); + assertFalse(SectionAgeMath.canSkip(state, newest + 1, tsQ + 2 * STEP_NANOS)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionFrustumGateTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionFrustumGateTest.java new file mode 100644 index 000000000..95cff85e4 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/SectionFrustumGateTest.java @@ -0,0 +1,101 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import net.minecraft.util.AxisAlignedBB; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.joml.FrustumIntersection; +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SectionFrustumGateTest { + + private static FrustumIntersection knownFrustum() { + return new FrustumIntersection(new Matrix4f().perspective((float) Math.toRadians(90), 1.0f, 0.1f, 100.0f)); + } + + @Test + void triStateVerdictsAgainstKnownPerspective() { + final FrustumIntersection frustum = knownFrustum(); + + assertEquals(FrustumIntersection.INSIDE, frustum.intersectAab(-1, -1, -50, 1, 1, -40)); + assertEquals(FrustumIntersection.INTERSECT, frustum.intersectAab(-1, -1, -5, 1, 1, 5)); + assertTrue(frustum.intersectAab(-1, -1, 10, 1, 1, 20) >= 0); + assertTrue(frustum.intersectAab(-100, -1, -20, -50, 1, -10) >= 0); + } + + @Test + void sectionVerdictIsSoundForContainedBoxes() { + final Random rng = new Random(0x5EC7104); + + for (int iter = 0; iter < 2000; iter++) { + final Matrix4f m = new Matrix4f() + .perspective((float) Math.toRadians(30 + rng.nextInt(90)), 0.5f + rng.nextFloat() * 2.0f, 0.05f, 64 + rng.nextFloat() * 448) + .rotateX((rng.nextFloat() - 0.5f) * (float) Math.PI) + .rotateY(rng.nextFloat() * 2.0f * (float) Math.PI); + final FrustumIntersection frustum = new FrustumIntersection(m); + + for (int s = 0; s < 50; s++) { + final float ox = (rng.nextFloat() - 0.5f) * 512; + final float oy = (rng.nextFloat() - 0.5f) * 512; + final float oz = (rng.nextFloat() - 0.5f) * 512; + + final int verdict = frustum.intersectAab(ox, oy, oz, ox + 16, oy + 16, oz + 16); + + final float lx = rng.nextFloat() * 15, ly = rng.nextFloat() * 15, lz = rng.nextFloat() * 15; + final float hx = lx + rng.nextFloat() * (16 - lx); + final float hy = ly + rng.nextFloat() * (16 - ly); + final float hz = lz + rng.nextFloat() * (16 - lz); + + final boolean boxVisible = frustum.testAab(ox + lx, oy + ly, oz + lz, ox + hx, oy + hy, oz + hz); + + if (verdict == FrustumIntersection.INSIDE) { + assertTrue(boxVisible, "box in INSIDE section must be visible"); + } else if (verdict >= 0) { + assertFalse(boxVisible, "box in plane-culled section must be culled"); + } + } + } + } + + @Test + void packedLocalBoundsMatchLegacyDoubleFormulation() { + final Random rng = new Random(0xA3B1D); + + for (int iter = 0; iter < 5000; iter++) { + final int ox = (rng.nextInt(4_000_000) - 2_000_000) & ~15; + final int oy = rng.nextInt(16) << 4; + final int oz = (rng.nextInt(4_000_000) - 2_000_000) & ~15; + + final CameraTransform t = new CameraTransform(ox + (rng.nextDouble() - 0.5) * 1024, oy + (rng.nextDouble() - 0.5) * 256, oz + (rng.nextDouble() - 0.5) * 1024); + + final double minX = ox + rng.nextDouble() * 15; + final double minY = oy + rng.nextDouble() * 15; + final double minZ = oz + rng.nextDouble() * 15; + final AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, minX + rng.nextDouble() * (ox + 16 - minX), minY + rng.nextDouble() * (oy + 16 - minY), minZ + rng.nextDouble() * (oz + 16 - minZ)); + + final FloatArrayList packed = new FloatArrayList(); + AngelicaBuiltRenderSectionData.packSectionLocalBounds(packed, aabb, ox, oy, oz); + + final float fx = (ox - t.intX) - t.fracX; + final float fy = (oy - t.intY) - t.fracY; + final float fz = (oz - t.intZ) - t.fracZ; + + final double[] world = { aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ }; + final float[] origin = { fx, fy, fz, fx, fy, fz }; + final int[] camInt = { t.intX, t.intY, t.intZ, t.intX, t.intY, t.intZ }; + final float[] camFrac = { t.fracX, t.fracY, t.fracZ, t.fracX, t.fracY, t.fracZ }; + + for (int i = 0; i < 6; i++) { + final float legacyCoord = (float) (world[i] - camInt[i]) - camFrac[i]; + final float packedCoord = origin[i] + packed.getFloat(i); + assertEquals(legacyCoord, packedCoord, 1e-3f, "coord " + i + " diverged at iter " + iter); + } + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMathTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMathTest.java new file mode 100644 index 000000000..1abfa07e3 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/celeritas/TeDistanceMathTest.java @@ -0,0 +1,66 @@ +package com.gtnewhorizons.angelica.rendering.celeritas; + +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TeDistanceMathTest { + + private static double distSq(double x1, double y1, double z1, double x2, double y2, double z2) { + final double dx = x1 - x2, dy = y1 - y2, dz = z1 - z2; + return dx * dx + dy * dy + dz * dz; + } + + @Test + void cameraInsideSectionIsZero() { + assertEquals(0.0, TeDistanceMath.distSqToSection(8, 8, 8, 0, 0, 0)); + assertEquals(0.0, TeDistanceMath.distSqToSection(16, 0, 16, 0, 0, 0)); + assertEquals(0.0, TeDistanceMath.distSqToSection(-32, 5, 100.5, -32, 0, 96)); + } + + @Test + void matchesClampFormulation() { + final Random rng = new Random(0xD157); + for (int iter = 0; iter < 10_000; iter++) { + final int ox = (rng.nextInt(4_000_000) - 2_000_000) & ~15; + final int oy = rng.nextInt(16) << 4; + final int oz = (rng.nextInt(4_000_000) - 2_000_000) & ~15; + final double camX = ox + (rng.nextDouble() - 0.5) * 512; + final double camY = oy + (rng.nextDouble() - 0.5) * 512; + final double camZ = oz + (rng.nextDouble() - 0.5) * 512; + + final double cx = Math.max(ox, Math.min(camX, ox + 16)); + final double cy = Math.max(oy, Math.min(camY, oy + 16)); + final double cz = Math.max(oz, Math.min(camZ, oz + 16)); + final double expected = distSq(camX, camY, camZ, cx, cy, cz); + + assertEquals(expected, TeDistanceMath.distSqToSection(camX, camY, camZ, ox, oy, oz), 1e-9, "clamp formulation diverged at iter " + iter); + } + } + + @Test + void lowerBoundsEveryPointInSection() { + final Random rng = new Random(0xB0C5); + for (int iter = 0; iter < 2_000; iter++) { + final int ox = (rng.nextInt(200_000) - 100_000) & ~15; + final int oy = rng.nextInt(16) << 4; + final int oz = (rng.nextInt(200_000) - 100_000) & ~15; + final double camX = ox + (rng.nextDouble() - 0.5) * 256; + final double camY = oy + (rng.nextDouble() - 0.5) * 256; + final double camZ = oz + (rng.nextDouble() - 0.5) * 256; + + final double sectionDistSq = TeDistanceMath.distSqToSection(camX, camY, camZ, ox, oy, oz); + + for (int s = 0; s < 30; s++) { + final double px = ox + rng.nextDouble() * 16; + final double py = oy + rng.nextDouble() * 16; + final double pz = oz + rng.nextDouble() * 16; + final double pointDistSq = distSq(camX, camY, camZ, px, py, pz); + assertTrue(pointDistSq >= sectionDistSq - 1e-9, "point dist " + pointDistSq + " < section dist " + sectionDistSq + " at iter " + iter); + } + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/CullingShaderCompileTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/CullingShaderCompileTest.java new file mode 100644 index 000000000..65e61bf8e --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/CullingShaderCompileTest.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@GLCoreTest +class CullingShaderCompileTest { + + private static String source(String name) throws IOException { + try (InputStream in = CullingShaderCompileTest.class.getResourceAsStream("/assets/angelica/shaders/culling/" + name)) { + assertNotNull(in, "missing shader resource: " + name); + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static void assertCompiles(String name) throws IOException { + assumeTrue(RenderSystem.supportsCompute(), "compute shaders unsupported"); + final int shader = GLStateManager.glCreateShader(GL43.GL_COMPUTE_SHADER); + try { + GLStateManager.glShaderSource(shader, source(name)); + GLStateManager.glCompileShader(shader); + final int status = GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS); + assertEquals(GL11.GL_TRUE, status, () -> name + " failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096)); + } finally { + GLStateManager.glDeleteShader(shader); + } + } + + @Test + void chunkCullCompiles() throws IOException { + assertCompiles("chunk_cull.csh"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractorTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractorTest.java new file mode 100644 index 000000000..d7f2b68a7 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/FrustumExtractorTest.java @@ -0,0 +1,92 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FrustumExtractorTest { + private static final float EPS = 1e-4f; + + @Test + void uboSizeIs160() { + assertEquals(160, FrustumExtractor.UBO_SIZE_BYTES); + assertEquals(0, FrustumExtractor.UBO_SIZE_BYTES % 16, "std140 requires a 16-byte multiple"); + } + + @Test + void patchBatchEntryBase_writesAtOffset128_andWriteStd140Resets() { + final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer(); + FrustumExtractor.patchBatchEntryBase(777, out); + assertEquals(777, out.getInt(128)); + FrustumExtractor.writeStd140(new Matrix4f(), 0, 0, out); + assertEquals(0, out.getInt(128), "writeStd140 must reset entryBase"); + } + + @Test + void identityMatrix_planesAreUnitNormalsAtUnitDistance() { + final Matrix4f identity = new Matrix4f(); + final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer(); + FrustumExtractor.writeStd140(identity, 0, 0, out); + + assertPlane(out, 0, 1f, 0f, 0f, 1f); + assertPlane(out, 16, -1f, 0f, 0f, 1f); + assertPlane(out, 32, 0f, 1f, 0f, 1f); + assertPlane(out, 48, 0f, -1f, 0f, 1f); + assertPlane(out, 64, 0f, 0f, 1f, 1f); + assertPlane(out, 80, 0f, 0f, -1f, 1f); + } + + @Test + void identityMatrix_left_correct() { + final Matrix4f identity = new Matrix4f(); + final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer(); + FrustumExtractor.writeStd140(identity, 0, 0, out); + assertPlane(out, 0, 1f, 0f, 0f, 1f); + } + + @Test + void perspectiveAxisAlignedPoint_insideFrustum() { + final Matrix4f proj = new Matrix4f().perspective((float) Math.toRadians(70.0), 16f / 9f, 0.1f, 1000.0f); + final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer(); + FrustumExtractor.writeStd140(proj, 0, 0, out); + + assertTrue(insideAllPlanes(out, new Vector3f(0f, 0f, -10f)), "point ahead should be inside"); + assertTrue(!insideAllPlanes(out, new Vector3f(0f, 0f, 10f)), "point behind should be outside"); + } + + @Test + void visibleCountStored() { + final Matrix4f mvp = new Matrix4f(); + final ByteBuffer out = FrustumExtractor.allocateUboByteBuffer(); + FrustumExtractor.writeStd140(mvp, 4242, 0, out); + assertEquals(4242, out.getInt(96), "visibleCount at offset 96"); + assertEquals(0, out.getInt(100)); + assertEquals(0, out.getInt(104)); + assertEquals(0, out.getInt(108)); + } + + private static void assertPlane(ByteBuffer out, int offset, float a, float b, float c, float d) { + final float len = (float) Math.sqrt(a * a + b * b + c * c); + final float inv = len == 0.0f ? 1.0f : 1.0f / len; + assertEquals(a * inv, out.getFloat(offset + 0), EPS, "a @" + offset); + assertEquals(b * inv, out.getFloat(offset + 4), EPS, "b @" + offset); + assertEquals(c * inv, out.getFloat(offset + 8), EPS, "c @" + offset); + assertEquals(d * inv, out.getFloat(offset + 12), EPS, "d @" + offset); + } + + private static boolean insideAllPlanes(ByteBuffer out, Vector3f p) { + for (int i = 0; i < 6; i++) { + final float a = out.getFloat(i * 16 + 0); + final float b = out.getFloat(i * 16 + 4); + final float c = out.getFloat(i * 16 + 8); + final float d = out.getFloat(i * 16 + 12); + if (a * p.x + b * p.y + c * p.z + d < 0.0f) return false; + } + return true; + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/IndirectCullDrawParityTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/IndirectCullDrawParityTest.java new file mode 100644 index 000000000..326b2a969 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/IndirectCullDrawParityTest.java @@ -0,0 +1,645 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizons.angelica.config.GpuCullingMode; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute; +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeBinding; +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat; +import org.embeddedt.embeddium.impl.gl.array.GlVertexArray; +import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage; +import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer; +import org.embeddedt.embeddium.impl.gl.device.CommandList; +import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice; +import org.embeddedt.embeddium.impl.gl.device.RenderDevice; +import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; +import org.embeddedt.embeddium.impl.gl.tessellation.GlVertexArrayTessellation; +import org.embeddedt.embeddium.impl.gl.tessellation.TessellationBinding; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.joml.Matrix4f; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL43; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@GLCoreTest +class IndirectCullDrawParityTest { + + private static final int FBO_SIZE = 128; + private static final int GRID = 16; + private static final int FACINGS = 7; + private static final int CMD_INTS = 5; + + private static final int SOLID_PASS = 0; + private static final int CUTOUT_PASS = 1; + private static final int SORTED_PASS = 2; + + private static final int[] SOLID_MASKS = { 0x7F, 0x55, 0x2A, 0x63, 0x1C }; + private static final int[] CUTOUT_MASKS = { 0x33, 0x4D, 0x7F }; + private static final int REGION1_SOLID_SECTIONS = 3; + + private static CommandList commandList; + private static int program; + + private static final class Section { + int passIndex; + int sliceMask; + int slot = -1; + final int[] quadCount = new int[FACINGS]; + final int[] vertexOffset = new int[FACINGS]; + final int[] elementCount = new int[FACINGS]; + final int[] indexOffset = new int[FACINGS]; + ByteBuffer srd; + + long srdAddress() { return MemoryUtilities.memAddress(srd); } + + void writeSrd() { + srd.putInt(0, sliceMask); + srd.putInt(4, 0); + for (int f = 0; f < FACINGS; f++) { + final int off = 8 + f * 12; + srd.putInt(off + 0, vertexOffset[f]); + srd.putInt(off + 4, elementCount[f]); + srd.putInt(off + 8, indexOffset[f]); + } + } + } + + private static final class Scene { + final List

solid = new ArrayList<>(); + final List
cutout = new ArrayList<>(); + final List
sorted = new ArrayList<>(); + FloatBuffer vertices; + ByteBuffer sharedIndices; + ByteBuffer sortedIndices; + int totalQuads; + + List
all() { + final List
all = new ArrayList<>(solid); + all.addAll(cutout); + all.addAll(sorted); + return all; + } + } + + @BeforeAll + static void setUpDevice() { + GLRenderDevice.VANILLA_STATE_RESETTER = () -> {}; + RenderDevice.enterManagedCode(); + commandList = RenderDevice.INSTANCE.createCommandList(); + program = buildProgram(); + GpuCulling.setMode(GpuCullingMode.COMPUTE); + } + + @AfterAll + static void tearDownDevice() { + GpuCulling.setMode(GpuCullingMode.CPU_ONLY); + if (program != 0) GLStateManager.glDeleteProgram(program); + RenderDevice.exitManagedCode(); + } + + @AfterEach + void resetGlState() { + GLStateManager.glUseProgram(0); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDisable(GL11.GL_DEPTH_TEST); + GLStateManager.glViewport(0, 0, 800, 600); + } + + static final String FLAT_VS = "#version 330 core\n" + + "layout(location = 0) in vec3 a_Pos;\n" + + "void main() { gl_Position = vec4(a_Pos, 1.0); }\n"; + static final String FLAT_FS = "#version 330 core\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = vec4(1.0); }\n"; + + static int compileShader(int type, String src) { + final int shader = GLStateManager.glCreateShader(type); + GLStateManager.glShaderSource(shader, src); + GLStateManager.glCompileShader(shader); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS), () -> "shader failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096)); + return shader; + } + + private static int buildProgram() { + final int vsh = compileShader(GL20.GL_VERTEX_SHADER, FLAT_VS); + final int fsh = compileShader(GL20.GL_FRAGMENT_SHADER, FLAT_FS); + final int prog = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(prog, vsh); + GLStateManager.glAttachShader(prog, fsh); + GLStateManager.glLinkProgram(prog); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetProgrami(prog, GL20.GL_LINK_STATUS), () -> "parity program failed to link:\n" + GLStateManager.glGetProgramInfoLog(prog, 4096)); + GLStateManager.glDeleteShader(vsh); + GLStateManager.glDeleteShader(fsh); + return prog; + } + + private static Scene buildScene() { + final Scene scene = new Scene(); + for (int s = 0; s < SOLID_MASKS.length; s++) { + scene.solid.add(newSection(SOLID_PASS, SOLID_MASKS[s], s)); + } + for (int s = 0; s < CUTOUT_MASKS.length; s++) { + scene.cutout.add(newSection(CUTOUT_PASS, CUTOUT_MASKS[s], SOLID_MASKS.length + s)); + } + for (int s = 0; s < SOLID_MASKS.length; s++) { + scene.sorted.add(newSection(SORTED_PASS, SOLID_MASKS[s], s + 1)); + } + + int quad = 0; + int vertex = 0; + int maxQuadsPerDraw = 0; + int sortedIndexInts = 0; + final List quadRects = new ArrayList<>(); + for (Section section : allOf(scene)) { + final int sectionFirstVertex = vertex; + for (int f = 0; f < FACINGS; f++) { + section.vertexOffset[f] = vertex; + section.elementCount[f] = 6 * section.quadCount[f]; + section.indexOffset[f] = section.passIndex == SORTED_PASS ? sortedIndexInts * 4 : 0; + if (section.passIndex == SORTED_PASS) sortedIndexInts += section.elementCount[f]; + for (int q = 0; q < section.quadCount[f]; q++) { + quadRects.add(quadRect(quad)); + quad++; + vertex += 4; + } + } + maxQuadsPerDraw = Math.max(maxQuadsPerDraw, (vertex - sectionFirstVertex) / 4); + section.writeSrd(); + } + scene.totalQuads = quad; + assertTrue(quad <= GRID * GRID, "scene overflows the NDC cell grid"); + + scene.vertices = BufferUtils.createFloatBuffer(vertex * 3); + for (float[] rect : quadRects) { + final float x0 = rect[0], y0 = rect[1], x1 = rect[2], y1 = rect[3], z = rect[4]; + scene.vertices.put(x0).put(y0).put(z); + scene.vertices.put(x1).put(y0).put(z); + scene.vertices.put(x1).put(y1).put(z); + scene.vertices.put(x0).put(y1).put(z); + } + scene.vertices.flip(); + + scene.sharedIndices = BufferUtils.createByteBuffer(6 * maxQuadsPerDraw * 4).order(ByteOrder.nativeOrder()); + for (int q = 0; q < maxQuadsPerDraw; q++) { + putQuadIndices(scene.sharedIndices, 4 * q); + } + scene.sharedIndices.flip(); + + scene.sortedIndices = BufferUtils.createByteBuffer(sortedIndexInts * 4).order(ByteOrder.nativeOrder()); + for (Section section : scene.sorted) { + for (int f = 0; f < FACINGS; f++) { + if ((section.sliceMask & (1 << f)) == 0) continue; + for (int q = 0; q < section.quadCount[f]; q++) { + putQuadIndices(scene.sortedIndices, 4 * q); + } + } + } + scene.sortedIndices.flip(); + return scene; + } + + private static List
allOf(Scene scene) { + return scene.all(); + } + + private static Section newSection(int passIndex, int sliceMask, int seed) { + final Section section = new Section(); + section.passIndex = passIndex; + section.sliceMask = sliceMask; + for (int f = 0; f < FACINGS; f++) { + if ((sliceMask & (1 << f)) != 0) { + section.quadCount[f] = 1 + ((seed + f) % 3); + } + } + section.srd = MemoryUtilities.memAlloc(92).order(ByteOrder.nativeOrder()); + return section; + } + + private static float[] quadRect(int quadIndex) { + final int cx = quadIndex % GRID; + final int cy = quadIndex / GRID; + final float cell = 2.0f / GRID; + final float x0 = -1.0f + cx * cell + cell * 0.1f; + final float y0 = -1.0f + cy * cell + cell * 0.1f; + final float z = -0.9f + 1.8f * quadIndex / (GRID * GRID); + return new float[] { x0, y0, x0 + cell * 0.8f, y0 + cell * 0.8f, z }; + } + + private static void putQuadIndices(ByteBuffer out, int base) { + out.putInt(base).putInt(base + 1).putInt(base + 2); + out.putInt(base + 2).putInt(base + 3).putInt(base); + } + + private static GlMutableBuffer upload(ByteBuffer data) { + final GlMutableBuffer buffer = commandList.createMutableBuffer(); + commandList.uploadData(buffer, data, GlBufferUsage.STATIC_DRAW); + return buffer; + } + + private static GlVertexArrayTessellation tessellation(GlMutableBuffer vertexBuffer, GlMutableBuffer indexBuffer) { + final GlVertexAttribute position = new GlVertexAttribute(GlVertexAttributeFormat.FLOAT, "a_Pos", 3, false, 0, 12, false); + final TessellationBinding[] bindings = { + TessellationBinding.forVertexBuffer(vertexBuffer, new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(0, position) }), + TessellationBinding.forElementBuffer(indexBuffer), + }; + final GlVertexArrayTessellation tess = new GlVertexArrayTessellation(new GlVertexArray(), bindings); + tess.init(commandList); + return tess; + } + + private static int newFbo(int[] texturesOut) { + final int depthTex = GLStateManager.glGenTextures(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, depthTex); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_DEPTH_COMPONENT32F, FBO_SIZE, FBO_SIZE, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + final int colorTex = GLStateManager.glGenTextures(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, colorTex); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, FBO_SIZE, FBO_SIZE, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + + final int fbo = GLStateManager.glGenFramebuffers(); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo); + GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTex, 0); + GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTex, 0); + assertEquals(GL30.GL_FRAMEBUFFER_COMPLETE, GLStateManager.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER), "parity FBO incomplete"); + texturesOut[0] = depthTex; + texturesOut[1] = colorTex; + return fbo; + } + + private static void beginDrawing(int fbo) { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo); + GLStateManager.glViewport(0, 0, FBO_SIZE, FBO_SIZE); + GLStateManager.glEnable(GL11.GL_DEPTH_TEST); + GLStateManager.glDepthFunc(GL11.GL_LESS); + GLStateManager.glDepthMask(true); + GLStateManager.disableCull(); + GLStateManager.glClearDepth(1.0); + GLStateManager.glClearColor(0f, 0f, 0f, 0f); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_COLOR_BUFFER_BIT); + GLStateManager.glUseProgram(program); + } + + private static FloatBuffer readDepth(int fbo) { + GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fbo); + final FloatBuffer depth = BufferUtils.createFloatBuffer(FBO_SIZE * FBO_SIZE); + GLStateManager.glReadPixels(0, 0, FBO_SIZE, FBO_SIZE, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, depth); + return depth; + } + + private static int coveredPixels(FloatBuffer depth) { + int covered = 0; + for (int i = 0; i < depth.capacity(); i++) { + if (depth.get(i) < 1.0f) covered++; + } + return covered; + } + + private static void assertDepthParity(int directFbo, int gpuFbo, String label) { + final FloatBuffer direct = readDepth(directFbo); + final FloatBuffer gpu = readDepth(gpuFbo); + final int covered = coveredPixels(direct); + assertTrue(covered > 100, label + ": direct path drew almost nothing (" + covered + " covered pixels); scene setup is broken"); + assertEquals(covered, coveredPixels(gpu), label + ": covered pixel count differs between direct and GPU-culled indirect"); + for (int i = 0; i < direct.capacity(); i++) { + if (direct.get(i) != gpu.get(i)) { + final int x = i % FBO_SIZE; + final int y = i / FBO_SIZE; + assertEquals(direct.get(i), gpu.get(i), label + ": depth mismatch at (" + x + "," + y + "); the GPU-culled indirect path rendered different geometry than the direct path"); + } + } + } + + private static RenderRegion newRegionKey() { + try { + for (Constructor ctor : RenderRegion.class.getDeclaredConstructors()) { + if (ctor.getParameterCount() == 5) { + ctor.setAccessible(true); + return (RenderRegion) ctor.newInstance(0, 0, 0, 0, null); + } + } + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + throw new IllegalStateException("RenderRegion constructor shape changed"); + } + + private static int reflectInt(GpuIndirectMultiDrawEmitter emitter, String fieldName) { + try { + final Field field = GpuIndirectMultiDrawEmitter.class.getDeclaredField(fieldName); + field.setAccessible(true); + return field.getInt(emitter); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + private static ByteBuffer frustumUbo(int indexPointerMask) { + final ByteBuffer ubo = FrustumExtractor.allocateUboByteBuffer(); + final Matrix4f identity = new Matrix4f(); + FrustumExtractor.writeStd140(identity, 0, indexPointerMask, ubo); + FrustumExtractor.patchCameraWorld(0f, 0f, 0f, ubo); + FrustumExtractor.patchBypassFrustum(true, ubo); + FrustumExtractor.patchPrimitiveRatio(QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), QuadPrimitiveType.TRIANGULATED.getIndexBufferElementsPerPrimitive(), ubo); + return ubo; + } + + private static void metaUpdate(SectionMetaBuffer meta, Section section, int localSectionIndex) { + section.slot = meta.update(section.passIndex, 0, 0, 0, localSectionIndex, section.srdAddress(), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertTrue(section.slot >= 0, "meta rejected section for pass " + section.passIndex + " local index " + localSectionIndex); + } + + private static void pushSectionCommands(DrawCommandSink sink, long srdAddress, int sliceMask, int indexPointerMask) { + for (int facing = 0; facing < FACINGS; facing++) { + if (((sliceMask >> facing) & 1) == 0) { + continue; + } + + sink.push(SectionRenderDataUnsafe.Strategy.FULL.getVertexOffset(srdAddress, facing), + SectionRenderDataUnsafe.Strategy.FULL.getElementCount(srdAddress, facing, QuadPrimitiveType.TRIANGULATED), + SectionRenderDataUnsafe.Strategy.FULL.getIndexOffset(srdAddress, facing) & indexPointerMask); + } + } + + private static void renderCpuEmitter(Scene scene, int fbo, GlVertexArrayTessellation tessNonSorted, GlVertexArrayTessellation tessSorted, MultiDrawEmitter emitter) { + beginDrawing(fbo); + + renderCpuPass(emitter, tessNonSorted, 0, List.of( + scene.solid.subList(0, REGION1_SOLID_SECTIONS), + scene.solid.subList(REGION1_SOLID_SECTIONS, scene.solid.size()))); + renderCpuPass(emitter, tessNonSorted, 0, List.of(scene.cutout)); + renderCpuPass(emitter, tessSorted, 0xFFFFFFFF, List.of(scene.sorted)); + } + + private static void renderCpuPass(MultiDrawEmitter emitter, GlVertexArrayTessellation tessellation, int indexPointerMask, List> regions) { + final DrawCommandSink sink = emitter.getCommandSink(); + + if (!emitter.batchesWholePass()) { + for (List
region : regions) { + sink.clear(); + for (Section section : region) { + pushSectionCommands(sink, section.srdAddress(), section.sliceMask, indexPointerMask); + } + emitter.executeBatch(commandList, tessellation, GlPrimitiveType.TRIANGLES); + } + return; + } + + int sectionCount = 0; + for (List
region : regions) { + sectionCount += region.size(); + } + + emitter.beginPass(commandList, sectionCount); + + final int[] commandCounts = new int[regions.size()]; + for (int r = 0; r < regions.size(); r++) { + sink.clear(); + for (Section section : regions.get(r)) { + pushSectionCommands(sink, section.srdAddress(), section.sliceMask, indexPointerMask); + } + commandCounts[r] = sink.size(); + } + + emitter.finishAssembly(commandList); + + int firstCommand = 0; + for (int count : commandCounts) { + emitter.selectDrawRange(firstCommand, count); + firstCommand += count; + emitter.executeBatch(commandList, tessellation, GlPrimitiveType.TRIANGLES); + } + + emitter.onPassFinished(commandList); + } + + private static final class GpuFramePasses { + final List expectedCombined = new ArrayList<>(); + final List expectedSorted = new ArrayList<>(); + int combinedIndirectBuffer; + int sortedIndirectBuffer; + } + + private static GpuFramePasses renderGpu(Scene scene, int fbo, GlVertexArrayTessellation tessNonSorted, GlVertexArrayTessellation tessSorted, GpuIndirectMultiDrawEmitter gpu, RenderRegion region1, RenderRegion region2, String frameLabel) { + final GpuFramePasses result = new GpuFramePasses(); + beginDrawing(fbo); + + gpu.beginCombinedPasses(0, 0); + assertTrue(gpu.isComputeActiveThisPass(), "compute path unexpectedly inactive"); + gpu.setFrustumUboBytes(frustumUbo(0)); + gpu.syncSectionMetaIfDirty(); + + int outputBase = 0; + outputBase = walkSections(scene.solid.subList(0, REGION1_SOLID_SECTIONS), gpu, region1, outputBase, result.expectedCombined, 0); + outputBase = walkSections(scene.solid.subList(REGION1_SOLID_SECTIONS, scene.solid.size()), gpu, region2, outputBase, result.expectedCombined, 0); + gpu.startSecondPass(); + walkSections(scene.cutout, gpu, region1, outputBase, result.expectedCombined, 0); + gpu.finishCombinedBuild(); + + gpu.prepareRegion(region1); + gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES); + gpu.prepareRegion(region2); + gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES); + gpu.endPass(); + + assertTrue(gpu.selectPreparedSecondPass(), "prepared cutout pass was not selectable"); + gpu.prepareRegion(region1); + gpu.executeBatch(commandList, tessNonSorted, GlPrimitiveType.TRIANGLES); + gpu.endPass(); + result.combinedIndirectBuffer = reflectInt(gpu, "indirectSsboGlId"); + assertIndirectBufferMatches(result.combinedIndirectBuffer, result.expectedCombined, frameLabel + " combined solid+cutout pass"); + + gpu.beginCullPass(0xFFFFFFFF); + gpu.setFrustumUboBytes(frustumUbo(0xFFFFFFFF)); + gpu.syncSectionMetaIfDirty(); + walkSections(scene.sorted, gpu, region1, 0, result.expectedSorted, 0xFFFFFFFF); + gpu.prepareRegion(region1); + gpu.executeBatch(commandList, tessSorted, GlPrimitiveType.TRIANGLES); + gpu.endPass(); + result.sortedIndirectBuffer = reflectInt(gpu, "indirectSsboGlId"); + assertIndirectBufferMatches(result.sortedIndirectBuffer, result.expectedSorted, frameLabel + " sorted pass"); + + return result; + } + + private static int walkSections(List
sections, GpuIndirectMultiDrawEmitter gpu, RenderRegion region, int outputBase, List expectedCommands, int indexPointerMask) { + gpu.reserveSections(sections.size()); + final int drawStart = outputBase; + int drawCount = 0; + int entryStart = -1; + int entryCount = 0; + int maxElems = 0; + for (int i = 0; i < sections.size(); i++) { + final Section section = sections.get(i); + final int entryIdx = gpu.appendSection(section.slot, section.sliceMask, outputBase); + if (entryStart < 0) entryStart = entryIdx; + entryCount++; + + final boolean mergeRuns = indexPointerMask == 0; + final long runs = mergeRuns ? BatchAssembler.packRuns(section.sliceMask & 0x7F) : 0L; + final int runCount = mergeRuns ? BatchAssembler.runCount(runs) : Integer.bitCount(section.sliceMask & 0x7F); + final long srd = section.srdAddress(); + final SectionRenderDataUnsafe.Strategy layout = SectionRenderDataUnsafe.Strategy.FULL; + final int sectionBase = layout.getVertexOffset(srd, 0); + final int indexBase = layout.getIndexOffset(srd, 0) / 4; + int singleFacing = -1; + for (int run = 0; run < runCount; run++) { + if (!mergeRuns) { + do { singleFacing++; } while ((section.sliceMask & (1 << singleFacing)) == 0); + } + final int firstFacing = mergeRuns ? BatchAssembler.runFirst(runs, run) : singleFacing; + final int lastFacing = mergeRuns ? BatchAssembler.runLast(runs, run) : singleFacing; + final int startVertex = layout.getVertexOffset(srd, firstFacing); + final int endVertex = layout.getRunVertexEnd(srd, lastFacing, QuadPrimitiveType.TRIANGULATED); + final int elements = SectionRenderDataUnsafe.elementsForVertices(endVertex - startVertex, QuadPrimitiveType.TRIANGULATED); + final int firstIndex = indexBase + + SectionRenderDataUnsafe.elementsForVertices(startVertex - sectionBase, QuadPrimitiveType.TRIANGULATED); + expectedCommands.add(new int[] { elements, 1, firstIndex & indexPointerMask, startVertex, 0 }); + outputBase++; + drawCount++; + maxElems = Math.max(maxElems, elements); + } + } + if (drawCount > 0) { + gpu.recordRegion(region, drawStart, drawCount, entryStart, entryCount, maxElems); + } + return outputBase; + } + + private static void assertIndirectBufferMatches(int bufferId, List expected, String label) { + assertNotEquals(0, bufferId, label + ": no indirect buffer was created"); + final ByteBuffer readback = BufferUtils.createByteBuffer(expected.size() * CMD_INTS * 4).order(ByteOrder.nativeOrder()); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, bufferId); + GLStateManager.glGetBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, readback); + GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, 0); + final String[] fieldNames = { "count", "instanceCount", "firstIndex", "baseVertex", "baseInstance" }; + for (int c = 0; c < expected.size(); c++) { + for (int i = 0; i < CMD_INTS; i++) { + assertEquals(expected.get(c)[i], readback.getInt((c * CMD_INTS + i) * 4), label + ": command " + c + " field " + fieldNames[i] + " differs from the CPU-computed command stream"); + } + } + } + + @Test + void gpuCulledIndirectMatchesDirectAcrossFrames() { + assumeTrue(RenderSystem.supportsCompute(), "compute shaders unsupported"); + final Scene scene = buildScene(); + final GpuDrivenChunkCuller culler = new GpuDrivenChunkCuller(); + assertTrue(culler.ensureReady(), "chunk_cull.csh failed to load on a real driver"); + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final GpuIndirectMultiDrawEmitter gpu = new GpuIndirectMultiDrawEmitter(culler, meta); + final RenderRegion region1 = newRegionKey(); + final RenderRegion region2 = newRegionKey(); + + final DirectMultiDrawEmitter direct = new DirectMultiDrawEmitter(); + final IndirectMultiDrawEmitter cpuIndirect = new IndirectMultiDrawEmitter(); + GlMutableBuffer vertexBuffer = null; + GlMutableBuffer sharedIndexBuffer = null; + GlMutableBuffer sortedIndexBuffer = null; + GlVertexArrayTessellation tessNonSorted = null; + GlVertexArrayTessellation tessSorted = null; + final int[] directTex = new int[2]; + final int[] cpuTex = new int[2]; + final int[] gpuTex = new int[2]; + int directFbo = 0; + int cpuFbo = 0; + int gpuFbo = 0; + try { + final ByteBuffer vertexBytes = BufferUtils.createByteBuffer(scene.vertices.capacity() * 4).order(ByteOrder.nativeOrder()); + vertexBytes.asFloatBuffer().put(scene.vertices.duplicate()); + vertexBuffer = upload(vertexBytes); + sharedIndexBuffer = upload(scene.sharedIndices.duplicate().order(ByteOrder.nativeOrder())); + sortedIndexBuffer = upload(scene.sortedIndices.duplicate().order(ByteOrder.nativeOrder())); + tessNonSorted = tessellation(vertexBuffer, sharedIndexBuffer); + tessSorted = tessellation(vertexBuffer, sortedIndexBuffer); + directFbo = newFbo(directTex); + cpuFbo = newFbo(cpuTex); + gpuFbo = newFbo(gpuTex); + + int local = 0; + for (Section section : scene.solid) metaUpdate(meta, section, local++); + local = 0; + for (Section section : scene.cutout) metaUpdate(meta, section, local++); + local = 0; + for (Section section : scene.sorted) metaUpdate(meta, section, local++); + + for (int frame = 1; frame <= 2; frame++) { + renderCpuEmitter(scene, directFbo, tessNonSorted, tessSorted, direct); + renderCpuEmitter(scene, cpuFbo, tessNonSorted, tessSorted, cpuIndirect); + renderGpu(scene, gpuFbo, tessNonSorted, tessSorted, gpu, region1, region2, "frame " + frame); + assertDepthParity(directFbo, cpuFbo, "frame " + frame + " (celeritas CPU indirect emitter)"); + assertDepthParity(directFbo, gpuFbo, "frame " + frame + " (GPU-culled indirect emitter)"); + } + + final Section mutated = scene.solid.get(0); + int shrinkFacing = -1; + for (int f = 0; f < FACINGS; f++) { + if ((mutated.sliceMask & (1 << f)) != 0 && mutated.quadCount[f] > 1) { shrinkFacing = f; break; } + } + assertTrue(shrinkFacing >= 0, "scene has no shrinkable facing"); + mutated.quadCount[shrinkFacing]--; + mutated.elementCount[shrinkFacing] -= 6; + + for (int f = shrinkFacing + 1; f < FACINGS; f++) { + mutated.vertexOffset[f] -= 4; + if (mutated.passIndex == SORTED_PASS) mutated.indexOffset[f] -= 6 * 4; + } + mutated.writeSrd(); + metaUpdate(meta, mutated, 0); + + renderCpuEmitter(scene, directFbo, tessNonSorted, tessSorted, direct); + renderCpuEmitter(scene, cpuFbo, tessNonSorted, tessSorted, cpuIndirect); + renderGpu(scene, gpuFbo, tessNonSorted, tessSorted, gpu, region1, region2, "frame 3 (after section mesh update)"); + assertDepthParity(directFbo, cpuFbo, "frame 3 (celeritas CPU indirect emitter)"); + assertDepthParity(directFbo, gpuFbo, "frame 3 (GPU-culled indirect emitter)"); + } finally { + direct.delete(); + cpuIndirect.delete(); + gpu.delete(); + meta.shutdown(); + culler.shutdown(); + if (tessNonSorted != null) tessNonSorted.delete(commandList); + if (tessSorted != null) tessSorted.delete(commandList); + if (vertexBuffer != null) commandList.deleteBuffer(vertexBuffer); + if (sharedIndexBuffer != null) commandList.deleteBuffer(sharedIndexBuffer); + if (sortedIndexBuffer != null) commandList.deleteBuffer(sortedIndexBuffer); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + if (directFbo != 0) GLStateManager.glDeleteFramebuffers(directFbo); + if (cpuFbo != 0) GLStateManager.glDeleteFramebuffers(cpuFbo); + if (gpuFbo != 0) GLStateManager.glDeleteFramebuffers(gpuFbo); + for (int tex : directTex) if (tex != 0) GLStateManager.glDeleteTextures(tex); + for (int tex : cpuTex) if (tex != 0) GLStateManager.glDeleteTextures(tex); + for (int tex : gpuTex) if (tex != 0) GLStateManager.glDeleteTextures(tex); + for (Section section : scene.all()) MemoryUtilities.memFree(section.srd); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/MultiDrawCompatStompTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/MultiDrawCompatStompTest.java new file mode 100644 index 000000000..9813fff31 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/MultiDrawCompatStompTest.java @@ -0,0 +1,127 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizons.angelica.glsm.CompatUniformManager; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.joml.Matrix4f; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL40; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@GLCoreTest +class MultiDrawCompatStompTest { + + private static final Matrix4f SENTINEL = new Matrix4f().scaling(2f, 3f, 4f).setTranslation(5f, 6f, 7f); + private static final Matrix4f LEGACY_CAMERA = new Matrix4f().rotationY(0.7f).setTranslation(-11f, -22f, -33f); + + private static final String IRIS_MVM_VS = "#version 330 core\n" + + "uniform mat4 iris_ModelViewMatrix;\n" + + "layout(location = 0) in vec3 a_Pos;\n" + + "void main() { gl_Position = iris_ModelViewMatrix * vec4(a_Pos, 1.0); }\n"; + + private int vsh; + private int fsh; + private int program; + private int vao; + private int indirectBuffer; + private int elementBuffer; + private int location; + + private static void putMatrix(Matrix4f m, FloatBuffer buf) { + buf.clear(); + m.get(buf); + buf.position(0).limit(16); + } + + private static Matrix4f readUniform(int program, int location) { + final FloatBuffer buf = BufferUtils.createFloatBuffer(16); + GLStateManager.glGetUniform(program, location, buf); + return new Matrix4f(buf); + } + + @BeforeEach + void armSentinel() { + vsh = IndirectCullDrawParityTest.compileShader(GL20.GL_VERTEX_SHADER, IRIS_MVM_VS); + fsh = IndirectCullDrawParityTest.compileShader(GL20.GL_FRAGMENT_SHADER, IndirectCullDrawParityTest.FLAT_FS); + program = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(program, vsh); + GLStateManager.glAttachShader(program, fsh); + GLStateManager.glLinkProgram(program); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetProgrami(program, GL20.GL_LINK_STATUS), () -> "program failed to link:\n" + GLStateManager.glGetProgramInfoLog(program, 4096)); + assertTrue(CompatUniformManager.hasProgram(program), "program with iris_ModelViewMatrix was not registered by CompatUniformManager at link"); + location = GLStateManager.glGetUniformLocation(program, "iris_ModelViewMatrix"); + assertTrue(location >= 0, "iris_ModelViewMatrix location not found"); + + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + elementBuffer = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, elementBuffer); + GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createByteBuffer(12), GL15.GL_STATIC_DRAW); + indirectBuffer = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, indirectBuffer); + final ByteBuffer zeroCommand = BufferUtils.createByteBuffer(20).order(ByteOrder.nativeOrder()); + GLStateManager.glBufferData(GL40.GL_DRAW_INDIRECT_BUFFER, zeroCommand, GL15.GL_STATIC_DRAW); + + final FloatBuffer matBuf = BufferUtils.createFloatBuffer(16); + GLStateManager.glUseProgram(program); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + putMatrix(LEGACY_CAMERA, matBuf); + GLStateManager.glLoadMatrix(matBuf); + putMatrix(SENTINEL, matBuf); + GLStateManager.glUniformMatrix4(location, false, matBuf); + assertEquals(SENTINEL, readUniform(program, location), "sentinel upload did not take"); + } + + @AfterEach + void tearDown() { + GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0); + GLStateManager.glBindVertexArray(0); + GLStateManager.glUseProgram(0); + if (vao != 0) GLStateManager.glDeleteVertexArrays(vao); + if (indirectBuffer != 0) GLStateManager.glDeleteBuffers(indirectBuffer); + if (elementBuffer != 0) GLStateManager.glDeleteBuffers(elementBuffer); + GLStateManager.glDeleteProgram(program); + GLStateManager.glDeleteShader(vsh); + GLStateManager.glDeleteShader(fsh); + final FloatBuffer identity = BufferUtils.createFloatBuffer(16); + new Matrix4f().get(identity); + GLStateManager.glLoadMatrix(identity); + } + + @Test + void multiDrawIndirectDoesNotStompIrisMatrix() { + assumeTrue(RenderSystem.supportsMultiDrawIndirect(), "glMultiDrawElementsIndirect needs GL 4.3 / ARB_multi_draw_indirect; macOS core profile caps at 4.1"); + + GLStateManager.glMultiDrawElementsIndirect(GL11.GL_TRIANGLES, GL11.GL_UNSIGNED_INT, 0L, 1, 0); + assertEquals(SENTINEL, readUniform(program, location), "glMultiDrawElementsIndirect stomped iris_ModelViewMatrix from the legacy matrix stack; celeritas-managed programs own this uniform and the shadow pass renders with the camera view if it is overwritten"); + } + + @Test + void baseVertexDrawsDoNotStompIrisMatrixButRegularDrawDoes() { + GLStateManager.glDrawElementsBaseVertex(GL11.GL_TRIANGLES, 0, GL11.GL_UNSIGNED_INT, 0L, 0); + assertEquals(SENTINEL, readUniform(program, location), "glDrawElementsBaseVertex stomped iris_ModelViewMatrix; the Individual draw emitter renders shadows with the camera view if it is overwritten"); + + GLStateManager.glDrawRangeElementsBaseVertex(GL11.GL_TRIANGLES, 0, 0, 0, GL11.GL_UNSIGNED_INT, 0L, 0); + assertEquals(SENTINEL, readUniform(program, location), "glDrawRangeElementsBaseVertex stomped iris_ModelViewMatrix"); + + GLStateManager.glDrawElements(GL11.GL_TRIANGLES, 0, GL11.GL_UNSIGNED_INT, 0L); + final Matrix4f afterRegularDraw = readUniform(program, location); + assertNotEquals(SENTINEL, afterRegularDraw, "regular glDrawElements no longer refreshes compat uniforms; entity/hand programs rely on the legacy-stack upload"); + assertTrue(afterRegularDraw.equals(LEGACY_CAMERA, 1e-6f), "regular draw refreshed iris_ModelViewMatrix but not from the legacy modelview stack"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBufferTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBufferTest.java new file mode 100644 index 000000000..ed2c6449c --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaBufferTest.java @@ -0,0 +1,305 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SectionMetaBufferTest { + @Test + void slotLayout_originAndFencePosts() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] vo = { 100, 200, 300, 400, 500, 600, 700 }; + final int[] ec = { 12, 24, 36, 48, 60, 72, 84 }; + final int[] io = { 4, 16, 32, 64, 128, 256, 512 }; + final int sliceMaskLow = 0x7F; + final ByteBuffer src = SyntheticSectionData.row(sliceMaskLow, 0xDEADBEEF, vo, ec, io); + + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + + final int slot = meta.lookupSlot(0, 16, 32, 64); + assertEquals(0, slot, "first allocated slot should be 0"); + + final ByteBuffer mirror = meta.getMirrorForReadOnly(); + assertNotNull(mirror); + + assertEquals(16, mirror.getInt(0), "origin.x"); + assertEquals(32, mirror.getInt(4), "origin.y"); + assertEquals(64, mirror.getInt(8), "origin.z"); + assertEquals(sliceMaskLow, mirror.getInt(SectionMetaBuffer.OFFSET_SLICE_MASK), "origin.w (sliceMask low)"); + + for (int facing = 0; facing < 7; facing++) { + assertEquals(vo[facing], mirror.getInt(SectionMetaBuffer.OFFSET_POSTS + facing * 4), "post[" + facing + "] is facing " + facing + "'s first vertex"); + } + assertEquals(vo[6] + (ec[6] / 6) * 4, mirror.getInt(SectionMetaBuffer.OFFSET_POSTS + 7 * 4), "post[7] closes the last facing's vertex range"); + assertEquals(io[0] / 4, mirror.getInt(SectionMetaBuffer.OFFSET_FIRST_INDEX_BASE), "firstIndexBase is the section's index base in elements"); + } finally { + MemoryUtilities.memFree(src); + meta.shutdown(); + } + } + + @Test + void slotAllocation_isStablePerSection() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] vo = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] ec = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] io = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int firstSlot = meta.lookupSlot(0, 16, 32, 64); + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(firstSlot, meta.lookupSlot(0, 16, 32, 64), "slot must be stable across updates"); + + meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int otherSlot = meta.lookupSlot(0, 0, 0, 0); + assertEquals(firstSlot + 1, otherSlot, "fresh section -> next high-water slot"); + + meta.remove(0, 16, 32, 64, 0); + assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "removed slot should not resolve"); + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(firstSlot, meta.lookupSlot(0, 16, 32, 64), "free-list reuse should reclaim the slot"); + } finally { + MemoryUtilities.memFree(src); + meta.shutdown(); + } + } + + @Test + void localSectionIndex_unpacking() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] vo = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] ec = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] io = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io); + try { + final int x = 3, y = 2, z = 5; + final int localIdx = (x << 5) | (z << 2) | y; + meta.update(0, 0, 0, 0, localIdx, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final ByteBuffer mirror = meta.getMirrorForReadOnly(); + assertEquals(x << 4, mirror.getInt(0), "origin.x = sectionX << 4"); + assertEquals(y << 4, mirror.getInt(4), "origin.y = sectionY << 4"); + assertEquals(z << 4, mirror.getInt(8), "origin.z = sectionZ << 4"); + } finally { + MemoryUtilities.memFree(src); + meta.shutdown(); + } + } + + @Test + void distinctPasses_sameCoords_distinctSlots() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] voA = { 1000, 0, 0, 0, 0, 0, 0 }; + final int[] voB = { 2000, 0, 0, 0, 0, 0, 0 }; + final int[] ecA = { 100, 0, 0, 0, 0, 0, 0 }; + final int[] ecB = { 0, 0, 0, 0, 0, 0, 200 }; // different facing pattern + final int[] io = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer srcA = SyntheticSectionData.row(0x33, 0, voA, ecA, io); + final ByteBuffer srcB = SyntheticSectionData.row(0x40, 0, voB, ecB, io); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(srcA), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + meta.update(1, 16, 32, 64, 0, MemoryUtilities.memAddress(srcB), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int slotA = meta.lookupSlot(0, 16, 32, 64); + final int slotB = meta.lookupSlot(1, 16, 32, 64); + assertEquals(0, slotA, "pass 0 -> slot 0"); + assertEquals(1, slotB, "pass 1 -> slot 1, distinct from pass 0's slot"); + + final ByteBuffer mirror = meta.getMirrorForReadOnly(); + final int stride = SectionMetaBuffer.BYTES_PER_SECTION; + assertEquals(0x33, mirror.getInt(0 * stride + SectionMetaBuffer.OFFSET_SLICE_MASK), "slot 0 sliceMask comes from passA"); + assertEquals(0x40, mirror.getInt(1 * stride + SectionMetaBuffer.OFFSET_SLICE_MASK), "slot 1 sliceMask comes from passB"); + assertEquals(1000, mirror.getInt(0 * stride + SectionMetaBuffer.OFFSET_POSTS), "slot 0 post[0] from passA"); + assertEquals(2000, mirror.getInt(1 * stride + SectionMetaBuffer.OFFSET_POSTS), "slot 1 post[0] from passB"); + } finally { + MemoryUtilities.memFree(srcA); + MemoryUtilities.memFree(srcB); + meta.shutdown(); + } + } + + @Test + void update_returnsAllocatedSlot() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] vo = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] ec = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] io = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io); + try { + final int slotA = meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int slotB = meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(0, slotA, "first allocation -> slot 0"); + assertEquals(1, slotB, "second distinct section -> slot 1"); + assertEquals(slotA, meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "re-update returns the stable slot"); + assertEquals(-1, meta.update(0, 0, 0, 0, 0, 0L, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "null dataPtr -> -1"); + } finally { + MemoryUtilities.memFree(src); + meta.shutdown(); + } + } + + @Test + void syncIfDirty_positionsAndClearsDirty() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertTrue(meta.isDirty(), "dirty after update"); + final AtomicReference seen = new AtomicReference<>(); + final boolean ran = meta.syncIfDirty(b -> { seen.set(b); return true; }); + assertTrue(ran, "sink must run when dirty + non-empty"); + assertFalse(meta.isDirty(), "dirty cleared by syncIfDirty"); + assertNotNull(seen.get()); + assertEquals(0, seen.get().position(), "position is zeroed for sink"); + assertEquals(2 * SectionMetaBuffer.BYTES_PER_SECTION, seen.get().limit(), "limit is hwm * BYTES_PER_SECTION"); + assertEquals(0, seen.get().position(), "position is zero"); + assertFalse(meta.syncIfDirty(_ -> { throw new AssertionError("must not run"); }), "second call with no updates must short-circuit"); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void syncIfDirty_refusedSinkKeepsDataPending() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final AtomicInteger offers = new AtomicInteger(); + + assertFalse(meta.syncIfDirty(b -> { offers.incrementAndGet(); return false; }), "a refused sink reports no sync"); + assertTrue(meta.isDirty(), "refused data stays pending"); + + final AtomicReference seen = new AtomicReference<>(); + assertTrue(meta.syncIfDirty(b -> { offers.incrementAndGet(); seen.set(b); return true; }), "the same data is re-offered once the sink accepts"); + assertFalse(meta.isDirty(), "dirty clears only after the sink consumes"); + assertEquals(2, offers.get()); + assertEquals(SectionMetaBuffer.BYTES_PER_SECTION, seen.get().limit()); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void syncIfDirty_emptyMirrorStillClearsDirty() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + try { + assertFalse(meta.isDirty(), "fresh buffer is not dirty"); + assertFalse(meta.syncIfDirty(_ -> { throw new AssertionError("must not run"); }), "no updates -> false"); + } finally { + meta.reset(); + } + } + + @Test + void reset_isIdempotent() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + meta.reset(); + assertNull(meta.getMirrorForReadOnly(), "mirror gone after reset"); + assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "slot map cleared"); + meta.reset(); + meta.reset(); + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(0, meta.lookupSlot(0, 16, 32, 64), "reset is reusable, allocates fresh slot"); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void concurrent_updates_and_syncs_doNotCrash() throws InterruptedException { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] zeros = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, zeros, zeros, zeros); + final AtomicBoolean stop = new AtomicBoolean(false); + final AtomicReference error = new AtomicReference<>(); + final long srcAddr = MemoryUtilities.memAddress(src); + + final Thread writer = new Thread(() -> { + try { + int x = 0, y = 0, z = 0; + while (!stop.get()) { + meta.update(0, x << 4, y << 4, z << 4, 0, srcAddr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + x++; + if (x > 63) { x = 0; y++; } + if (y > 63) { y = 0; z++; } + if (z > 63) z = 0; + } + } catch (Throwable t) { error.set(t); } + }, "section-writer"); + + final Thread reader = new Thread(() -> { + try { + byte[] sink = new byte[1024 * 1024]; + while (!stop.get()) { + meta.syncIfDirty(b -> { + final int n = Math.min(b.remaining(), sink.length); + for (int i = 0; i < n; i++) sink[i] = b.get(i); + return true; + }); + } + } catch (Throwable t) { error.set(t); } + }, "section-reader"); + + writer.start(); + reader.start(); + Thread.sleep(2000); + stop.set(true); + writer.join(5000); + reader.join(5000); + + try { + if (error.get() != null) throw new AssertionError("worker crashed", error.get()); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void perPassRemove_leavesSiblingPasses() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final int[] vo = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] ec = { 0, 0, 0, 0, 0, 0, 0 }; + final int[] io = { 0, 0, 0, 0, 0, 0, 0 }; + final ByteBuffer src = SyntheticSectionData.row(0, 0, vo, ec, io); + try { + meta.update(0, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + meta.update(1, 16, 32, 64, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int slotA = meta.lookupSlot(0, 16, 32, 64); + final int slotB = meta.lookupSlot(1, 16, 32, 64); + + meta.remove(0, 16, 32, 64, 0); + assertEquals(-1, meta.lookupSlot(0, 16, 32, 64), "pass 0 slot must be gone"); + assertEquals(slotB, meta.lookupSlot(1, 16, 32, 64), "pass 1 slot must survive pass 0 removal"); + + meta.update(0, 0, 0, 0, 0, MemoryUtilities.memAddress(src), SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(slotA, meta.lookupSlot(0, 0, 0, 0), "free-list reuse claims pass 0's vacated slot"); + } finally { + MemoryUtilities.memFree(src); + meta.shutdown(); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaSlotLifecycleTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaSlotLifecycleTest.java new file mode 100644 index 000000000..9a8d0bdd3 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SectionMetaSlotLifecycleTest.java @@ -0,0 +1,109 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SectionMetaSlotLifecycleTest { + + @Test + void freedSlotsAreReusedInsteadOfGrowingTheHighWaterMark() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F); + final long ptr = MemoryUtilities.memAddress(src); + try { + for (int i = 0; i < 8; i++) meta.update(0, i * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(8, meta.getHighWaterMark()); + + for (int i = 0; i < 8; i++) meta.remove(0, i * 64, 0, 0, 0); + assertEquals(8, meta.getHighWaterMark(), "high-water mark is monotonic within a session"); + + for (int i = 0; i < 8; i++) meta.update(0, (100 + i) * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(8, meta.getHighWaterMark(), "eight fresh sections must reuse the eight freed slots"); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void everySlotIsDistinctWhileLive() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F); + final long ptr = MemoryUtilities.memAddress(src); + try { + final int a = meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int b = meta.update(0, 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertNotEquals(a, b); + + meta.remove(0, 0, 0, 0, 0); + final int c = meta.update(0, 128, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertEquals(a, c, "the freed slot is handed to the next section"); + assertNotEquals(b, c, "a live slot is never handed out twice"); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void resetReturnsTheBufferToEmpty() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F); + final long ptr = MemoryUtilities.memAddress(src); + try { + for (int i = 0; i < 5; i++) meta.update(0, i * 64, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertTrue(meta.getHighWaterMark() > 0); + + meta.reset(); + assertEquals(0, meta.getHighWaterMark()); + assertEquals(-1, meta.lookupSlot(0, 0, 0, 0), "slots do not survive a reset"); + + assertEquals(0, meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED), "allocation restarts from slot 0"); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void passesDoNotShareSlots() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + final ByteBuffer src = SyntheticSectionData.sliceMaskOnly(0x7F); + final long ptr = MemoryUtilities.memAddress(src); + try { + final int solid = meta.update(0, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int cutout = meta.update(1, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + final int translucent = meta.update(2, 0, 0, 0, 0, ptr, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED); + assertNotEquals(solid, cutout); + assertNotEquals(cutout, translucent); + assertEquals(3, meta.getHighWaterMark()); + + meta.remove(1, 0, 0, 0, 0); + assertEquals(-1, meta.lookupSlot(1, 0, 0, 0)); + assertEquals(solid, meta.lookupSlot(0, 0, 0, 0), "removing one pass leaves its siblings alone"); + assertEquals(translucent, meta.lookupSlot(2, 0, 0, 0)); + } finally { + MemoryUtilities.memFree(src); + meta.reset(); + } + } + + @Test + void aNullDataPointerAllocatesNothing() { + final SectionMetaBuffer meta = new SectionMetaBuffer(); + try { + assertEquals(-1, meta.update(0, 0, 0, 0, 0, 0L, SectionRenderDataUnsafe.Strategy.FULL, QuadPrimitiveType.TRIANGULATED)); + assertEquals(0, meta.getHighWaterMark()); + } finally { + meta.reset(); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/ShadowSnapshotBlitTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/ShadowSnapshotBlitTest.java new file mode 100644 index 000000000..7ad09ba39 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/ShadowSnapshotBlitTest.java @@ -0,0 +1,149 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@GLCoreTest +class ShadowSnapshotBlitTest { + + private static final int SIZE = 256; + private static final float FAR = 1.0f; + private static final float NEAR_PATCH = 0.25f; + + private static int newDepthTexture() { + final int tex = GLStateManager.glGenTextures(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, tex); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_DEPTH_COMPONENT, SIZE, SIZE, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (java.nio.ByteBuffer) null); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + return tex; + } + + private static int newDepthFbo(int tex) { + final int fbo = GLStateManager.glGenFramebuffers(); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo); + GLStateManager.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, tex, 0); + assertEquals(GL30.GL_FRAMEBUFFER_COMPLETE, GLStateManager.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER), "depth-only FBO incomplete"); + return fbo; + } + + private static void fillPattern(int fbo) { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo); + GLStateManager.glDepthMask(true); + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + GLStateManager.glClearDepth(FAR); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); + GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + GLStateManager.glScissor(0, 0, SIZE / 2, SIZE / 2); + GLStateManager.glClearDepth(NEAR_PATCH); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + } + + private static float readDepth(int fbo, int x, int y) { + GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fbo); + final FloatBuffer buf = BufferUtils.createFloatBuffer(1); + GLStateManager.glReadPixels(x, y, 1, 1, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, buf); + return buf.get(0); + } + + @Test + void depthSnapshotRoundTripsThroughBlit() { + final int srcTex = newDepthTexture(); + final int srcFbo = newDepthFbo(srcTex); + final int cacheTex = newDepthTexture(); + final int cacheFbo = newDepthFbo(cacheTex); + try { + fillPattern(srcFbo); + assertEquals(NEAR_PATCH, readDepth(srcFbo, 10, 10), 1e-4f, "source pattern not written"); + assertEquals(FAR, readDepth(srcFbo, SIZE - 10, SIZE - 10), 1e-4f, "source background not written"); + + RenderSystem.blitFramebuffer(srcFbo, cacheFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + assertEquals(NEAR_PATCH, readDepth(cacheFbo, 10, 10), 1e-4f, "capture blit did not copy the near patch into the cache"); + assertEquals(FAR, readDepth(cacheFbo, SIZE - 10, SIZE - 10), 1e-4f, "capture blit did not copy the far background into the cache"); + + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, srcFbo); + GLStateManager.glDepthMask(true); + GLStateManager.glClearDepth(FAR); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); + assertEquals(FAR, readDepth(srcFbo, 10, 10), 1e-4f, "source not cleared before restore"); + + RenderSystem.blitFramebuffer(cacheFbo, srcFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + assertEquals(NEAR_PATCH, readDepth(srcFbo, 10, 10), 1e-4f, "restore blit did not bring the near patch back"); + assertEquals(FAR, readDepth(srcFbo, SIZE - 10, SIZE - 10), 1e-4f, "restore blit corrupted the far background"); + } finally { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDeleteFramebuffers(srcFbo); + GLStateManager.glDeleteFramebuffers(cacheFbo); + GLStateManager.glDeleteTextures(srcTex); + GLStateManager.glDeleteTextures(cacheTex); + } + } + + @Test + void depthBlitIsNotAffectedByScissorState() { + final int srcTex = newDepthTexture(); + final int srcFbo = newDepthFbo(srcTex); + final int cacheTex = newDepthTexture(); + final int cacheFbo = newDepthFbo(cacheTex); + try { + fillPattern(srcFbo); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, cacheFbo); + GLStateManager.glClearDepth(FAR); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); + + GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + GLStateManager.glScissor(0, 0, 4, 4); + RenderSystem.blitFramebuffer(srcFbo, cacheFbo, 0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + + assertEquals(NEAR_PATCH, readDepth(cacheFbo, 100, 100), 1e-4f, "scissor clipped the snapshot blit; the cache only received the scissor box"); + } finally { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDeleteFramebuffers(srcFbo); + GLStateManager.glDeleteFramebuffers(cacheFbo); + GLStateManager.glDeleteTextures(srcTex); + GLStateManager.glDeleteTextures(cacheTex); + } + } + + @Test + void rawBlitStaysScissorClipped() { + final int srcTex = newDepthTexture(); + final int srcFbo = newDepthFbo(srcTex); + final int cacheTex = newDepthTexture(); + final int cacheFbo = newDepthFbo(cacheTex); + try { + fillPattern(srcFbo); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, cacheFbo); + GLStateManager.glClearDepth(FAR); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); + + GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, srcFbo); + GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, cacheFbo); + GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + GLStateManager.glScissor(0, 0, 4, 4); + GLStateManager.glBlitFramebuffer(0, 0, SIZE, SIZE, 0, 0, SIZE, SIZE, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + + assertEquals(NEAR_PATCH, readDepth(cacheFbo, 1, 1), 1e-4f, "raw blit copied nothing inside the scissor box"); + assertEquals(FAR, readDepth(cacheFbo, 100, 100), 1e-4f, "raw glBlitFramebuffer ignored scissor"); + } finally { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDeleteFramebuffers(srcFbo); + GLStateManager.glDeleteFramebuffers(cacheFbo); + GLStateManager.glDeleteTextures(srcTex); + GLStateManager.glDeleteTextures(cacheTex); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SyntheticSectionData.java b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SyntheticSectionData.java new file mode 100644 index 000000000..e6b8adaa4 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/culling/SyntheticSectionData.java @@ -0,0 +1,39 @@ +package com.gtnewhorizons.angelica.rendering.culling; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** Off-heap SectionRenderData rows in the FULL layout. Callers own the buffer and must memFree it. */ +final class SyntheticSectionData { + + private static final int BYTES = 92; + private static final int FACINGS = 7; + private static final int[] ZEROS = new int[FACINGS]; + + private SyntheticSectionData() {} + + static ByteBuffer row(int sliceMaskLow, int sliceMaskHigh, int[] vertexOffsets, int[] elementCounts, int[] indexOffsets) { + final ByteBuffer buf = MemoryUtilities.memAlloc(BYTES).order(ByteOrder.nativeOrder()); + buf.putInt(0, sliceMaskLow); + buf.putInt(4, sliceMaskHigh); + for (int facing = 0; facing < FACINGS; facing++) { + final int off = 8 + facing * 12; + buf.putInt(off + 0, vertexOffsets[facing]); + buf.putInt(off + 4, elementCounts[facing]); + buf.putInt(off + 8, indexOffsets[facing]); + } + return buf; + } + + static ByteBuffer sliceMaskOnly(int sliceMask) { + return row(sliceMask, 0, ZEROS, ZEROS, ZEROS); + } + + static ByteBuffer singleQuadOnFacing0() { + final int[] vertexOffsets = { 0, 4, 4, 4, 4, 4, 4 }; + final int[] elementCounts = { 6, 0, 0, 0, 0, 0, 0 }; + return row(0x01, 0, vertexOffsets, elementCounts, ZEROS); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCacheTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCacheTest.java new file mode 100644 index 000000000..8386a90f5 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCacheTest.java @@ -0,0 +1,122 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache.MeshBackend; +import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.LongSupplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AngelicaTesrMeshCacheTest { + + private static final ResourceLocation TEX_A = new ResourceLocation("angelica", "test_a"); + private static final ResourceLocation TEX_B = new ResourceLocation("angelica", "test_b"); + + private final long[] now = { 1_000L }; + private final LongSupplier clock = () -> now[0]; + private final FakeBackend backend = new FakeBackend(); + private final RecordingReplay replay = new RecordingReplay(); + private final AngelicaTesrMeshCache cache = new AngelicaTesrMeshCache(backend, clock, replay); + private final Object key = new Object(); + + @Test + void firstFrameCapturesAndReplays() { + cache.renderCached(key, sink -> sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A)); + + assertEquals(1, backend.beginCaptures); + assertTrue(cache.hasEntry(key)); + assertEquals(1, cache.version(key)); + assertEquals(1, replay.calls.size()); + assertSame(TEX_A, replay.calls.get(0).texture); + } + + @Test + void cleanFrameReplaysWithoutRecapture() { + cache.renderCached(key, this::oneBucket); + cache.renderCached(key, sink -> { throw new AssertionError("builder must not run on a clean frame"); }); + + assertEquals(1, backend.beginCaptures); + assertEquals(1, cache.version(key)); + assertEquals(2, replay.calls.size()); + } + + @Test + void invalidateForcesRecapture() { + cache.renderCached(key, this::oneBucket); + cache.invalidate(key); + assertFalse(cache.hasEntry(key)); + + cache.renderCached(key, this::oneBucket); + assertEquals(2, backend.beginCaptures); + } + + @Test + void lruEvicts() { + cache.renderCached(key, this::oneBucket); + + now[0] = 1_000L + AngelicaTesrMeshCache.LRU_TIMEOUT_MS; // boundary -> retained + cache.tick(); + assertTrue(cache.hasEntry(key)); + + now[0] = 1_000L + AngelicaTesrMeshCache.LRU_TIMEOUT_MS + 1; // past timeout -> evicted + cache.tick(); + assertFalse(cache.hasEntry(key)); + } + + @Test + void multiBucketOrderAndMaterialPassthrough() { + final TesrMaterial material = TesrMaterial.builder().color(0.25f, 0.5f, 0.75f, 1f).build(); + cache.renderCached(key, sink -> { + sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A); + sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_B, material); + }); + + assertEquals(2, replay.calls.size()); + assertSame(TEX_A, replay.calls.get(0).texture); + assertSame(TesrMaterial.CURRENT_STATE, replay.calls.get(0).material); + assertSame(TEX_B, replay.calls.get(1).texture); + assertSame(material, replay.calls.get(1).material); + } + + private void oneBucket(TesrMeshSink sink) { + sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TEX_A); + } + + private static final class FakeBackend implements MeshBackend { + int beginCaptures; + + @Override + public Tessellator beginCapture(VertexFormat format) { + beginCaptures++; + return null; + } + + @Override + public TemplateBuffer endCaptureToTemplate() { + return new TemplateBuffer(new int[8], 1, 7); + } + } + + private record Recorded(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {} + + private static final class RecordingReplay implements AngelicaTesrMeshCache.ReplaySink { + final List calls = new ArrayList<>(); + + @Override + public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) { + calls.add(new Recorded(template, texture, material)); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java new file mode 100644 index 000000000..173585aa5 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java @@ -0,0 +1,74 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class EntityMaterialsTest { + + private static final int SA = GL11.GL_SRC_ALPHA; + private static final int OMSA = GL11.GL_ONE_MINUS_SRC_ALPHA; + + @Test + void mainModelStateMapsToCutout() { + assertSame(EntityMaterials.CUTOUT, EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true)); + } + + @Test + void shadowPassHalfAlphaRefMapsToCutoutHalf() { + assertSame(EntityMaterials.CUTOUT_HALF, EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.5f, GL11.GL_LEQUAL, true)); + } + + @Test + void noAlphaNoBlendMapsToSolid() { + assertSame(EntityMaterials.SOLID, EntityMaterials.fromState(true, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true)); + } + + @Test + void invisibilityMapsToTranslucent() { + assertSame(EntityMaterials.TRANSLUCENT, EntityMaterials.fromState(true, true, SA, OMSA, true, GL11.GL_GREATER, 0.0039f, GL11.GL_LEQUAL, false)); + assertSame(EntityMaterials.TRANSLUCENT_DEPTH_WRITE, EntityMaterials.fromState(true, true, SA, OMSA, true, GL11.GL_GREATER, 0.0039f, GL11.GL_LEQUAL, true)); + } + + @Test + void eyesMapToAdditive() { + assertSame(EntityMaterials.ADDITIVE, EntityMaterials.fromState(true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.ADDITIVE_NO_DEPTH_WRITE, EntityMaterials.fromState(true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false)); + } + + @Test + void hurtOverlayMapsToOverlay() { + assertSame(EntityMaterials.OVERLAY, EntityMaterials.fromState(false, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, true)); + } + + @Test + void glintStateMapsToGlintOnlyWhenTexAnimated() { + assertSame(EntityMaterials.GLINT, EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false)); + assertNull(EntityMaterials.fromState(true, false, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false), () -> "glint blend without texture animation must stay live"); + assertNull(EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, true), () -> "glint blend with depth write is not vanilla glint"); + } + + @Test + void texAnimatedAdditiveVariantsMap() { + assertSame(EntityMaterials.ADDITIVE, EntityMaterials.fromState(true, true, true, GL11.GL_ONE, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.ADDITIVE_ALPHA_NO_DEPTH_WRITE, EntityMaterials.fromState(true, true, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false)); + assertNull(EntityMaterials.fromState(true, true, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "animated standard-alpha (scrolling translucent) must stay live"); + assertNull(EntityMaterials.fromState(true, true, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "animated without blend must stay live"); + } + + @Test + void additiveAlphaMapsWithoutAnimation() { + assertSame(EntityMaterials.ADDITIVE_ALPHA, EntityMaterials.fromState(true, false, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.ADDITIVE_ALPHA_NO_DEPTH_WRITE, EntityMaterials.fromState(true, false, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false)); + } + + @Test + void unrecognizedStatesFallBackToLive() { + assertNull(EntityMaterials.fromState(true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, false), () -> "glint blend at EQUAL must stay live"); + assertNull(EntityMaterials.fromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.3f, GL11.GL_LEQUAL, true), () -> "nonstandard alpha ref must stay live"); + assertNull(EntityMaterials.fromState(false, false, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, true), () -> "texture off without overlay signature must stay live"); + assertNull(EntityMaterials.fromState(true, true, SA, OMSA, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, true), () -> "textured EQUAL-depth re-render must stay live"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java new file mode 100644 index 000000000..90a93a545 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java @@ -0,0 +1,315 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.BatchVertexFormats; +import net.coderbot.batchedentityrendering.impl.BufferSegment; +import net.coderbot.batchedentityrendering.impl.BufferSourceProbe; +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import java.util.List; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RetainedTesrGroupsTest { + + private static final class TestLayer extends RenderLayer { + TestLayer() { + super("test", BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 256, () -> {}, () -> {}); + } + } + + @Test + void retainedGroupAccumulatesInsteadOfStreaming() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false); + + assertTrue(groups.hasDraws(layer)); + assertEquals(0, groups.streamedInstances); + final List order = BufferSourceProbe.prepare(source); + assertTrue(order.contains(layer), "declareUse must register the layer"); + assertNull(BufferSourceProbe.segmentsFor(source, layer), "retained instances must not produce dynamic segments"); + } + + @Test + void streamingGroupStreamsIntoDynamicSegments() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + + groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); + assertEquals(1, groups.streamPromotions); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(4f, 5f, 6f), 0, -1, 5, null, false); + + assertFalse(groups.hasDraws(layer), "volatile group must not report retained draws"); + assertEquals(2, groups.streamedInstances); + + BufferSourceProbe.prepare(source); + final List segments = BufferSourceProbe.segmentsFor(source, layer); + assertEquals(1, segments.size()); + assertEquals(8, segments.get(0).getVertexCount(), "both instances stream into one segment"); + assertEquals(5, segments.get(0).getBlockEntityId()); + } + + @Test + void stableTransformsDemoteStreamingGroup() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TemplateBuffer template = template(); + final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); + + groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); + long streamedFrames = 0; + for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, fixed, 0, -1, 5, null, false); + if (groups.hasDraws(layer)) break; + streamedFrames++; + } + + assertTrue(groups.hasDraws(layer), "identical frames must demote the group back to retained"); + assertTrue(streamedFrames >= RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES, "demotion must wait for the stability window, streamed " + streamedFrames); + } + + @Test + void movingTransformsStayStreaming() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TemplateBuffer template = template(); + + groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); + for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(frame, 0f, 0f), 0, -1, 5, null, false); + assertFalse(groups.hasDraws(layer), "moving group must keep streaming at frame " + frame); + } + } + + @Test + void idleGapResetsVolatility() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + + groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); + for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + } + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false); + + assertTrue(groups.hasDraws(layer), "idle reset must demote the group back to retained"); + assertEquals(0, groups.streamedInstances); + } + + @Test + void translucentStreamingGroupNeverDemotes() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial translucent = TesrMaterial.builder().translucent().build(); + final TemplateBuffer template = template(); + final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); + + groups.forceStreaming(layer, translucent, 5); + final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; + for (int frame = 0; frame < frames; frame++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, translucent, fixed, 0, -1, 5, null, false); + assertFalse(groups.hasDraws(layer), "translucent group must keep streaming at frame " + frame); + } + assertEquals(frames, groups.streamedInstances); + } + + @Test + void streamMaterialStreamsFromFirstQueue() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); + + assertFalse(groups.hasDraws(layer), "stream group must not report retained draws"); + assertEquals(1, groups.streamedInstances); + assertEquals(0, groups.streamPromotions, "streaming from birth is not a promotion"); + + BufferSourceProbe.prepare(source); + final List segments = BufferSourceProbe.segmentsFor(source, layer); + assertEquals(1, segments.size()); + assertEquals(5, segments.get(0).getBlockEntityId()); + } + + @Test + void streamGroupNeverDemotesUnderStableTransforms() { + for (final TesrMaterial material : new TesrMaterial[] { + TesrMaterial.builder().stream().build(), + TesrMaterial.builder().translucent().stream().build()}) { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TemplateBuffer template = template(); + final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); + + final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; + for (int frame = 0; frame < frames; frame++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, material, fixed, 0, -1, 5, null, false); + assertFalse(groups.hasDraws(layer), material.transparency() + " stream group must keep streaming at frame " + frame); + } + assertEquals(frames, groups.streamedInstances); + } + } + + @Test + void idleGapKeepsStreamGroupStreaming() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false); + for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) { + groups.beginPass(new Matrix4f(), 0, 0, 0); + } + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false); + + assertFalse(groups.hasDraws(layer), "idle reset must not move a stream group to retained"); + assertEquals(2, groups.streamedInstances); + } + + @Test + void streamGroupRoutesToInstanceArraysWhenInstancedCapable() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); + groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); + + assertTrue(groups.hasDraws(layer), "instanced-capable stream group accumulates for the hook draw"); + assertEquals(0, groups.streamedInstances, "no segment streaming when instanced"); + BufferSourceProbe.prepare(source); + assertNull(BufferSourceProbe.segmentsFor(source, layer)); + } + + @Test + void forceStreamSkipsInstanceArraysEvenWhenInstancedCapable() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); + groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, true); + + assertFalse(groups.hasDraws(layer), "forceStream instance must not enter the instance arrays"); + assertEquals(1, groups.streamedInstances); + } + + @Test + void streamGroupTexMatrixFallsBackToSegmentStream() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, new Matrix4f().translation(0.5f, 0.5f, 0f), false); + + assertFalse(groups.hasDraws(layer), "texMatrix instance must not enter the instance arrays"); + assertEquals(1, groups.streamedInstances); + } + + @Test + void streamGroupDrawModeMismatchFallsBackToRetained() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + final int[] data = new int[3 * VERTEX_SIZE]; + final TemplateBuffer triangles = new TemplateBuffer(data, 3, GL11.GL_TRIANGLES); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(triangles, layer, stream, new Matrix4f(), 0, -1, 5, null, false); + + assertTrue(groups.hasDraws(layer), "mismatched drawMode must fall back to retained accumulation"); + assertEquals(0, groups.streamedInstances); + } + + @Test + void sweepEvictsIdleGroupsAndKeepsLive() { + final long[] clock = {1_000L}; + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source, () -> clock[0]); + final TestLayer layer = new TestLayer(); + final TemplateBuffer template = template(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + assertEquals(2, groups.groupCount()); + + clock[0] += RetainedTesrGroups.GROUP_TTL_MS + 1; + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + groups.sweep(clock[0]); + + assertEquals(1, groups.groupCount(), "idle group must be evicted, live group kept"); + assertTrue(groups.hasDraws(layer), "live group still draws this frame"); + + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + assertEquals(2, groups.groupCount(), "evicted id must be re-creatable"); + } + + @Test + void clearEmptiesAllGroups() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RetainedTesrGroups groups = new RetainedTesrGroups(source); + final TestLayer layer = new TestLayer(); + final TemplateBuffer template = template(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + groups.clear(); + + assertEquals(0, groups.groupCount()); + assertFalse(groups.hasDraws(layer)); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + assertEquals(1, groups.groupCount()); + assertTrue(groups.hasDraws(layer)); + } + + private static TemplateBuffer template() { + final int[] data = new int[4 * VERTEX_SIZE]; + for (int v = 0; v < 4; v++) { + final int base = v * VERTEX_SIZE; + data[base + X_INDEX] = Float.floatToRawIntBits(v); + data[base + COLOR_INDEX] = 0xFFFFFFFF; + } + return new TemplateBuffer(data, 4, GL11.GL_QUADS); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMathTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMathTest.java new file mode 100644 index 000000000..bd9e72ec8 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrAnchorMathTest.java @@ -0,0 +1,100 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TesrAnchorMathTest { + + private static final double TE_X = 123456.25, TE_Y = 64.0, TE_Z = -98765.75; + + private static Matrix4f cameraRelative(double camX, double camY, double camZ) { + return new Matrix4f().translation((float) (TE_X - camX), (float) (TE_Y - camY), (float) (TE_Z - camZ)); + } + + private static Matrix4f anchorRelative(double camX, double camY, double camZ, long ax, long ay, long az) { + final Matrix4f m = cameraRelative(camX, camY, camZ); + TesrAnchorMath.toAnchorRelative(m, camX, camY, camZ, ax, ay, az); + return m; + } + + @Test + void anchorCoordRoundsDownToGrid() { + assertEquals(96, TesrAnchorMath.anchorCoord(100.5)); + assertEquals(112, TesrAnchorMath.anchorCoord(112.0)); + assertEquals(-16, TesrAnchorMath.anchorCoord(-0.5)); + assertEquals(-32, TesrAnchorMath.anchorCoord(-16.5)); + } + + @Test + void shouldReanchorTriggersOnlyBeyondThreshold() { + assertFalse(TesrAnchorMath.shouldReanchor(100, 0, 0, 0, 0, 0)); + assertFalse(TesrAnchorMath.shouldReanchor(511, 0, 0, 0, 0, 0)); + assertTrue(TesrAnchorMath.shouldReanchor(513, 0, 0, 0, 0, 0)); + assertTrue(TesrAnchorMath.shouldReanchor(300, 300, 300, 0, 0, 0)); + } + + @Test + void anchorRelativeTranslationReconstructsWorldOffset() { + final double camX = TE_X - 30.5, camY = TE_Y + 5.0, camZ = TE_Z + 12.25; + final long ax = TesrAnchorMath.anchorCoord(camX); + final long ay = TesrAnchorMath.anchorCoord(camY); + final long az = TesrAnchorMath.anchorCoord(camZ); + final Matrix4f mA = anchorRelative(camX, camY, camZ, ax, ay, az); + assertEquals(TE_X - ax, mA.m30(), 1e-2f); + assertEquals(TE_Y - ay, mA.m31(), 1e-2f); + assertEquals(TE_Z - az, mA.m32(), 1e-2f); + } + + @Test + void hashIsInvariantUnderCameraMotion() { + final double camAX = TE_X - 20.0, camAY = TE_Y - 3.0, camAZ = TE_Z + 8.0; + final long ax = TesrAnchorMath.anchorCoord(camAX); + final long ay = TesrAnchorMath.anchorCoord(camAY); + final long az = TesrAnchorMath.anchorCoord(camAZ); + + final Matrix4f mA = anchorRelative(camAX, camAY, camAZ, ax, ay, az); + final long h1 = TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, -1); + + final double camBX = camAX + 137.37, camBY = camAY + 41.03, camBZ = camAZ - 250.91; + final Matrix4f mB = anchorRelative(camBX, camBY, camBZ, ax, ay, az); + final long h2 = TesrAnchorMath.instanceHash(42, mB, 0x00F000F0, -1); + + assertEquals(h1, h2, "camera-only motion must not change the rebuild hash"); + } + + @Test + void reanchorRoundTripKeepsWorldPosition() { + final double camX = TE_X - 20.0, camY = TE_Y, camZ = TE_Z + 20.0; + final long ax1 = TesrAnchorMath.anchorCoord(camX); + final long ax2 = ax1 + 480; + final Matrix4f m1 = anchorRelative(camX, camY, camZ, ax1, 0, 0); + final Matrix4f m2 = anchorRelative(camX, camY, camZ, ax2, 0, 0); + assertEquals(ax1 + m1.m30(), ax2 + m2.m30(), 1e-2); + } + + @Test + void hashChangesOnRealDifferences() { + final Matrix4f mA = new Matrix4f().translation(1.5f, 2.5f, 3.5f); + final long base = TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, -1); + assertNotEquals(base, TesrAnchorMath.instanceHash(43, mA, 0x00F000F0, -1), "template identity"); + assertNotEquals(base, TesrAnchorMath.instanceHash(42, mA, 0x00F000A0, -1), "packed light"); + assertNotEquals(base, TesrAnchorMath.instanceHash(42, mA, 0x00F000F0, 0xFF0000FF), "color"); + final Matrix4f moved = new Matrix4f(mA).translate(1f, 0f, 0f); + assertNotEquals(base, TesrAnchorMath.instanceHash(42, moved, 0x00F000F0, -1), "transform"); + } + + @Test + void summedHashIsOrderIndependent() { + final Matrix4f m1 = new Matrix4f().translation(1f, 2f, 3f); + final Matrix4f m2 = new Matrix4f().translation(-4f, 5f, -6f).rotateY(0.5f); + final long a = TesrAnchorMath.instanceHash(1, m1, 10, -1); + final long b = TesrAnchorMath.instanceHash(2, m2, 20, -1); + assertEquals(a + b, b + a); + assertNotEquals(a, b); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java new file mode 100644 index 000000000..82b78a033 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java @@ -0,0 +1,61 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.api.tesr.TesrShader; +import com.gtnewhorizons.angelica.api.tesr.TesrShaders; +import net.minecraft.util.ResourceLocation; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +class TesrLayerKeyTest { + + private static final ResourceLocation TEX = new ResourceLocation("angelica", "textures/test.png"); + private static final TesrShader SHADER = TesrShaders.register("test:layer_key", () -> {}, () -> {}); + private static final TesrMaterial.SpecialRender NONE = TesrMaterial.SpecialRender.NONE; + + @Test + void scratchProbeMatchesCopiedKey() { + final TesrBatchRenderer.LayerKey scratch = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false); + final TesrBatchRenderer.LayerKey stored = scratch.copy(); + assertNotSame(scratch, stored); + assertEquals(scratch, stored); + assertEquals(scratch.hashCode(), stored.hashCode()); + + scratch.set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false); + assertEquals(stored, scratch, "re-set scratch still matches stored copy"); + } + + @Test + void fieldChangesBreakEquality() { + final TesrBatchRenderer.LayerKey base = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false); + final TesrBatchRenderer.LayerKey other = base.copy(); + + other.set(null, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.TRANSLUCENT, false, false, false, false, 0f, false, NONE, null, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0.5f, false, NONE, null, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, true, 0f, false, NONE, null, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, TesrMaterial.SpecialRender.GLINT, null, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, SHADER, false); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, true); + assertNotEquals(base, other); + + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false); + assertEquals(base, other); + } + + @Test + void nullTextureAndShaderHash() { + final TesrBatchRenderer.LayerKey key = new TesrBatchRenderer.LayerKey().set(null, null, false, false, false, false, 0f, false, null, null, false); + assertEquals(key, key.copy()); + assertEquals(key.hashCode(), key.copy().hashCode()); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatchTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatchTest.java new file mode 100644 index 000000000..fadcf89e2 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrProviderDispatchTest.java @@ -0,0 +1,34 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider; +import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; +import net.minecraft.tileentity.TileEntity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class TesrProviderDispatchTest { + + private static final class FakeProvider implements TesrMeshProvider { + private final Object key; + FakeProvider(Object key) { this.key = key; } + @Override public Object angelica$meshKey(TileEntity te) { return key; } + @Override public void angelica$build(TesrMeshSink sink, TileEntity te) {} + } + + @Test + void nonProviderIsNotHandled() { + assertFalse(TesrProviderDispatch.tryRender(new Object(), null, 0, 0, 0)); + } + + @Test + void nullMeshKeyFallsBackToNormalRender() { + assertFalse(TesrProviderDispatch.tryRender(new FakeProvider(null), null, 0, 0, 0)); + } + + @Test + void nullTileEntityResolvesToZeroBlockEntityId() { + assertEquals(0, TesrProviderDispatch.resolveBlockEntityId(null)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransformTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransformTest.java new file mode 100644 index 000000000..749d02577 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/VertexTransformTest.java @@ -0,0 +1,149 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import net.coderbot.batchedentityrendering.impl.BatchVertexFormats; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class VertexTransformTest { + + private static final float NORM_EPS = 1.5f / 127f; + private static final VertexFormat DEST = BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL; + private static final int OFF_POS = 0, OFF_COLOR = 12, OFF_TEX = 16, OFF_LIGHT = 24, OFF_NORMAL = 32; + + private static int[] oneVertexUp() { + final int[] data = new int[VERTEX_SIZE]; + data[COLOR_INDEX] = 0xFFFFFFFF; + data[X_INDEX] = Float.floatToRawIntBits(0f); + data[Y_INDEX] = Float.floatToRawIntBits(1f); + data[Z_INDEX] = Float.floatToRawIntBits(0f); + data[TEX_X_INDEX] = Float.floatToRawIntBits(0.25f); + data[TEX_Y_INDEX] = Float.floatToRawIntBits(0.75f); + data[NORMAL_INDEX] = NormI8.pack(0f, 1f, 0f); + return data; + } + + private static TemplateBuffer template(int[] data) { + return new TemplateBuffer(data, 1, 7); + } + + @Test + void writeInstanceTranslatesPositionSetsColorLightKeepsUv() { + final TemplateBuffer template = template(oneVertexUp()); + final Matrix4f mv = new Matrix4f().translation(10f, -2f, 3f); + final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize()); + final long addr = memAddress0(dest); + + VertexTransform.writeInstance(addr, DEST, template, mv, new Vector3f(), 0xFF8040C0, 0x00F000F0, null); + + assertEquals(10f, memGetFloat(addr + OFF_POS), 1e-6f); + assertEquals(-1f, memGetFloat(addr + OFF_POS + 4), 1e-6f); + assertEquals(3f, memGetFloat(addr + OFF_POS + 8), 1e-6f); + assertEquals(0xFF8040C0, memGetInt(addr + OFF_COLOR)); + assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 0f); + assertEquals(0.75f, memGetFloat(addr + OFF_TEX + 4), 0f); + assertEquals(240f, memGetFloat(addr + OFF_LIGHT), 0f); // 0x00F0 + assertEquals(240f, memGetFloat(addr + OFF_LIGHT + 4), 0f); // 0x00F0 + final int n = memGetInt(addr + OFF_NORMAL); + assertEquals(0f, NormI8.unpackX(n), NORM_EPS); + assertEquals(1f, NormI8.unpackY(n), NORM_EPS); + assertEquals(0f, NormI8.unpackZ(n), NORM_EPS); + } + + @Test + void writeInstanceRotatesNormal() { + final TemplateBuffer template = template(oneVertexUp()); + final Matrix4f mv = new Matrix4f().rotationX((float) Math.toRadians(90)); + final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize()); + final long addr = memAddress0(dest); + + VertexTransform.writeInstance(addr, DEST, template, mv, new Vector3f(), 0, 0, null); + + final int n = memGetInt(addr + OFF_NORMAL); + assertEquals(0f, NormI8.unpackX(n), NORM_EPS); + assertEquals(0f, NormI8.unpackY(n), NORM_EPS); + assertEquals(1f, NormI8.unpackZ(n), NORM_EPS); + } + + @Test + void writeInstanceModulatesBakedColorAndPreservesTemplate() { + final int[] data = oneVertexUp(); + data[COLOR_INDEX] = 0xFF0080FF; // ABGR: a=255 b=0 g=128 r=255 + final TemplateBuffer template = template(data); + final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize()); + final long addr = memAddress0(dest); + + VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), 0x80FFFFFF, 0, null); + assertEquals(0x800080FF, memGetInt(addr + OFF_COLOR)); + + VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, null); + assertEquals(0xFF0080FF, memGetInt(addr + OFF_COLOR)); + } + + @Test + void mulColorIsExactForWhiteAndRounds() { + assertEquals(0x12345678, VertexTransform.mulColor(0x12345678, 0xFFFFFFFF)); + assertEquals(0x12345678, VertexTransform.mulColor(0xFFFFFFFF, 0x12345678)); + assertEquals(0x80, VertexTransform.mulColor(0xFF, 0x80)); + assertEquals(0x00, VertexTransform.mulColor(0x7F, 0x00)); + } + + @Test + void writeInstanceAppliesTextureMatrixToUvThenRestores() { + final TemplateBuffer template = template(oneVertexUp()); + final ByteBuffer dest = ByteBuffer.allocateDirect(DEST.getVertexSize()); + final long addr = memAddress0(dest); + final Matrix4f texMatrix = new Matrix4f().translation(0f, 0.1f, 0f).scale(1f, 0.5f, 1f); + + VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, texMatrix); + assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 1e-6f); + assertEquals(0.75f * 0.5f + 0.1f, memGetFloat(addr + OFF_TEX + 4), 1e-6f); + + VertexTransform.writeInstance(addr, DEST, template, new Matrix4f(), new Vector3f(), -1, 0, null); + assertEquals(0.25f, memGetFloat(addr + OFF_TEX), 0f); + assertEquals(0.75f, memGetFloat(addr + OFF_TEX + 4), 0f); + } + + @Test + void decodeReadsPositionUvNormalByUsage() { + final VertexFormat src = DefaultVertexFormat.POSITION_TEXTURE_NORMAL; + final ByteBuffer buf = ByteBuffer.allocateDirect(src.getVertexSize()); + final long addr = memAddress0(buf); + memPutFloat(addr, 5f); + memPutFloat(addr + 4, 6f); + memPutFloat(addr + 8, 7f); + memPutFloat(addr + 12, 0.1f); + memPutFloat(addr + 16, 0.2f); + memPutInt(addr + 20, NormI8.pack(1f, 0f, 0f)); + + final int[] out = VertexTransform.decode(addr, src, 1); + + assertEquals(5f, Float.intBitsToFloat(out[X_INDEX]), 0f); + assertEquals(6f, Float.intBitsToFloat(out[Y_INDEX]), 0f); + assertEquals(7f, Float.intBitsToFloat(out[Z_INDEX]), 0f); + assertEquals(0.1f, Float.intBitsToFloat(out[TEX_X_INDEX]), 0f); + assertEquals(0.2f, Float.intBitsToFloat(out[TEX_Y_INDEX]), 0f); + assertEquals(1f, NormI8.unpackX(out[NORMAL_INDEX]), NORM_EPS); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizerTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizerTest.java new file mode 100644 index 000000000..4b22cc6e7 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/voxelization/ShadowVoxelizerTest.java @@ -0,0 +1,368 @@ +package com.gtnewhorizons.angelica.rendering.voxelization; + +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; +import com.gtnewhorizons.angelica.config.GpuCullingMode; +import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; +import org.embeddedt.embeddium.impl.gl.util.VertexRange; +import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; +import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; +import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; +import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; +import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; +import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType; +import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ShadowVoxelizerTest { + + private static final ChunkPrimitiveType PRIMITIVE = QuadPrimitiveType.TRIANGULATED; + + private static class RecordingSink implements ShadowVoxelizer.Sink { + final List regions = new ArrayList<>(); + final List ranges = new ArrayList<>(); + int finishes; + boolean refuseRegion; + boolean refuseRange; + + @Override + public boolean region(RenderRegion region, GlVertexFormat format, float x, float y, float z) { + if (refuseRegion) return false; + regions.add(new float[]{x, y, z}); + return true; + } + + @Override + public boolean range(int vertexOffset, int vertexCount) { + if (refuseRange) return false; + ranges.add(new int[]{vertexOffset, vertexCount}); + return true; + } + + @Override + public void finish() { + finishes++; + } + } + + private static final ChunkVertexType VERTEX_TYPE = new ChunkVertexType() { + @Override public float getPositionScale() { return 1f; } + @Override public float getPositionOffset() { return 0f; } + @Override public float getTextureScale() { return 1f; } + @Override public GlVertexFormat getVertexFormat() { return null; } + @Override public ChunkVertexEncoder createEncoder() { return null; } + }; + + private static TerrainRenderPass pass(String name) { + return new TerrainRenderPass(name, null, false, false, false, false, VERTEX_TYPE, PRIMITIVE, Map.of()); + } + + private static RenderRegion region(int x, int y, int z) { + try { + for (Constructor ctor : RenderRegion.class.getDeclaredConstructors()) { + if (ctor.getParameterCount() == 5) { + ctor.setAccessible(true); + return (RenderRegion) ctor.newInstance(x, y, z, 0, null); + } + } + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + throw new IllegalStateException("RenderRegion constructor shape changed"); + } + + private SectionRenderDataStorage storage() { + final SectionRenderDataUnsafe.Strategy layout = SectionRenderDataUnsafe.Strategy.COMPACT; + final int bytes = (int) layout.getStride() * RenderRegion.REGION_SIZE; + final ByteBuffer rows = MemoryUtilities.memAlloc(bytes).order(ByteOrder.nativeOrder()); + for (int i = 0; i < bytes; i++) rows.put(i, (byte) 0); + allocated.add(rows); + + final SectionRenderDataStorage storage = allocateInstance(SectionRenderDataStorage.class); + setField(storage, SectionRenderDataStorage.class, "storageStrategy", layout); + setField(storage, SectionRenderDataStorage.class, "primitiveType", PRIMITIVE); + setField(storage, SectionRenderDataStorage.class, "pMeshDataArray", MemoryUtilities.memAddress(rows)); + return storage; + } + + @SuppressWarnings("unchecked") + private static T allocateInstance(Class type) { + try { + final Class unsafeClass = Class.forName("sun.misc.Unsafe"); + final Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + final Object unsafe = theUnsafe.get(null); + return (T) unsafeClass.getMethod("allocateInstance", Class.class).invoke(unsafe, type); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + private static void setField(Object target, Class owner, String name, Object value) { + try { + final Field field = owner.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + @SuppressWarnings("unchecked") + private static void attachStorage(RenderRegion region, TerrainRenderPass renderPass, SectionRenderDataStorage storage) { + try { + final Field field = RenderRegion.class.getDeclaredField("sectionRenderData"); + field.setAccessible(true); + ((Map) field.get(region)).put(renderPass, storage); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + private static ChunkRenderList renderList(RenderRegion region, int... localSectionIndices) { + final ChunkRenderList list = new ChunkRenderList(region); + final byte[] sections = new byte[RenderRegion.REGION_SIZE]; + for (int i = 0; i < localSectionIndices.length; i++) { + sections[i] = (byte) localSectionIndices[i]; + } + setField(list, ChunkRenderList.class, "sectionsWithGeometry", sections); + setField(list, ChunkRenderList.class, "sectionsWithGeometryCount", localSectionIndices.length); + return list; + } + + private static ChunkRenderListIterable lists(ChunkRenderList... lists) { + return reverse -> List.of(lists).iterator(); + } + + private static void writeSection(SectionRenderDataStorage storage, int localSectionIndex, int baseVertex, int... vertsPerFacing) { + final Map ranges = new EnumMap<>(ModelQuadFacing.class); + int vertex = baseVertex; + for (int f = 0; f < vertsPerFacing.length; f++) { + if (vertsPerFacing[f] > 0) { + ranges.put(ModelQuadFacing.VALUES[f], new VertexRange(vertex, vertsPerFacing[f])); + } + vertex += vertsPerFacing[f]; + } + storage.getStorageStrategy().writeMeshes(storage.getDataPointer(localSectionIndex), baseVertex, 0, ranges, PRIMITIVE); + } + + private static RecordingSink walk(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform camera, boolean faceCulling) { + final RecordingSink sink = new RecordingSink(); + new ShadowVoxelizer().walkPass(renderLists, renderPass, null, camera, camera, faceCulling, sink); + return sink; + } + + private final List allocated = new ArrayList<>(); + + @AfterEach + void tearDown() { + GpuCulling.setMode(GpuCullingMode.CPU_ONLY); + allocated.forEach(MemoryUtilities::memFree); + allocated.clear(); + } + + @Test + void emittedRangesAreIdenticalAcrossCullModes() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 0, 8, 4, 0, 0, 12); + writeSection(storage, 5, 100, 0, 16, 0, 0, 4, 0, 0); + attachStorage(region, renderPass, storage); + final ChunkRenderListIterable renderLists = lists(renderList(region, 0, 5)); + final CameraTransform camera = new CameraTransform(0, 0, 0); + + GpuCulling.setMode(GpuCullingMode.CPU_ONLY); + final RecordingSink cpu = walk(renderLists, renderPass, camera, false); + GpuCulling.setMode(GpuCullingMode.COMPUTE); + final RecordingSink compute = walk(renderLists, renderPass, camera, false); + + assertFalse(cpu.ranges.isEmpty(), "the walk produced nothing to compare"); + assertEquals(cpu.ranges.size(), compute.ranges.size(), "range count differs between cull modes"); + for (int i = 0; i < cpu.ranges.size(); i++) { + assertArrayEqualsInt(cpu.ranges.get(i), compute.ranges.get(i), "range " + i); + } + assertEquals(1, cpu.regions.size(), "one region announced once"); + assertEquals(1, compute.regions.size()); + } + + @Test + void regionOffsetIsCameraRelative() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(1, 0, 3); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 0, 0, 0, 0, 0, 0); + attachStorage(region, renderPass, storage); + final CameraTransform camera = new CameraTransform(70.25, 12.5, -3.75); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, camera, false); + + assertEquals(1, sink.regions.size()); + final float[] offset = sink.regions.get(0); + assertEquals(region.getOriginX() - camera.intX - camera.fracX, offset[0], 0f, "x"); + assertEquals(region.getOriginY() - camera.intY - camera.fracY, offset[1], 0f, "y"); + assertEquals(region.getOriginZ() - camera.intZ - camera.fracZ, offset[2], 0f, "z"); + } + + @Test + void regionOffsetUsesTheRegionOriginNotA256BlockGrid() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(1, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 0, 0, 0, 0, 0, 0); + attachStorage(region, renderPass, storage); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false); + + assertEquals(128f, sink.regions.get(0)[0], 0f, "region 1 starts at block 128"); + } + + @Test + void contiguousFacingsCollapseToOneRange() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 4, 4, 4, 4, 4, 4); + attachStorage(region, renderPass, storage); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false); + + assertEquals(1, sink.ranges.size(), "seven adjacent facings are one vertex span, not seven dispatches"); + assertEquals(0, sink.ranges.get(0)[0]); + assertEquals(28, sink.ranges.get(0)[1]); + } + + @Test + void gapsInTheFacingMaskSplitRuns() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 0, 8, 0, 0, 0, 4); + attachStorage(region, renderPass, storage); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false); + + assertEquals(3, sink.ranges.size()); + assertArrayEqualsInt(new int[]{0, 4}, sink.ranges.get(0), "facing 0"); + assertArrayEqualsInt(new int[]{4, 8}, sink.ranges.get(1), "facing 2"); + assertArrayEqualsInt(new int[]{12, 4}, sink.ranges.get(2), "facing 6"); + } + + @Test + void sectionsWithoutGeometryNeverAnnounceTheRegion() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 0, 0, 0, 0, 0, 0, 0); + attachStorage(region, renderPass, storage); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false); + + assertTrue(sink.regions.isEmpty(), "an empty region must not open an encoder"); + assertTrue(sink.ranges.isEmpty()); + assertEquals(1, sink.finishes); + } + + @Test + void missingStorageForThePassIsSkipped() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + + final RecordingSink sink = walk(lists(renderList(region, 0)), renderPass, new CameraTransform(0, 0, 0), false); + + assertTrue(sink.ranges.isEmpty()); + assertEquals(1, sink.finishes); + } + + @Test + void unbindableRegionIsSkippedButThePassContinues() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion regionA = region(0, 0, 0); + final RenderRegion regionB = region(1, 0, 0); + final SectionRenderDataStorage storageA = storage(); + final SectionRenderDataStorage storageB = storage(); + writeSection(storageA, 0, 0, 4, 0, 0, 0, 0, 0, 0); + writeSection(storageB, 0, 0, 4, 0, 0, 0, 0, 0, 0); + attachStorage(regionA, renderPass, storageA); + attachStorage(regionB, renderPass, storageB); + + final RecordingSink sink = new RecordingSink(); + sink.refuseRegion = true; + new ShadowVoxelizer().walkPass(lists(renderList(regionA, 0), renderList(regionB, 0)), renderPass, null, + new CameraTransform(0, 0, 0), new CameraTransform(0, 0, 0), false, sink); + + assertTrue(sink.ranges.isEmpty(), "a region that cannot be bound emits nothing"); + assertEquals(1, sink.finishes, "the encoder is still closed exactly once"); + } + + @Test + void refusedRangeSkipsOnlyThatRegion() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion regionA = region(0, 0, 0); + final RenderRegion regionB = region(1, 0, 0); + final SectionRenderDataStorage storageA = storage(); + final SectionRenderDataStorage storageB = storage(); + writeSection(storageA, 0, 0, 4, 0, 4, 0, 0, 0, 0); + writeSection(storageB, 0, 0, 4, 0, 0, 0, 0, 0, 0); + attachStorage(regionA, renderPass, storageA); + attachStorage(regionB, renderPass, storageB); + + final RecordingSink sink = new RecordingSink() { + @Override public boolean range(int vertexOffset, int vertexCount) { + return regions.size() != 1 && super.range(vertexOffset, vertexCount); + } + }; + new ShadowVoxelizer().walkPass(lists(renderList(regionA, 0), renderList(regionB, 0)), renderPass, null, new CameraTransform(0, 0, 0), new CameraTransform(0, 0, 0), false, sink); + + assertEquals(2, sink.regions.size(), "the second region is still attempted after the first is refused"); + assertEquals(1, sink.ranges.size(), "only the second region's range lands"); + assertEquals(1, sink.finishes); + } + + @Test + void faceCullingNarrowsTheEmittedRangesTheSameWayInBothModes() { + final TerrainRenderPass renderPass = pass("solid"); + final RenderRegion region = region(0, 0, 0); + final SectionRenderDataStorage storage = storage(); + writeSection(storage, 0, 0, 4, 4, 4, 4, 4, 4, 4); + attachStorage(region, renderPass, storage); + final ChunkRenderListIterable renderLists = lists(renderList(region, 0)); + final CameraTransform camera = new CameraTransform(500, 200, 500); + + GpuCulling.setMode(GpuCullingMode.CPU_ONLY); + final RecordingSink cpu = walk(renderLists, renderPass, camera, true); + GpuCulling.setMode(GpuCullingMode.COMPUTE); + final RecordingSink compute = walk(renderLists, renderPass, camera, true); + + assertFalse(cpu.ranges.isEmpty(), "face culling removed everything; the fixture is not exercising the path"); + assertTrue(cpu.ranges.size() < 7 || cpu.ranges.get(0)[1] < 28, "face culling did not narrow anything"); + assertEquals(cpu.ranges.size(), compute.ranges.size()); + for (int i = 0; i < cpu.ranges.size(); i++) { + assertArrayEqualsInt(cpu.ranges.get(i), compute.ranges.get(i), "range " + i); + } + } + + private static void assertArrayEqualsInt(int[] expected, int[] actual, String label) { + assertEquals(expected[0], actual[0], label + " vertexOffset"); + assertEquals(expected[1], actual[1], label + " vertexCount"); + } +} diff --git a/src/test/java/com/prupe/mcpatcher/mal/biome/BlockCachedColorMapTest.java b/src/test/java/com/prupe/mcpatcher/mal/biome/BlockCachedColorMapTest.java new file mode 100644 index 000000000..6800ad869 --- /dev/null +++ b/src/test/java/com/prupe/mcpatcher/mal/biome/BlockCachedColorMapTest.java @@ -0,0 +1,103 @@ +package com.prupe.mcpatcher.mal.biome; + +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.IBlockAccess; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BlockCachedColorMapTest { + + private static final class CountingMap implements IColorMap { + + private final float[] scratch = new float[3]; + int calls; + + @Override + public boolean isHeightDependent() { + return true; + } + + @Override + public int getColorMultiplier() { + return 0; + } + + @Override + public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { + return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k)); + } + + @Override + public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { + calls++; + scratch[0] = i; + scratch[1] = j; + scratch[2] = k; + return scratch; + } + + @Override + public void claimResources(Collection resources) {} + + @Override + public IColorMap copy() { + return new CountingMap(); + } + } + + private final IBlockAccess world = Mockito.mock(IBlockAccess.class); + + @Test + void repeatQueriesHitTheCache() { + final CountingMap parent = new CountingMap(); + final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent); + + final float[] first = cached.getColorMultiplierF(world, 10, 64, -3); + assertEquals(1, parent.calls); + assertArrayEquals(new float[] { 10, 64, -3 }, first); + + cached.getColorMultiplierF(world, 10, 64, -3); + assertEquals(1, parent.calls, "second query for the same block must not hit the parent"); + } + + @Test + void cachedValueSurvivesParentScratchReuse() { + final CountingMap parent = new CountingMap(); + final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent); + + final float[] a = cached.getColorMultiplierF(world, 1, 64, 1); + cached.getColorMultiplierF(world, 2, 64, 2); + assertArrayEquals(new float[] { 1, 64, 1 }, a, "parent scratch reuse must not corrupt cached entries"); + assertArrayEquals(new float[] { 1, 64, 1 }, cached.getColorMultiplierF(world, 1, 64, 1)); + assertEquals(2, parent.calls); + } + + @Test + void distinctCoordinatesAreDistinctEntries() { + final CountingMap parent = new CountingMap(); + final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent); + + cached.getColorMultiplierF(world, -1, 64, 0); + cached.getColorMultiplierF(world, 0, 64, -1); + cached.getColorMultiplierF(world, -1, 63, 0); + assertEquals(3, parent.calls, "negative/asymmetric coords must not collide in the packed key"); + } + + @Test + void worldChangeClearsTheCache() { + final CountingMap parent = new CountingMap(); + final ColorMapBase.BlockCached cached = new ColorMapBase.BlockCached(parent); + + cached.getColorMultiplierF(world, 5, 64, 5); + assertEquals(1, parent.calls); + + final IBlockAccess otherWorld = Mockito.mock(IBlockAccess.class); + cached.getColorMultiplierF(otherWorld, 5, 64, 5); + assertEquals(2, parent.calls, "a different world must not serve cached colors"); + } +} diff --git a/src/test/java/me/flashyreese/mods/reeses_sodium_options/util/StringUtilsTest.java b/src/test/java/me/flashyreese/mods/reeses_sodium_options/util/StringUtilsTest.java index 96f89c933..ba03033a2 100644 --- a/src/test/java/me/flashyreese/mods/reeses_sodium_options/util/StringUtilsTest.java +++ b/src/test/java/me/flashyreese/mods/reeses_sodium_options/util/StringUtilsTest.java @@ -1,5 +1,10 @@ package me.flashyreese.mods.reeses_sodium_options.util; +import java.util.Collection; +import me.jellysquid.mods.sodium.client.gui.options.OptionFlag; +import me.jellysquid.mods.sodium.client.gui.options.OptionImpact; +import me.jellysquid.mods.sodium.client.gui.options.control.Control; +import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage; import com.google.common.collect.ImmutableList; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.OptionPage; @@ -99,16 +104,16 @@ class StringUtilsTest { @Override public String getName() { return name; } @Override public String getTooltip() { return tooltip; } - @Override public me.jellysquid.mods.sodium.client.gui.options.OptionImpact getImpact() { return null; } - @Override public me.jellysquid.mods.sodium.client.gui.options.control.Control getControl() { return null; } + @Override public OptionImpact getImpact() { return null; } + @Override public Control getControl() { return null; } @Override public Object getValue() { return null; } @Override public void setValue(Object value) {} @Override public void reset() {} - @Override public me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage getStorage() { return null; } + @Override public OptionStorage getStorage() { return null; } @Override public boolean isAvailable() { return true; } @Override public boolean hasChanged() { return false; } @Override public void applyChanges() {} - @Override public java.util.Collection getFlags() { return List.of(); } + @Override public Collection getFlags() { return List.of(); } } private static class MockOptionPage extends OptionPage { diff --git a/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java b/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java new file mode 100644 index 000000000..a8a12ced2 --- /dev/null +++ b/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java @@ -0,0 +1,101 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilderTest.TestLayer; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AngelicaBufferSourceTest { + + private static final ModelQuad QUAD = SegmentedBufferBuilderTest.quad(); + + @Test + void sameLayerKeepsBuilderAffinity() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + final SegmentedBufferBuilder first = source.getBuffer(layer, 1); + first.addQuad(QUAD); + final SegmentedBufferBuilder second = source.getBuffer(layer, 2); + assertSame(first, second); + } + + @Test + void prepareGroupsSegmentsByLayerAndSortsOpaqueById() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final TestLayer opaque = new TestLayer("opaque", TransparencyType.OPAQUE); + final TestLayer translucent = new TestLayer("translucent", TransparencyType.GENERAL_TRANSPARENT); + + source.getBuffer(opaque, 7).addQuad(QUAD); + source.getBuffer(translucent, 9).addQuad(QUAD); + source.getBuffer(opaque, 3).addQuad(QUAD); + source.getBuffer(translucent, 2).addQuad(QUAD); + + final List order = source.prepare(); + assertEquals(2, order.size()); + + assertSame(opaque, order.get(0)); + assertSame(translucent, order.get(1)); + + final List opaqueSegments = source.segmentsFor(opaque); + assertNotNull(opaqueSegments); + assertEquals(2, opaqueSegments.size()); + assertEquals(3, opaqueSegments.get(0).getBlockEntityId()); + assertEquals(7, opaqueSegments.get(1).getBlockEntityId()); + + final List translucentSegments = source.segmentsFor(translucent); + assertEquals(2, translucentSegments.size()); + assertEquals(9, translucentSegments.get(0).getBlockEntityId()); + assertEquals(2, translucentSegments.get(1).getBlockEntityId()); + } + + @Test + void affinityEvictionLosesNoSegments() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final int layers = 40; + for (int i = 0; i < layers; i++) { + source.getBuffer(new TestLayer("layer" + i, TransparencyType.OPAQUE), i).addQuad(QUAD); + } + final List order = source.prepare(); + assertEquals(layers, order.size()); + int segments = 0; + for (RenderLayer layer : order) { + segments += source.segmentsFor(layer).size(); + } + assertEquals(layers, segments); + } + + @Test + void endBatchWithTypeCompactsOrder() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final TestLayer opaqueA = new TestLayer("oa", TransparencyType.OPAQUE); + final TestLayer translucent = new TestLayer("t", TransparencyType.GENERAL_TRANSPARENT); + final TestLayer opaqueB = new TestLayer("ob", TransparencyType.OPAQUE); + source.declareUse(opaqueA); + source.declareUse(translucent); + source.declareUse(opaqueB); + + source.endBatchWithType(TransparencyType.OPAQUE, null); + + final List remaining = source.prepare(); + assertEquals(1, remaining.size()); + assertSame(translucent, remaining.get(0)); + } + + @Test + void declaredLayersAppearInOrderWithoutSegments() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final TestLayer retainedOnly = new TestLayer("retained", TransparencyType.OPAQUE); + source.declareUse(retainedOnly); + final List order = source.prepare(); + assertEquals(1, order.size()); + assertSame(retainedOnly, order.get(0)); + assertTrue(source.isEmpty()); + } +} diff --git a/src/test/java/net/coderbot/batchedentityrendering/impl/BufferSourceProbe.java b/src/test/java/net/coderbot/batchedentityrendering/impl/BufferSourceProbe.java new file mode 100644 index 000000000..51af8e630 --- /dev/null +++ b/src/test/java/net/coderbot/batchedentityrendering/impl/BufferSourceProbe.java @@ -0,0 +1,18 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; + +import java.util.List; + +public final class BufferSourceProbe { + + private BufferSourceProbe() {} + + public static List prepare(AngelicaBufferSource source) { + return source.prepare(); + } + + public static List segmentsFor(AngelicaBufferSource source, RenderLayer layer) { + return source.segmentsFor(layer); + } +} diff --git a/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java b/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java new file mode 100644 index 000000000..f22e6f66f --- /dev/null +++ b/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java @@ -0,0 +1,263 @@ +package net.coderbot.batchedentityrendering.impl; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import java.nio.ByteBuffer; +import java.util.List; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SegmentedBufferBuilderTest { + + static final class TestLayer extends RenderLayer implements BlendingStateHolder { + private final TransparencyType transparencyType; + + TestLayer(String name, TransparencyType transparencyType) { + super(name, BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 256, () -> {}, () -> {}); + this.transparencyType = transparencyType; + } + + @Override + public TransparencyType getTransparencyType() { + return transparencyType; + } + } + + static ModelQuad quad() { + final ModelQuad q = new ModelQuad(); + for (int i = 0; i < 4; i++) { + q.setX(i, i); + q.setY(i, i); + q.setZ(i, i); + } + return q; + } + + @Test + void sameKeyContinuesSegment() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + builder.begin(layer, 5); + builder.addQuad(quad()); + builder.begin(layer, 5); + builder.addQuad(quad()); + final List segments = builder.getSegments(); + assertEquals(1, segments.size()); + assertEquals(0, segments.get(0).getFirstVertex()); + assertEquals(8, segments.get(0).getVertexCount()); + assertEquals(5, segments.get(0).getBlockEntityId()); + } + + @Test + void keyChangeSplitsSegments() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE); + final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE); + builder.begin(a, 1); + builder.addQuad(quad()); + builder.begin(a, 2); + builder.addQuad(quad()); + builder.addQuad(quad()); + builder.begin(b, 2); + builder.addQuad(quad()); + final List segments = builder.getSegments(); + assertEquals(3, segments.size()); + assertEquals(0, segments.get(0).getFirstVertex()); + assertEquals(4, segments.get(0).getVertexCount()); + assertEquals(1, segments.get(0).getBlockEntityId()); + assertEquals(4, segments.get(1).getFirstVertex()); + assertEquals(8, segments.get(1).getVertexCount()); + assertEquals(2, segments.get(1).getBlockEntityId()); + assertEquals(0, segments.get(2).getFirstVertex()); + assertEquals(4, segments.get(2).getVertexCount()); + assertEquals(b, segments.get(2).getRenderType()); + } + + @Test + void emptySegmentsAreDropped() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE); + final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE); + builder.begin(a, 1); + builder.begin(b, 1); + builder.addQuad(quad()); + final List segments = builder.getSegments(); + assertEquals(1, segments.size()); + assertEquals(b, segments.get(0).getRenderType()); + } + + @Test + void bufferGrowsPastInitialCapacity() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + builder.begin(layer, 1); + final ModelQuad q = quad(); + final int quads = 3000; // 3000 * 4 * 32B ~ 384KB > 256KB initial + for (int i = 0; i < quads; i++) { + builder.addQuad(q); + } + final List segments = builder.getSegments(); + assertEquals(1, segments.size()); + assertEquals(quads * 4, segments.get(0).getVertexCount()); + assertEquals(quads * 4, builder.getVertexCount()); + } + + @Test + void resetClearsFillState() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + builder.begin(layer, 1); + builder.addQuad(quad()); + builder.reset(); + assertTrue(builder.isEmpty()); + assertEquals(0, builder.getSegments().size()); + } + + @Test + void addTemplateInstanceTransformsAndExtendsSegment() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + + builder.begin(layer, 3); + builder.addTemplateInstance(template(), new Matrix4f().translation(10f, 20f, 30f), new Vector3f(), -1, 0, null); + builder.addQuad(quad()); + + final List segments = builder.getSegments(); + assertEquals(1, segments.size()); + assertEquals(0, segments.get(0).getFirstVertex()); + assertEquals(8, segments.get(0).getVertexCount()); + assertEquals(3, segments.get(0).getBlockEntityId()); + + final ByteBuffer buffer = segments.get(0).getOwner().buffer; + final int stride = layer.getVertexFormat().getVertexSize(); + for (int v = 0; v < 4; v++) { + assertEquals(10f + v, buffer.getFloat(v * stride), 1e-6f, "x of vertex " + v); + assertEquals(20f, buffer.getFloat(v * stride + 4), 1e-6f, "y of vertex " + v); + assertEquals(30f, buffer.getFloat(v * stride + 8), 1e-6f, "z of vertex " + v); + } + } + + @Test + void reclaimFreesIdleLayerBuffers() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + final long t0 = 100_000L; + + builder.begin(layer, 1); + builder.addQuad(quad()); + builder.resetAndReclaim(t0, 10_000L); + assertEquals(1, builder.bufferCount(), "used buffer survives its own batch"); + + builder.resetAndReclaim(t0 + 5_000L, 10_000L); + assertEquals(1, builder.bufferCount(), "unused buffer survives within the idle window"); + + builder.resetAndReclaim(t0 + 10_001L, 10_000L); + assertEquals(0, builder.bufferCount(), "buffer idle past the window is freed"); + } + + @Test + void allocatedBytesTracksBufferLifecycle() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE); + final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE); + final long t0 = 100_000L; + assertEquals(0L, builder.allocatedBytes()); + + builder.begin(a, 1); + builder.addQuad(quad()); + List segments = builder.getSegments(); + final SegmentedBufferBuilder.LayerBuffer aBuffer = segments.get(0).getOwner(); + final long aInitial = aBuffer.buffer.capacity(); + assertEquals(aInitial, builder.allocatedBytes(), "creation adds initial capacity"); + + builder.begin(a, 1); + final ModelQuad q = quad(); + for (int i = 0; i < 3000; i++) { + builder.addQuad(q); + } + builder.begin(b, 1); + builder.addQuad(q); + segments = builder.getSegments(); + final SegmentedBufferBuilder.LayerBuffer bBuffer = segments.get(segments.size() - 1).getOwner(); + final long aGrown = aBuffer.buffer.capacity(); + assertTrue(aGrown > aInitial, "layer a buffer grew"); + assertEquals(aGrown + bBuffer.buffer.capacity(), builder.allocatedBytes(), "growth adds capacity delta"); + + builder.resetAndReclaim(t0, 10_000L); + assertEquals(aGrown + bBuffer.buffer.capacity(), builder.allocatedBytes(), "reclaim without eviction keeps bytes"); + + builder.resetAndReclaim(t0 + 10_001L, 10_000L); + assertEquals(0L, builder.allocatedBytes(), "eviction subtracts capacity"); + + builder.begin(a, 1); + builder.addQuad(q); + assertEquals(aInitial, builder.allocatedBytes(), "recreation adds fresh capacity"); + builder.freeAll(); + assertEquals(0L, builder.allocatedBytes(), "freeAll zeroes"); + } + + @Test + void evictionThenReuseKeepsStateConsistent() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer a = new TestLayer("a", TransparencyType.OPAQUE); + final TestLayer b = new TestLayer("b", TransparencyType.OPAQUE); + final long t0 = 100_000L; + + builder.begin(a, 1); + builder.addQuad(quad()); + builder.begin(b, 1); + builder.addQuad(quad()); + builder.resetAndReclaim(t0, 10_000L); + assertEquals(2, builder.bufferCount()); + + builder.resetAndReclaim(t0 + 10_001L, 10_000L); + assertEquals(0, builder.bufferCount()); + assertEquals(0L, builder.allocatedBytes()); + assertTrue(builder.isEmpty()); + + builder.begin(a, 2); + builder.addQuad(quad()); + final List segments = builder.getSegments(); + assertEquals(1, segments.size()); + assertEquals(2, segments.get(0).getBlockEntityId()); + assertEquals(1, builder.bufferCount()); + assertTrue(builder.allocatedBytes() > 0); + } + + @Test + void freeAllReleasesBuffersAndStaysUsable() { + final SegmentedBufferBuilder builder = new SegmentedBufferBuilder(); + final TestLayer layer = new TestLayer("a", TransparencyType.OPAQUE); + + builder.begin(layer, 1); + builder.addQuad(quad()); + builder.freeAll(); + assertTrue(builder.isEmpty()); + assertEquals(0, builder.bufferCount()); + + builder.begin(layer, 1); + builder.addQuad(quad()); + assertEquals(1, builder.getSegments().size()); + } + + static TemplateBuffer template() { + final int[] data = new int[4 * VERTEX_SIZE]; + for (int v = 0; v < 4; v++) { + final int base = v * VERTEX_SIZE; + data[base + X_INDEX] = Float.floatToRawIntBits(v); + data[base + COLOR_INDEX] = 0xFFFFFFFF; + } + return new TemplateBuffer(data, 4, GL11.GL_QUADS); + } +} diff --git a/src/test/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolderTest.java b/src/test/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolderTest.java new file mode 100644 index 000000000..dc7b260af --- /dev/null +++ b/src/test/java/net/coderbot/iris/gl/uniform/ManifestCollectingHolderTest.java @@ -0,0 +1,81 @@ +package net.coderbot.iris.gl.uniform; + +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; +import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ManifestCollectingHolderTest { + + private static void declare(UniformHolder h) { + final Vector3fc zero = new Vector3f(); + h.uniform1f(PER_FRAME, "frameTimeCounter", () -> 0.0f) + .uniform1f(ONCE, "pi", () -> 3.14159f) + .uniform3f(PER_FRAME, "cameraPosition", () -> zero) + .uniform1i(PER_TICK, "worldTime", () -> 0) + .uniform1f(PER_FRAME, "rainStrength", () -> 0.0f) + .externallyManagedUniform("iris_ModelViewMatrix", UniformType.MAT4); + } + + private static UniformManifest harvest() { + final ManifestCollectingHolder h = new ManifestCollectingHolder(); + declare(h); + return h.build(); + } + + @Test + void groupsByFrequencyPreservingRegistrationOrderWithinGroup() { + final List e = harvest().entries(); + + assertEquals(List.of("pi", "worldTime", "frameTimeCounter", "cameraPosition", "rainStrength"), + e.stream().map(UniformManifest.Entry::name).toList(), + "ONCE then PER_TICK then PER_FRAME, declaration order inside each group"); + + assertEquals(List.of(ONCE, PER_TICK, PER_FRAME, PER_FRAME, PER_FRAME), + e.stream().map(UniformManifest.Entry::frequency).toList()); + } + + @Test + void capturesDeclaredTypes() { + final UniformManifest m = harvest(); + assertEquals(UniformType.VEC3, entry(m, "cameraPosition").type()); + assertEquals(UniformType.FLOAT, entry(m, "frameTimeCounter").type()); + assertEquals(UniformType.INT, entry(m, "worldTime").type()); + } + + @Test + void isDeterministicAcrossHarvests() { + assertEquals(harvest().entries(), harvest().entries()); + } + + @Test + void externallyManagedUniformsStayOutOfTheBlock() { + final UniformManifest m = harvest(); + assertTrue(m.externallyManagedNames().contains("iris_ModelViewMatrix")); + assertFalse(m.entries().stream().anyMatch(e -> e.name().equals("iris_ModelViewMatrix")), "per-draw matrices are written by the backend and must remain loose uniforms"); + } + + @Test + void duplicateDeclarationIsDroppedNotDuplicated() { + final ManifestCollectingHolder h = new ManifestCollectingHolder(); + h.uniform1f(PER_FRAME, "rainStrength", () -> 0.0f); + h.uniform1f(ONCE, "rainStrength", () -> 1.0f); + + final List e = h.build().entries(); + assertEquals(1, e.size()); + assertEquals(PER_FRAME, e.get(0).frequency(), "first declaration wins"); + } + + private static UniformManifest.Entry entry(UniformManifest m, String name) { + return m.entries().stream().filter(x -> x.name().equals(name)).findFirst().orElseThrow(); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java b/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java new file mode 100644 index 000000000..b15fcbdf2 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java @@ -0,0 +1,32 @@ +package net.coderbot.iris.pipeline; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MvBuiltinScanTest { + + @Test + void detectsVariableUsage() { + String frag = "#version 120\nvoid main() { vec4 p = gl_ModelViewMatrix * vec4(1.0); gl_FragColor = p; }"; + assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag)); + } + + @Test + void detectsFtransformCall() { + String vert = "#version 120\nvoid main() { gl_Position = ftransform(); }"; + assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(vert)); + } + + @Test + void ignoresCommentsAndUnrelated() { + String frag = "#version 120\n// gl_ModelViewMatrix in a comment only\nvoid main() { gl_FragColor = vec4(1.0); }"; + assertFalse(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag)); + } + + @Test + void nullSourceIsClean() { + assertFalse(DeferredWorldRenderingPipeline.referencesMvBuiltins(null)); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/ShadowGraphGateTest.java b/src/test/java/net/coderbot/iris/pipeline/ShadowGraphGateTest.java new file mode 100644 index 000000000..5ca61c52e --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/ShadowGraphGateTest.java @@ -0,0 +1,34 @@ +package net.coderbot.iris.pipeline; + +import net.coderbot.iris.shadows.ShadowGraphGate; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ShadowGraphGateTest { + + @Test + void nanAlwaysDirty() { + assertTrue(ShadowGraphGate.shouldMarkDirty(Float.NaN, 0.25f)); + } + + @Test + void smallDeltaClean() { + assertFalse(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f + 0.0004f)); + assertFalse(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f - 0.0004f)); + } + + @Test + void thresholdDeltaDirty() { + assertTrue(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f + 0.001f)); + assertTrue(ShadowGraphGate.shouldMarkDirty(0.25f, 0.25f - 0.001f)); + } + + @Test + void wrapAroundIsNotADiscontinuity() { + assertFalse(ShadowGraphGate.shouldMarkDirty(0.9999f, 0.0001f), "0.0002 across the wrap is below threshold"); + assertTrue(ShadowGraphGate.shouldMarkDirty(0.999f, 0.0006f), "0.0016 across the wrap is above threshold"); + assertFalse(ShadowGraphGate.shouldMarkDirty(0.0001f, 0.9999f), "wrap works in both directions"); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java new file mode 100644 index 000000000..567746033 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java @@ -0,0 +1,163 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.taumc.glsl.ShaderParser; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AttributeTransformerInstancedTest { + + private static final InputAvailability TEX_LM = new InputAvailability(true, true); + + private static final String VERTEX = """ + #version 120 + attribute vec4 mc_Entity; + attribute vec4 mc_midTexCoord; + varying vec2 texcoord; + varying vec2 lmcoord; + varying vec4 color; + varying float mats; + varying vec2 midtex; + varying vec3 nrm; + void main() { + texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; + lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + color = gl_Color; + mats = mc_Entity.x; + midtex = mc_midTexCoord.st; + nrm = normalize(gl_NormalMatrix * gl_Normal); + gl_Position = ftransform(); + } + """; + + private static final String VERTEX_MV_INVERSE = """ + #version 120 + varying vec3 wpos; + void main() { + wpos = (gl_ModelViewMatrixInverse * (gl_ModelViewMatrix * gl_Vertex)).xyz; + gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex; + } + """; + + private static final String FRAGMENT = """ + #version 120 + varying vec4 color; + void main() { + gl_FragData[0] = color; + } + """; + + @BeforeAll + static void initShaderTransformer() throws Exception { + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460); + ShaderTransformer.init(); + } + + @BeforeEach + void clearCaches() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + } + + private static String instancedVertex(String vertex) { + Map result = TransformPatcher.patchAttributesInstanced(vertex, null, null, null, FRAGMENT, TEX_LM, false); + assertNotNull(result); + String v = result.get(PatchShaderType.VERTEX); + assertNotNull(v); + ShaderParser.parseShader(v); + return v; + } + + private static String squash(String s) { + return s.replaceAll("\\s+", ""); + } + + private static void assertHas(String shader, String snippet) { + assertTrue(squash(shader).contains(squash(snippet)), "expected snippet: " + snippet); + } + + private static void assertLacks(String shader, String snippet) { + assertFalse(squash(shader).contains(squash(snippet)), "unexpected snippet: " + snippet); + } + + private static int indexOfSquashed(String shader, String snippet) { + return squash(shader).indexOf(squash(snippet)); + } + + @Test + void declaresInstanceAttribsAndGlobalMatrices() { + final String v = instancedVertex(VERTEX); + assertHas(v, "layout(location = 7) in vec4 iris_InstMat0"); + assertHas(v, "layout(location = 8) in vec4 iris_InstMat1"); + assertHas(v, "layout(location = 9) in vec4 iris_InstMat2"); + assertHas(v, "layout(location = 10) in vec4 iris_InstMat3"); + assertHas(v, "layout(location = 11) in vec4 iris_InstColor"); + assertHas(v, "layout(location = 12) in vec2 iris_InstLightmap"); + assertLacks(v, "uniform mat4 iris_ModelViewMatrix;"); + assertLacks(v, "uniform mat3 iris_NormalMatrix;"); + assertHas(v, "mat4 iris_ModelViewMatrix;"); + assertHas(v, "iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3)"); + assertHas(v, "iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz))"); + } + + @Test + void lightmapComesFromInstanceAttribute() { + final String v = instancedVertex(VERTEX); + assertLacks(v, "layout(location = 3)"); + assertHas(v, "iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0)"); + assertHas(v, "iris_LightmapTextureMatrix * iris_MultiTexCoord1"); + } + + @Test + void colorComposesInstanceColor() { + assertHas(instancedVertex(VERTEX), "iris_Color * iris_ColorModulator * iris_InstColor"); + } + + @Test + void foldsEntityAndMidTexCoordAttributes() { + final String v = instancedVertex(VERTEX); + assertLacks(v, "mc_Entity"); + assertLacks(v, "mc_midTexCoord"); + assertHas(v, "vec4(-1.0, -1.0, 0.0, 1.0)"); + assertHas(v, "vec4(0.5, 0.5, 0.0, 1.0)"); + } + + @Test + void mvInverseOnlyWhenReferenced() { + assertLacks(instancedVertex(VERTEX), "inverse(iris_ModelViewMatrix)"); + + final String with = instancedVertex(VERTEX_MV_INVERSE); + assertHas(with, "iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix)"); + assertLacks(with, "uniform mat4 iris_ModelViewMatrixInverse;"); + } + + @Test + void assignmentBlockRunsFirstInMain() { + final String v = instancedVertex(VERTEX); + final int mainIdx = indexOfSquashed(v, "void main()"); + final int assignIdx = indexOfSquashed(v, "iris_ModelViewMatrix = mat4("); + final int bodyUseIdx = indexOfSquashed(v, "iris_TextureMatrix * iris_MultiTexCoord0"); + assertTrue(mainIdx >= 0 && assignIdx > mainIdx); + assertTrue(bodyUseIdx > assignIdx); + } + + @Test + void standardPathUnchanged() { + Map result = TransformPatcher.patchAttributes(VERTEX, null, null, null, FRAGMENT, TEX_LM, false); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + assertHas(v, "uniform mat4 iris_ModelViewMatrix;"); + assertHas(v, "layout(location = 3) in vec4 iris_MultiTexCoord1"); + assertHas(v, "mc_Entity"); + assertLacks(v, "iris_InstMat0"); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/DHGenericAttributeLocationTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/DHGenericAttributeLocationTest.java new file mode 100644 index 000000000..4556af928 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/DHGenericAttributeLocationTest.java @@ -0,0 +1,97 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DHGenericAttributeLocationTest { + + private static final Map EXPECTED = new LinkedHashMap<>(); + static { + EXPECTED.put("vPosition", DHGenericTransformer.DH_GENERIC_LOC_POSITION); + EXPECTED.put("iris_color", DHGenericTransformer.DH_GENERIC_LOC_COLOR); + EXPECTED.put("aScale", DHGenericTransformer.DH_GENERIC_LOC_SCALE); + EXPECTED.put("aTranslateChunk", DHGenericTransformer.DH_GENERIC_LOC_TRANSLATE_CHUNK); + EXPECTED.put("aTranslateSubChunk", DHGenericTransformer.DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK); + EXPECTED.put("aMaterial", DHGenericTransformer.DH_GENERIC_LOC_MATERIAL); + } + + private static final String VERTEX = """ + #version 330 core + out vec4 col; + void main() { + col = vec4(1.0); + gl_Position = vec4(0.0); + } + """; + + private static final String FRAGMENT = """ + #version 330 core + in vec4 col; + void main() { + gl_FragData[0] = col; + } + """; + + @BeforeAll + static void initShaderTransformer() throws Exception { + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460); + ShaderTransformer.init(); + } + + @BeforeEach + void clearCaches() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + } + + private static String patchedVertex() { + final Map result = TransformPatcher.patchDHGeneric("dh_generic_test", VERTEX, null, null, null, FRAGMENT, Object2ObjectMaps.emptyMap()); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + assertNotNull(v); + return v; + } + + @Test + void everyDhGenericInputCarriesItsAuthoritativeLocation() { + final String vertex = patchedVertex(); + + for (Map.Entry e : EXPECTED.entrySet()) { + final Matcher m = Pattern + .compile("layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*in\\s+\\w+\\s+" + e.getKey() + "\\s*;") + .matcher(vertex); + assertTrue(m.find(), () -> "no explicit location for '" + e.getKey() + "' in:\n" + vertex); + assertEquals(e.getValue().intValue(), Integer.parseInt(m.group(1)), () -> e.getKey() + " must sit at DH's hardcoded index"); + } + } + + @Test + void noDhGenericInputIsLeftUnlocated() { + final String vertex = patchedVertex(); + + for (String name : EXPECTED.keySet()) { + final Matcher bare = Pattern.compile("(?m)^\\s*in\\s+\\w+\\s+" + name + "\\s*;").matcher(vertex); + assertTrue(!bare.find(), () -> "'" + name + "' declared without a location in:\n" + vertex); + } + } + + @Test + void locationsAreABijection() { + assertEquals(EXPECTED.size(), EXPECTED.values().stream().distinct().count(), "two inputs sharing a location would collide at link time"); + assertEquals(0, EXPECTED.values().stream().min(Integer::compare).orElseThrow().intValue()); + assertEquals(5, EXPECTED.values().stream().max(Integer::compare).orElseThrow().intValue()); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/GlslAstHelpersTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/GlslAstHelpersTest.java new file mode 100644 index 000000000..1646f97df --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/GlslAstHelpersTest.java @@ -0,0 +1,49 @@ +package net.coderbot.iris.pipeline.transform; + +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.grammar.GLSLParser; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GlslAstHelpersTest { + + @Test void zeroLiteralFor_basicTypes() { + assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor("image2D")); + assertEquals("ivec4(0)", GlslAstHelpers.zeroLiteralFor("iimage2D")); + assertEquals("uvec4(0u)", GlslAstHelpers.zeroLiteralFor("uimage3D")); + assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor("image1D")); + assertEquals("vec4(0.0)", GlslAstHelpers.zeroLiteralFor(null)); + } + + @Test void componentTypeFor_basicTypes() { + assertEquals("vec4", GlslAstHelpers.componentTypeFor("image3D")); + assertEquals("ivec4", GlslAstHelpers.componentTypeFor("iimage1D")); + assertEquals("uvec4", GlslAstHelpers.componentTypeFor("uimage2D")); + } + + @Test void firstArgIdentifier_returnsCalleeFirstArg() { + final var snippet = ShaderParser.parseSnippet("imageStore(target_img, ivec2(0), uvec4(0u))", + GLSLParser::postfix_expression); + assertEquals("target_img", GlslAstHelpers.firstArgIdentifier(snippet)); + } + + @Test void deleteStatementContaining_unlinksStmt() { + final String src = "#version 460 core\nvoid main(){ int x = 1; imageStore(t, 0, 0); int y = 2; }"; + final var parsed = ShaderParser.parseShader(src); + final var calls = GlslAstHelpers.collectAll(parsed.full(), GLSLParser.Postfix_expressionContext.class); + GLSLParser.Postfix_expressionContext target = null; + for (var c : calls) { + if ("imageStore".equals(GlslAstHelpers.extractCallName(c))) { target = c; break; } + } + assertTrue(target != null, "expected to find imageStore call in synthetic source"); + final boolean removed = GlslAstHelpers.deleteStatementContaining(target); + assertTrue(removed); + final var remaining = GlslAstHelpers.collectAll(parsed.full(), GLSLParser.Postfix_expressionContext.class); + for (var c : remaining) { + assertFalse("imageStore".equals(GlslAstHelpers.extractCallName(c)), "imageStore call should no longer be reachable in the tree"); + } + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformerTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformerTest.java new file mode 100644 index 000000000..756e53522 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/LocalZeroInitTransformerTest.java @@ -0,0 +1,248 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import org.antlr.v4.runtime.tree.ParseTree; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.ShaderPrinter; +import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LocalZeroInitTransformerTest { + + private static int savedMaxGlsl; + + @BeforeAll + static void initShaderTransformer() { + savedMaxGlsl = Reflect.getStatic(RenderSystem.class, "maxGlslVersion"); + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460); + ShaderTransformer.clearCache(); + ShaderTransformer.init(); + } + + @AfterAll + static void restoreCapabilities() { + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", savedMaxGlsl); + ShaderTransformer.clearCache(); + TransformPatcher.clearCache(); + ShaderTransformer.init(); + } + + private static final Set NUMERIC = Set.of( + "float", "int", "uint", + "vec2", "vec3", "vec4", "ivec2", "ivec3", "ivec4", "uvec2", "uvec3", "uvec4", + "mat2", "mat3", "mat4", + "mat2x2", "mat2x3", "mat2x4", "mat3x2", "mat3x3", "mat3x4", "mat4x2", "mat4x3", "mat4x4"); + + private record Declarator(String type, String name) {} + + private static String run(String src) { + final Transformer t = new Transformer(ShaderParser.parseShader(src).full()); + LocalZeroInitTransformer.transform(t); + final StringBuilder sb = new StringBuilder(); + t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree))); + return sb.toString(); + } + + private static List uninitialized(String src) { + final ParseTree tree = ShaderParser.parseShader(src).full(); + final List out = new ArrayList<>(); + for (GLSLParser.Declaration_statementContext stmt : GlslAstHelpers.collectAll(tree, GLSLParser.Declaration_statementContext.class)) { + final GLSLParser.DeclarationContext declaration = stmt.declaration(); + if (declaration == null) continue; + final GLSLParser.Init_declarator_listContext list = declaration.init_declarator_list(); + if (list == null) continue; + final GLSLParser.Single_declarationContext single = list.single_declaration(); + if (single == null) continue; + final String type = single.fully_specified_type() == null ? "" : single.fully_specified_type().getText(); + + final List declarators = new ArrayList<>(); + declarators.add(single.typeless_declaration()); + declarators.addAll(list.typeless_declaration()); + for (GLSLParser.Typeless_declarationContext d : declarators) { + if (d == null || d.initializer() != null) continue; + out.add(new Declarator(type, d.IDENTIFIER().getText())); + } + } + return out; + } + + private static boolean isUninitialized(String src, String name) { + return uninitialized(src).stream().anyMatch(d -> d.name().equals(name)); + } + + @Test + void accumulatorGetsZeroInitializer() { + final String src = + "#version 460 core\n" + + "out vec4 fragColor;\n" + + "vec4 accumulate() {\n" + + " vec4 lightVolume;\n" + + " for (int i = 0; i < 8; i++) lightVolume += vec4(float(i));\n" + + " return lightVolume;\n" + + "}\n" + + "void main() { fragColor = accumulate(); }\n"; + + assertTrue(isUninitialized(src, "lightVolume"), "fixture must start uninitialized"); + final String out = run(src); + assertTrue(uninitialized(out).isEmpty(), out); + } + + @Test + void existingInitializersAreLeftAlone() { + final String src = + "#version 460 core\n" + + "void main() {\n" + + " vec3 a = vec3(1.0, 2.0, 3.0);\n" + + " float b = 4.0;\n" + + "}\n"; + + final String out = run(src); + assertTrue(out.contains("vec3(1.0, 2.0, 3.0)"), out); + assertTrue(out.contains("4.0"), out); + assertTrue(uninitialized(out).isEmpty(), out); + } + + @Test + void multiDeclaratorListInitializesOnlyBareNames() { + final String src = + "#version 460 core\n" + + "void main() {\n" + + " vec3 a, b = vec3(1.0), c;\n" + + " a += b; c += b;\n" + + "}\n"; + + final String out = run(src); + assertTrue(uninitialized(out).isEmpty(), out); + assertTrue(out.contains("vec3(1.0)"), "b must keep its own initializer: " + out); + } + + @Test + void arrayDeclarationsAreSkippedInBothSpellings() { + final String src = + "#version 460 core\n" + + "void main() {\n" + + " float a[3];\n" + + " float[3] b;\n" + + " vec3 c[2];\n" + + "}\n"; + + final String out = run(src); + assertTrue(isUninitialized(out, "a"), out); + assertTrue(isUninitialized(out, "b"), out); + assertTrue(isUninitialized(out, "c"), out); + } + + @Test + void structAndOpaqueLocalsAreSkipped() { + final String src = + "#version 460 core\n" + + "struct Material { vec3 albedo; float rough; };\n" + + "void main() {\n" + + " Material m;\n" + + " m.rough = 1.0;\n" + + "}\n"; + + final String out = run(src); + assertTrue(isUninitialized(out, "m"), "struct locals have no scalar zero constructor: " + out); + } + + @Test + void qualifiedDeclarationsAreSkipped() { + final String src = + "#version 460 core\n" + + "void main() {\n" + + " const float k = 2.0;\n" + + " precise float p;\n" + + "}\n"; + + final String out = run(src); + assertTrue(isUninitialized(out, "p"), out); + assertTrue(out.contains("2.0"), "const initializer must survive: " + out); + } + + @Test + void boolAndDoubleAreSkipped() { + final String src = + "#version 460 core\n" + + "void main() {\n" + + " bool flag;\n" + + " double d;\n" + + "}\n"; + + final String out = run(src); + assertTrue(isUninitialized(out, "flag"), out); + assertTrue(isUninitialized(out, "d"), out); + } + + private static int numericBareCount(String src) { + return (int) uninitialized(src).stream().filter(d -> NUMERIC.contains(d.type())).count(); + } + + @Test + void patcherEmittedShapesLeaveNoBareNumericLocals() { + TransformPatcher.clearCache(); + final Map patched = TransformPatcher.patchComposite(PACK_SHAPED_VSH, null, PACK_SHAPED_FSH); + + for (PatchShaderType stage : List.of(PatchShaderType.VERTEX, PatchShaderType.FRAGMENT)) { + final String source = patched.get(stage); + assertNotNull(source, stage + " produced no output"); + assertTrue(numericBareCount(source) > 0, stage + ": fixture must reach the transformer with bare numeric locals\n\n" + source); + + final List leftover = uninitialized(run(source)).stream() + .filter(d -> NUMERIC.contains(d.type())) + .toList(); + assertEquals(List.of(), leftover, stage + " still has bare numeric locals\n\n" + run(source)); + } + } + + private static final String PACK_SHAPED_VSH = String.join("\n", + "#version 330 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec2 mc_midTexCoord;", + "out vec4 v_Color;", + "out vec3 v_Accum;", + "void main() {", + " vec4 accum;", + " mat3 tbn;", + " float depth;", + " ivec2 cell;", + " accum += iris_Color;", + " tbn[0] += vec3(mc_midTexCoord, 0.0);", + " depth += iris_Vertex.z;", + " cell += ivec2(1);", + " v_Color = accum + vec4(float(cell.x));", + " v_Accum = tbn[0] * depth;", + " gl_Position = iris_Vertex;", + "}", + ""); + + private static final String PACK_SHAPED_FSH = String.join("\n", + "#version 330 core", + "in vec4 v_Color;", + "in vec3 v_Accum;", + "uniform sampler2D tex;", + "void main() {", + " vec3 lighting;", + " vec2 uv;", + " uint bits;", + " lighting += v_Accum;", + " uv += v_Color.xy;", + " bits += 1u;", + " gl_FragColor = vec4(lighting + texture(tex, uv).rgb, float(bits));", + "}", + ""); +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractorTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractorTest.java new file mode 100644 index 000000000..e805f9055 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/RwImageStoreExtractorTest.java @@ -0,0 +1,645 @@ +package net.coderbot.iris.pipeline.transform; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RwImageStoreExtractorTest { + + @AfterEach + void clearImageRegistry() { + RwImageStoreExtractor.setActiveCustomImages(null); + } + + private static String norm(String s) { + return s.replaceAll("\\s+", " ").trim(); + } + + private static final String MINIMAL_VOX_VSH = String.join("\n", + "#version 460 core", + "#extension GL_ARB_shader_image_load_store : enable", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "attribute vec4 mc_Entity;", + "attribute vec4 at_midBlock;", + "writeonly uniform uimage3D voxel_img;", + "out vec2 texCoord;", + "flat out int mat;", + "uniform mat4 gbufferModelView;", + "void main() {", + " texCoord = iris_MultiTexCoord0.xy;", + " mat = int(mc_Entity.x + 0.5);", + " gl_Position = vec4(iris_Vertex.xyz, 1.0);", + " if (gl_VertexID % 4 == 0) {", + " imageStore(voxel_img, ivec3(at_midBlock.xyz), uvec4(uint(mat), 0u, 0u, 0u));", + " }", + "}", + ""); + + private static final String NO_IMAGESTORE_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "void main() { gl_Position = iris_Vertex; }", + ""); + + @Test void detection_returnsNullWhenNoImageStore() { + assertNull(RwImageStoreExtractor.tryExtract(NO_IMAGESTORE_VSH, PatchShaderType.VERTEX, "shadow")); + } + + @Test void detection_returnsNullOnNullInput() { + assertNull(RwImageStoreExtractor.tryExtract(null, PatchShaderType.VERTEX, "shadow")); + } + + @Test void writtenImages_collectedFromImageStoreCalls() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + assertNotNull(result); + assertTrue(result.writtenImages().contains("voxel_img")); + } + + @Test void modeIsChunkWhenChunkAttrsPresent() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + assertEquals(RwImageStoreExtractor.RwExtractMode.CHUNK, result.mode()); + } + + @Test void compute_hasComputeVersionAndWorkgroup() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + assertTrue(result.computeSource().startsWith("// _vg_mode: chunk\n")); + assertTrue(result.computeSource().contains("#version 460 core")); + assertTrue(result.computeSource().contains("layout(local_size_x = 64) in;")); + } + + @Test void compute_hasUniformsAndSsboBinding() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + final String s = result.computeSource(); + assertTrue(s.contains("uniform int _vg_startVertex;")); + assertTrue(s.contains("uniform int _vg_vertexCount;")); + assertTrue(s.contains("readonly buffer _VgVbuf")); + assertTrue(s.contains("layout(std430, binding = " + RwImageStoreExtractor.VG_VBUF_SSBO_BINDING + ") readonly buffer _VgVbuf"), "VBO SSBO must bind at the dedicated voxelization slot (not 0..8 which shaderpacks claim via buffer.N)"); + } + + @Test void compute_ssboBindingDoesNotCollideWithShaderpackSlots() { + assertTrue(RwImageStoreExtractor.VG_VBUF_SSBO_BINDING >= 9, "VG_VBUF_SSBO_BINDING must be >= 9 to avoid colliding with shaderpack buffer.N slots; got " + RwImageStoreExtractor.VG_VBUF_SSBO_BINDING); + } + + @Test void compute_renamesOriginalMainToVgBody() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + final String s = result.computeSource(); + assertTrue(s.contains("_vg_body"), "expected _vg_body in compute output"); + assertFalse(norm(s).contains("void main ( ) { texCoord ="), "user-original main must be renamed"); + } + + @Test void compute_synthesizedMainCallsUnpackAndBody() { + final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource(); + assertTrue(s.contains("gl_GlobalInvocationID")); + assertTrue(s.contains("_vg_unpack(uint(id));")); + assertTrue(s.contains("_vg_body();")); + } + + @Test void compute_hoistsAttributeDependentGlobalInitializers() { + final String vsh = MINIMAL_VOX_VSH.replace( + "void main() {", + "float tAmin = fract(mc_Entity.y);\nvec4 iris_Entity = vec4(mc_Entity.x - 1.0, 0.0, 0.0, 1.0);\nvoid main() {"); + final String s = RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, "shadow").computeSource(); + final String n = norm(s); + assertFalse(n.contains("vec4 iris_Entity = "), "global initializers evaluate before the dispatch main decodes attributes; must be stripped"); + assertTrue(n.contains("iris_Entity = vec4 ( mc_Entity . x"), "every stripped initializer must be re-emitted as an assignment, not just the first"); + assertTrue(n.contains("tAmin = fract ( mc_Entity . y"), "every stripped initializer must be re-emitted as an assignment, not just the first"); + assertTrue(n.indexOf("_vg_body ( ) {") < n.indexOf("iris_Entity = vec4 ( mc_Entity . x"), "the assignment must run inside the body, after the attribute decode"); + assertTrue(n.indexOf("tAmin = fract") < n.indexOf("iris_Entity = vec4"), "hoisted assignments must keep declaration order"); + } + + @Test void compute_keepsUnsizedArrayInitializersInPlace() { + final String vsh = MINIMAL_VOX_VSH.replace( + "void main() {", + "vec3[] tintA = vec3[](vec3(1.0), vec3(0.5));\nvec3 tintB[] = vec3[](vec3(1.0), vec3(0.5));\nvoid main() {"); + final String s = RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, "shadow").computeSource(); + final String n = norm(s); + assertTrue(n.contains("tintA = vec3 [ ] ("), "tintA: unsized array initializer must stay on the declaration"); + assertTrue(n.contains("tintB [ ] = vec3 [ ] ("), "tintB: unsized array initializer must stay on the declaration"); + assertTrue(n.indexOf("tintA =") == n.lastIndexOf("tintA ="), "tintA: initializer must not additionally be hoisted into the body"); + } + + @Test void compute_unpackHasExpectedAttributeReads() { + final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource(); + assertTrue(s.contains("iris_Vertex = vec4(uintBitsToFloat(_vg_vbuf.data[base + 0u])")); + assertTrue(s.contains("iris_Color = vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu)")); + assertTrue(s.contains("mc_Entity = vec4(float(_vg_vbuf.data[base + 10u])"), "ATTRIBUTES-patch mc_Entity is delivered as vec4 raw"); + } + + @Test void compute_dropsOutQualifierFromVaryings() { + final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource(); + assertFalse(norm(s).contains("out vec2 texCoord"), "out qualifier should be stripped\n\n" + s); + assertTrue(norm(s).contains("vec2 texCoord"), "varying becomes a global"); + } + + @Test void compute_vertInitOnlyAssignsUnpackedAttributes() { + final String src = String.join("\n", + "#version 460 core", + "in vec3 a_PosId;", + "writeonly uniform uimage3D voxel_img;", + "void main() {", + " gl_Position = vec4(a_PosId, 1.0);", + " imageStore(voxel_img, ivec3(a_PosId), uvec4(1u, 0u, 0u, 0u));", + "}", + ""); + final String s = norm(RwImageStoreExtractor.tryExtract(src, PatchShaderType.VERTEX, "shadow").computeSource()); + assertTrue(s.contains("_vert_position = a_PosId"), "the used attribute is still decoded\n\n" + s); + assertFalse(s.contains("a_TexCoord"), "an unused attribute must not be referenced\n\n" + s); + assertFalse(s.contains("a_LightCoord"), "an unused attribute must not be referenced\n\n" + s); + } + + @Test void compute_dropsInterpolationQualifierFromVaryings() { + final String s = norm(RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource()); + assertFalse(s.contains("flat"), "flat is interface-only; a compute global carrying it does not compile\n\n" + s); + assertTrue(s.contains("int mat"), "the varying still becomes a global"); + } + + @Test void compute_dropsAuxiliaryStorageQualifierFromVaryings() { + final String src = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "writeonly uniform uimage3D voxel_img;", + "centroid out vec2 texCoord;", + "void main() {", + " texCoord = iris_Vertex.xy;", + " imageStore(voxel_img, ivec3(0), uvec4(1u, 0u, 0u, 0u));", + "}", + ""); + final String s = norm(RwImageStoreExtractor.tryExtract(src, PatchShaderType.VERTEX, "shadow").computeSource()); + assertFalse(s.contains("centroid"), "centroid is interface-only\n\n" + s); + assertTrue(s.contains("vec2 texCoord"), "the varying still becomes a global"); + } + + @Test void compute_stripsChunkVertexAttributeDeclarations() { + final String s = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow").computeSource(); + assertFalse(norm(s).contains("in vec4 iris_Vertex")); + assertFalse(norm(s).contains("attribute vec4 mc_Entity")); + } + + @Test void raster_strippedHasNoImageStoreOrWriteonly() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + final String r = result.strippedSource(); + assertFalse(r.contains("imageStore("), "raster should have no imageStore calls"); + assertFalse(r.contains("writeonly uniform uimage"), "raster should have no writeonly image decls"); + assertFalse(norm(r).contains("uniform uimage3D voxel_img"), "raster should have no uimage3D voxel_img decl"); + assertTrue(r.contains("main"), "raster keeps main"); + } + + @Test void directives_preservedThroughRasterStrip() { + final var result = RwImageStoreExtractor.tryExtract(MINIMAL_VOX_VSH, PatchShaderType.VERTEX, "shadow"); + final String r = result.strippedSource(); + assertTrue(r.contains("#version"), "raster keeps a version directive"); + assertTrue(r.contains("#extension GL_ARB_shader_image_load_store"), "raster preserves user #extension directive\n\n" + r); + } + + @Test void knownAttributes_includesAllNineCanonicals() { + for (String name : new String[]{"iris_Vertex","iris_Color","iris_MultiTexCoord0","iris_MultiTexCoord1", "mc_midTexCoord","at_tangent","iris_Normal","mc_Entity","at_midBlock"}) { + assertNotNull(RwImageStoreExtractor.CHUNK_VERTEX_ATTRS.get(name), "missing " + name); + } + } + + @Test void knownAttributeVariants_includesCeleritasTypings() { + final var variants = RwImageStoreExtractor.CHUNK_VERTEX_ATTRS; + assertNotNull(variants.get("a_PosId").get("vec3")); + assertNotNull(variants.get("a_PosId").get("uvec4")); + assertNotNull(variants.get("a_Color").get("vec4")); + assertNotNull(variants.get("a_TexCoord").get("vec2")); + assertNotNull(variants.get("a_LightCoord").get("uint")); + assertNotNull(variants.get("a_LightCoord").get("ivec2")); + assertNotNull(variants.get("mc_Entity").get("vec4")); + assertNotNull(variants.get("mc_Entity").get("uint")); + assertNotNull(variants.get("mc_midTexCoord").get("vec4")); + assertNotNull(variants.get("mc_midTexCoord").get("vec2")); + } + + private static final String CELERITAS_PATCHED_VOX_VSH = String.join("\n", + "#version 460 core", + "#extension GL_ARB_shader_image_load_store : enable", + "", + "#ifdef USE_VERTEX_COMPRESSION", + "in uvec4 a_PosId;", + "in vec4 a_Color;", + "in vec2 a_TexCoord;", + "in ivec2 a_LightCoord;", + "void _vert_init() {", + " uint dummy = a_PosId.w;", + "}", + "#else", + "in vec3 a_PosId;", + "in vec4 a_Color;", + "in vec2 a_TexCoord;", + "in uint a_LightCoord;", + "void _vert_init() {", + " vec3 p = a_PosId;", + "}", + "#endif", + "", + "vec3 _vert_position;", + "vec2 _vert_tex_diffuse_coord;", + "ivec2 _vert_tex_light_coord;", + "vec4 _vert_color;", + "uint _draw_id;", + "uint _material_params;", + "", + "in uint mc_Entity;", + "in vec2 mc_midTexCoord;", + "in vec3 iris_Normal;", + "in vec4 at_midBlock;", + "", + "writeonly uniform uimage3D voxel_img;", + "", + "uniform vec3 u_RegionOffset;", + "out vec4 outColor;", + "", + "void main() {", + " _vert_init();", + " outColor = a_Color * vec4(iris_Normal, 1.0);", + " gl_Position = vec4(a_PosId + u_RegionOffset, 1.0);", + " if (mc_Entity > 0u) {", + " imageStore(voxel_img, ivec3(at_midBlock.xyz * 127.0), uvec4(mc_Entity, 0u, 0u, 0u));", + " }", + "}", + ""); + + @Test void celeritas_tryExtractProducesComputeSource() { + final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN"); + assertNotNull(result); + assertNotNull(result.computeSource(), "compute source must be built for celeritas-patched VSH"); + assertTrue(result.writtenImages().contains("voxel_img")); + assertEquals(RwImageStoreExtractor.RwExtractMode.CHUNK, result.mode()); + } + + @Test void celeritas_computeContainsLiveBranchGlobals() { + final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource(); + assertTrue(s.contains("vec3 a_PosId;"), "uncompressed (live) a_PosId global"); + assertTrue(s.contains("vec4 a_Color;")); + assertTrue(s.contains("vec2 a_TexCoord;")); + assertTrue(s.contains("uint a_LightCoord;")); + assertTrue(s.contains("uint mc_Entity;")); + assertTrue(s.contains("vec2 mc_midTexCoord;")); + assertTrue(s.contains("vec3 iris_Normal;")); + assertTrue(s.contains("vec4 at_midBlock;")); + } + + @Test void celeritas_computeContainsDeadBranchStubGlobals() { + final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource(); + assertTrue(s.contains("uvec4 a_PosId;"), "compressed-branch stub a_PosId"); + assertTrue(s.contains("ivec2 a_LightCoord;"), "compressed-branch stub a_LightCoord"); + assertTrue(s.contains("#ifdef USE_VERTEX_COMPRESSION"), "expected #ifdef guard around dual-branch globals"); + assertTrue(s.contains("#else")); + assertTrue(s.contains("#endif")); + } + + @Test void celeritas_unpackContainsCeleritasFormulas() { + final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource(); + assertTrue(s.contains("a_PosId = vec3(uintBitsToFloat(_vg_vbuf.data[base + 0u])")); + assertTrue(s.contains("a_TexCoord = vec2(uintBitsToFloat(_vg_vbuf.data[base + 4u])")); + assertTrue(s.contains("a_LightCoord = _vg_vbuf.data[base + 6u]")); + assertTrue(s.contains("mc_Entity = _vg_vbuf.data[base + 10u]"), "celeritas-typed mc_Entity must be delivered as the raw packed uint"); + assertTrue(s.contains("mc_midTexCoord = vec2(float(_vg_vbuf.data[base + 7u] & 0xFFFFu),"), "mc_midTexCoord is an unnormalized ushort delivered raw by the vertex stage, so the compute prelude must not rescale it"); + assertTrue(s.contains("a_PosId = uvec4(0u, 0u, 0u, 0u)")); + assertTrue(s.contains("a_LightCoord = ivec2(0, 0)")); + } + + @Test void celeritas_computeDecodesVertexGlobals() { + final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource(); + assertTrue(s.contains("_vert_position = a_PosId;"), "uncompressed branch must decode position\n\n" + s); + assertTrue(s.contains("_vert_position = vec3(a_PosId.xyz) * VERT_POS_SCALE + VERT_POS_OFFSET;"), "compressed branch must decode position\n\n" + s); + assertTrue(s.contains("_draw_id = (_vg_draw_params >> 8) & 0xFFu;"), "_get_draw_translation depends on _draw_id\n\n" + s); + } + + @Test void celeritas_vertexDecodeComesAfterTheGlobalDeclarations() { + final String s = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN").computeSource(); + for (String global : new String[]{"_vert_position", "_vert_tex_diffuse_coord", "_vert_color", "_vert_tex_light_coord", "_draw_id", "_material_params"}) { + final int declared = s.indexOf(global + " ;"); + final int assigned = s.indexOf(global + " ="); + assertTrue(declared >= 0, global + " should be declared by the celeritas header\n\n" + s); + assertTrue(assigned < 0 || declared < assigned, global + " is assigned at " + assigned + " before its declaration at " + declared + "\n\n" + s); + } + } + + @Test void celeritas_strippedHasNoImageStoreOrUimage() { + final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN"); + final String r = result.strippedSource(); + assertFalse(r.contains("imageStore(")); + assertFalse(norm(r).contains("uniform uimage3D voxel_img")); + } + + private static final String MULTI_IMAGE_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "attribute vec4 mc_Entity;", + "attribute vec4 at_midBlock;", + "writeonly uniform uimage2D wsr_img;", + "writeonly uniform uimage3D voxel_img;", + "writeonly uniform uimage3D wsr_lod_img;", + "void main() {", + " imageStore(voxel_img, ivec3(0), uvec4(0u));", + " imageStore(wsr_img, ivec2(0), uvec4(0u));", + " imageStore(wsr_lod_img, ivec3(0), uvec4(0u));", + "}", + ""); + + @Test void compute_emitsExplicitBindingsForWriteonlyImages() { + final String s = RwImageStoreExtractor.tryExtract(MULTI_IMAGE_VSH, PatchShaderType.VERTEX, "ATTRIBUTES").computeSource(); + assertTrue(s.contains("layout(binding = 0) writeonly uniform uimage3D voxel_img;"), "voxel_img must be binding 0 (alphabetical-first), missing in:\n" + s); + assertTrue(s.contains("layout(binding = 1) writeonly uniform uimage2D wsr_img;")); + assertTrue(s.contains("layout(binding = 2) writeonly uniform uimage3D wsr_lod_img;")); + } + + private static final String NON_WRITEONLY_PREPARE_VSH = String.join("\n", + "#version 460 core", + "layout(r32i) uniform iimage2D endcrystal_img;", + "uniform mat4 gbufferModelView;", + "void main() {", + " ivec4 prev = imageLoad(endcrystal_img, ivec2(0, 0));", + " imageStore(endcrystal_img, ivec2(0, 0), ivec4(prev.x + 1));", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void nonWriteonlyImage_stripsFromRaster() { + final var result = RwImageStoreExtractor.tryExtract(NON_WRITEONLY_PREPARE_VSH, PatchShaderType.VERTEX, "prepare"); + assertNotNull(result); + assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH, result.mode(), "no chunk attrs -> composite-vsh"); + final String r = result.strippedSource(); + assertFalse(r.contains("iimage2D"), "raster must have no iimage2D decl\n\n" + r); + assertFalse(r.contains("imageStore("), "raster must have no imageStore call"); + assertTrue(r.contains("ivec4(0)"), "imageLoad must be replaced by ivec4(0)\n\n" + r); + } + + private static final String COMPOSITE_VSH = String.join("\n", + "#version 460 core", + "writeonly uniform uimage2D state_img;", + "uniform mat4 gl_ModelViewProjectionMatrix;", + "void main() {", + " gl_Position = ftransform();", + " imageStore(state_img, ivec2(gl_VertexID, 0), uvec4(1u));", + "}", + ""); + + @Test void compositeVsh_modeAndPrelude() { + final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_VSH, PatchShaderType.VERTEX, "composite"); + assertNotNull(result); + assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH, result.mode()); + final String s = result.computeSource(); + assertTrue(s.startsWith("// _vg_mode: composite-vsh\n"), "sentinel comment on line 1\n\n" + s); + assertTrue(s.contains("const vec4 _vg_quad[4]"), "quad table missing\n\n" + s); + assertTrue(s.contains("#define gl_Vertex _vg_gl_vertex")); + assertTrue(s.contains("#define gl_VertexID _vg_gl_vertex_id")); + assertTrue(s.contains("vec4 iris_ftransform()")); + assertTrue(s.contains("if (vid >= 4u) return;")); + } + + @Test void compositeVsh_rasterStillCompilesShape() { + final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_VSH, PatchShaderType.VERTEX, "composite"); + final String r = result.strippedSource(); + assertFalse(r.contains("imageStore("), "raster has no imageStore"); + assertFalse(r.contains("uimage2D"), "raster has no uimage2D decl"); + } + + private static final String COMPOSITE_FSH = String.join("\n", + "#version 460 core", + "writeonly uniform uimage2D out_img;", + "in vec2 texcoord;", + "out vec4 outColor;", + "void main() {", + " ivec2 px = ivec2(gl_FragCoord.xy);", + " imageStore(out_img, px, uvec4(uint(px.x), uint(px.y), 0u, 0u));", + " outColor = vec4(0.0, 0.0, 0.0, 1.0);", + "}", + ""); + + @Test void compositeFsh_modeAndPrelude() { + final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_FSH, PatchShaderType.FRAGMENT, "composite_fsh"); + assertNotNull(result); + assertEquals(RwImageStoreExtractor.RwExtractMode.COMPOSITE_FSH, result.mode()); + final String s = result.computeSource(); + assertTrue(s.startsWith("// _vg_mode: composite-fsh\n")); + assertTrue(s.contains("layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;")); + assertTrue(s.contains("uniform ivec2 _vg_target_size;")); + assertTrue(s.contains("#define gl_FragCoord _vg_gl_fragcoord_raw")); + assertTrue(s.contains("vec2(px) + 0.5")); + } + + @Test void compositeFsh_rasterKeepsOutColorButStripsImage() { + final var result = RwImageStoreExtractor.tryExtract(COMPOSITE_FSH, PatchShaderType.FRAGMENT, "composite_fsh"); + final String r = result.strippedSource(); + assertFalse(r.contains("imageStore(")); + assertFalse(r.contains("uimage2D")); + assertTrue(norm(r).contains("out vec4 outColor"), "raster keeps user output\n\n" + r); + } + + private static final String ATOMIC_IMAGE_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "attribute vec4 mc_Entity;", + "attribute vec4 at_midBlock;", + "layout(r32ui) uniform uimage3D counter_img;", + "void main() {", + " imageAtomicAdd(counter_img, ivec3(0, 0, 0), 1u);", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void imageAtomic_isClassifiedAsWrite() { + final var result = RwImageStoreExtractor.tryExtract(ATOMIC_IMAGE_VSH, PatchShaderType.VERTEX, "atomic"); + assertNotNull(result); + assertTrue(result.writtenImages().contains("counter_img"), "imageAtomicAdd must classify the image as written"); + assertFalse(result.strippedSource().contains("imageAtomicAdd("), "imageAtomic call must be stripped from raster"); + } + + private static final String MIXED_IMAGES_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "attribute vec4 mc_Entity;", + "attribute vec4 at_midBlock;", + "uniform image2D voxel_a;", + "uniform iimage2D voxel_b;", + "uniform uimage3D voxel_c;", + "void main() {", + " vec4 a = imageLoad(voxel_a, ivec2(0));", + " ivec4 b = imageLoad(voxel_b, ivec2(0));", + " uvec4 c = imageLoad(voxel_c, ivec3(0));", + " imageStore(voxel_a, ivec2(0), a);", + " imageStore(voxel_b, ivec2(0), b);", + " imageStore(voxel_c, ivec3(0), c);", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void mixedReadWrite_componentTypesCorrect() { + final var result = RwImageStoreExtractor.tryExtract(MIXED_IMAGES_VSH, PatchShaderType.VERTEX, "mixed"); + assertNotNull(result); + final String r = result.strippedSource(); + assertTrue(r.contains("vec4(0.0)"), "image2D imageLoad replaced by vec4(0.0)\n\n" + r); + assertTrue(r.contains("ivec4(0)"), "iimage2D imageLoad replaced by ivec4(0)"); + assertTrue(r.contains("uvec4(0u)"), "uimage3D imageLoad replaced by uvec4(0u)"); + } + + private static final String ATOMIC_NOT_WRITEONLY_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "in uint mc_Entity;", + "in vec2 mc_midTexCoord;", + "in vec4 at_midBlock;", + "layout(r32i) uniform iimage2D endcrystal_img;", + "void main() {", + " imageAtomicAdd(endcrystal_img, ivec2(0, 0), 1);", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void atomicOnlyImage_doesNotGetWriteonlyQualifier() { + final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic_only"); + assertNotNull(result); + final String s = result.computeSource(); + assertFalse(s.contains("writeonly uniform iimage2D endcrystal_img"), "imageAtomic-only image must not get writeonly qualifier (atomics are read+write)\n\n" + s); + assertTrue(s.contains("uniform iimage2D endcrystal_img"), "image decl still emitted in prelude\n\n" + s); + } + + @Test void writeonlyImage_stillGetsWriteonlyQualifier() { + final var result = RwImageStoreExtractor.tryExtract(MULTI_IMAGE_VSH, PatchShaderType.VERTEX, "writeonly"); + final String s = result.computeSource(); + assertTrue(s.contains("writeonly uniform uimage3D voxel_img"), + "imageStore-only image keeps writeonly qualifier\n\n" + s); + } + + private static final String IRIS_INJECTED_MC_ENTITY_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "in uint mc_Entity;", + "in vec2 mc_midTexCoord;", + "in vec4 at_midBlock;", + "writeonly uniform uimage3D voxel_img;", + "vec4 iris_Entity = vec4(int(mc_Entity >> 1u) - 1, mc_Entity & 1u, 0.0, 1.0);", + "void main() {", + " imageStore(voxel_img, ivec3(at_midBlock.xyz * 127.0), uvec4(iris_Entity.x, 0u, 0u, 0u));", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void astDeclaredMcEntity_emitsOnlyUintVariant() { + final var result = RwImageStoreExtractor.tryExtract(IRIS_INJECTED_MC_ENTITY_VSH, PatchShaderType.VERTEX, "shadow"); + final String s = result.computeSource(); + assertFalse(s.contains("vec4 mc_Entity"), "mc_Entity declared in AST as uint must not emit a vec4 variant (Iris's iris_Entity uses mc_Entity >> 1u)\n\n" + s); + assertTrue(s.contains("uint mc_Entity;"), "mc_Entity must be emitted as uint matching the AST decl\n\n" + s); + assertFalse(s.contains("vec4 mc_midTexCoord"), "mc_midTexCoord declared in AST as vec2 must not emit a vec4 variant\n\n" + s); + assertTrue(s.contains("vec2 mc_midTexCoord;")); + } + + @Test void celeritasIfdefAttrs_emitBothVariantsGuarded() { + final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN"); + final String s = result.computeSource(); + assertTrue(s.contains("uvec4 a_PosId;"), "compressed-branch stub a_PosId\n\n" + s); + assertTrue(s.contains("vec3 a_PosId;"), "uncompressed-branch live a_PosId\n\n" + s); + } + + private static final String IMAGE_STORE_AS_BRACELESS_IF_BODY_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "in uint mc_Entity;", + "in vec2 mc_midTexCoord;", + "in vec4 at_midBlock;", + "writeonly uniform uimage3D voxel_img;", + "void main() {", + " if (gl_VertexID % 4 == 0)", + " imageStore(voxel_img, ivec3(0), uvec4(0u));", + " gl_Position = vec4(iris_Vertex.xyz, 1.0);", + "}", + ""); + + @Test void raster_brackelessIfBodyImageStore_stripDoesNotLeaveDanglingIf() { + final var result = RwImageStoreExtractor.tryExtract(IMAGE_STORE_AS_BRACELESS_IF_BODY_VSH, PatchShaderType.VERTEX, "if_body"); + assertNotNull(result); + final String r = result.strippedSource(); + assertFalse(r.contains("imageStore("), "imageStore must be removed\n\n" + r); + final String nr = norm(r); + assertTrue(nr.contains("if (gl_VertexID % 4 == 0) ;"), "if statement must have a valid empty body after strip\n\n" + r); + } + + @Test void raster_preservesIfdefBlockAndItsContents() { + final var result = RwImageStoreExtractor.tryExtract(CELERITAS_PATCHED_VOX_VSH, PatchShaderType.VERTEX, "CELERITAS_TERRAIN"); + final String r = result.strippedSource(); + assertTrue(r.contains("#ifdef USE_VERTEX_COMPRESSION"), "raster must preserve the #ifdef block verbatim so _vert_init() resolves\n\n" + r); + assertTrue(r.contains("#else"), "raster preserves the #else branch\n\n" + r); + assertTrue(r.contains("#endif"), "raster preserves the #endif\n\n" + r); + assertTrue(r.contains("void _vert_init()"), "raster must keep the _vert_init definition the user's main calls\n\n" + r); + assertFalse(r.contains("imageStore("), "raster still strips imageStore\n\n" + r); + assertFalse(norm(r).contains("uniform uimage3D voxel_img"), "raster still strips the image decl\n\n" + r); + } + + @Test void atomicCall_rewrittenToInlineCompoundStatement() { + final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic"); + assertNotNull(result); + final String c = result.computeSource(); + final String nc = norm(c); + assertFalse(nc.contains("imageAtomicAdd ("), "imageAtomicAdd must be rewritten in compute output\n\n" + c); + assertTrue(nc.contains("int _vg_prev = imageLoad ( endcrystal_img"), "inline emulation must load the prior value with the original global name\n\n" + c); + assertTrue(nc.contains("imageStore ( endcrystal_img"), "inline emulation must write the new value back to the original global\n\n" + c); + assertTrue(nc.contains("ivec4 ( _vg_prev +"), "inline emulation must compute prev + val in the destination vec\n\n" + c); + } + + @Test void atomicEmulation_droppedWriteonlyQualifier() { + final var result = RwImageStoreExtractor.tryExtract(ATOMIC_NOT_WRITEONLY_VSH, PatchShaderType.VERTEX, "atomic"); + final String c = result.computeSource(); + assertFalse(c.contains("writeonly uniform iimage2D endcrystal_img"), "image used by imageAtomic* must not get writeonly qualifier (now load+store)\n\n" + c); + assertTrue(c.contains("uniform iimage2D endcrystal_img"), "image decl present in prelude\n\n" + c); + } + + private static final String MIXED_ATOMIC_AND_STORE_VSH = String.join("\n", + "#version 460 core", + "in vec4 iris_Vertex;", + "in vec4 iris_Color;", + "in vec4 iris_MultiTexCoord0;", + "in vec3 iris_Normal;", + "in uint mc_Entity;", + "in vec2 mc_midTexCoord;", + "in vec4 at_midBlock;", + "layout(r32i) uniform iimage2D dual_img;", + "void main() {", + " imageStore(dual_img, ivec2(0), ivec4(42, 0, 0, 0));", + " imageAtomicAdd(dual_img, ivec2(1, 0), 1);", + " gl_Position = vec4(0.0);", + "}", + ""); + + @Test void mixedAtomicAndStore_bothRewritten() { + final var result = RwImageStoreExtractor.tryExtract(MIXED_ATOMIC_AND_STORE_VSH, PatchShaderType.VERTEX, "mixed_atom"); + assertNotNull(result); + final String c = result.computeSource(); + final String nc = norm(c); + assertFalse(nc.contains("imageAtomicAdd ("), "atomic call should be rewritten\n\n" + c); + assertTrue(nc.contains("int _vg_prev = imageLoad ( dual_img"), "atomic call should be inlined as load+store on dual_img\n\n" + c); + int storeCount = 0; + int from = 0; + while ((from = nc.indexOf("imageStore ( dual_img", from)) >= 0) { storeCount++; from++; } + assertTrue(storeCount >= 2, "expected both the user's imageStore and the emulated imageStore on dual_img, got " + storeCount + ":\n\n" + c); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicatorTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicatorTest.java new file mode 100644 index 000000000..93ce8aaf6 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/SamplerAliasDeduplicatorTest.java @@ -0,0 +1,140 @@ +package net.coderbot.iris.pipeline.transform; + +import org.junit.jupiter.api.Test; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.ShaderPrinter; +import org.taumc.glsl.Transformer; + +import java.util.EnumMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SamplerAliasDeduplicatorTest { + + private static Transformer parse(String src) { + return new Transformer(ShaderParser.parseShader(src).full()); + } + + private static String format(Transformer t) { + StringBuilder sb = new StringBuilder(); + t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree))); + return sb.toString(); + } + + @Test + void bothDeclared_aliasDropped_canonicalKept() { + String src = + "#version 330 core\n" + + "uniform sampler2D tex;\n" + + "uniform sampler2D textureAtlas;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " fragColor = texture(textureAtlas, vec2(0.5)) + texture(tex, vec2(0.5));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerAliasDeduplicator.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("uniform sampler2D tex"), "canonical declaration must remain"); + assertFalse(out.contains("uniform sampler2D textureAtlas"), "alias declaration must be removed: " + out); + assertFalse(out.contains("textureAtlas"), "all references to alias must be rewritten: " + out); + assertEquals(2, occurrences(out, "texture(tex"), "both references should now read from tex"); + } + + @Test + void onlyAliasDeclared_renamedToCanonical() { + String src = + "#version 330 core\n" + + "uniform sampler2D textureAtlas;\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = texture(textureAtlas, vec2(0.5)); }\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerAliasDeduplicator.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("uniform sampler2D tex"), "alias should be promoted to canonical: " + out); + assertFalse(out.contains("textureAtlas"), "no alias should remain: " + out); + } + + @Test + void crossStage_consistentCanonical() { + String vs = + "#version 330 core\n" + + "uniform sampler2D textureAtlas;\n" + + "void main() { gl_Position = vec4(texture(textureAtlas, vec2(0.0)).xyz, 1.0); }\n"; + String fs = + "#version 330 core\n" + + "uniform sampler2D tex;\n" + + "uniform sampler2D textureAtlas;\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = texture(textureAtlas, vec2(0.5)) + texture(tex, vec2(0.5)); }\n"; + + Transformer vt = parse(vs); + Transformer ft = parse(fs); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.VERTEX, vt); + trees.put(PatchShaderType.FRAGMENT, ft); + SamplerAliasDeduplicator.transformGrouped(trees, null); + + String voutS = format(vt); + String foutS = format(ft); + + assertTrue(voutS.contains("uniform sampler2D tex"), "vertex must declare tex: " + voutS); + assertFalse(voutS.contains("textureAtlas"), "vertex must not reference alias: " + voutS); + assertTrue(foutS.contains("uniform sampler2D tex"), "fragment must declare tex: " + foutS); + assertFalse(foutS.contains("uniform sampler2D textureAtlas"), "fragment alias decl must be gone: " + foutS); + assertFalse(foutS.contains("textureAtlas"), "fragment must not reference alias: " + foutS); + } + + @Test + void noMatch_unchanged() { + String src = + "#version 330 core\n" + + "uniform sampler2D somethingElse;\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = texture(somethingElse, vec2(0.5)); }\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerAliasDeduplicator.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("uniform sampler2D somethingElse"), "untouched uniform must survive: " + out); + assertFalse(out.contains("uniform sampler2D tex"), "no spurious tex declaration: " + out); + } + + @Test + void depthAliasGroup_collapsesToDepthtex0() { + String src = + "#version 330 core\n" + + "uniform sampler2D depthtex0;\n" + + "uniform sampler2D gdepthtex;\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = texture(gdepthtex, vec2(0.5)) + texture(depthtex0, vec2(0.5)); }\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerAliasDeduplicator.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("uniform sampler2D depthtex0")); + assertFalse(out.contains("gdepthtex"), out); + } + + private static int occurrences(String haystack, String needle) { + int n = 0, i = 0; + while ((i = haystack.indexOf(needle, i)) != -1) { n++; i += needle.length(); } + return n; + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriterTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriterTest.java new file mode 100644 index 000000000..d0acc4029 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/SamplerToStorageImageRewriterTest.java @@ -0,0 +1,310 @@ +package net.coderbot.iris.pipeline.transform; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelFormat; +import com.gtnewhorizons.angelica.glsm.texture.PixelType; +import com.gtnewhorizons.angelica.glsm.texture.TextureType; +import net.coderbot.iris.gl.image.ImageInformation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.ShaderPrinter; +import org.taumc.glsl.Transformer; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SamplerToStorageImageRewriterTest { + + @BeforeEach + void setUp() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + + @AfterEach + void tearDown() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + + private static Transformer parse(String src) { + return new Transformer(ShaderParser.parseShader(src).full()); + } + + private static String format(Transformer t) { + StringBuilder sb = new StringBuilder(); + t.mutateTree(tree -> sb.append(ShaderPrinter.getFormattedShader(tree))); + return sb.toString(); + } + + @Test + void integerSampler_texelFetchOnly_rewrittenToImageLoad() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false) + )); + + String src = + "#version 460 core\n" + + "uniform usampler3D wsr_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " uint v = texelFetch(wsr_sampler, ivec3(1,2,3), 0).r;\n" + + " fragColor = vec4(float(v));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertFalse(out.contains("usampler3D wsr_sampler"), "old sampler declaration must be gone: " + out); + assertTrue(out.contains("uimage3D wsr_img"), "image declaration must be injected: " + out); + assertTrue(out.contains("readonly"), "image must be marked readonly: " + out); + assertTrue(out.contains("layout(r16ui)"), "layout qualifier must be present: " + out); + assertTrue(out.contains("imageLoad(wsr_img,"), "texelFetch must be rewritten to imageLoad: " + out); + assertFalse(out.contains("texelFetch(wsr_img"), "texelFetch must not remain on image: " + out); + assertFalse(out.contains("wsr_sampler"), "no reference to the old sampler name: " + out); + } + + @Test + void filteredRead_abortsRewrite() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("ff_sampler", "ff_img", "r16ui", 3, false) + )); + + String src = + "#version 460 core\n" + + "uniform usampler3D ff_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " uvec4 v = texture(ff_sampler, vec3(0.5, 0.5, 0.5));\n" + + " fragColor = vec4(float(v.r));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("usampler3D ff_sampler"), "sampler must remain when filtered read present: " + out); + assertFalse(out.contains("uimage3D"), "no image injected: " + out); + } + + @Test + void legacyTexture2DRead_abortsRewrite() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("puddle_sampler", "puddle_img", "r8ui", 2, false) + )); + + String src = + "#version 460 core\n" + + "uniform usampler2D puddle_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " float noPuddles = texture2D(puddle_sampler, vec2(0.5)).r;\n" + + " fragColor = vec4(noPuddles);\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("usampler2D puddle_sampler"), "sampler must remain when read with texture2D: " + out); + assertFalse(out.contains("puddle_img"), "no image may be injected: " + out); + } + + @Test + void legacyTexture3DRead_abortsRewrite() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false) + )); + + String src = + "#version 460 core\n" + + "uniform usampler3D voxel_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " fragColor = vec4(float(texture3D(voxel_sampler, vec3(0.5)).r));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("usampler3D voxel_sampler"), "sampler must remain: " + out); + assertFalse(out.contains("voxel_img"), "no image may be injected: " + out); + } + + @Test + void floatSamplerNotInCandidateSet_unchanged() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + + String src = + "#version 460 core\n" + + "uniform sampler3D ff_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " fragColor = texelFetch(ff_sampler, ivec3(0), 0);\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("sampler3D ff_sampler"), "float sampler must stay sampler: " + out); + assertFalse(out.contains("uimage3D"), out); + } + + @Test + void crossStage_samplerOnlyInFragment_vertexUntouched() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false) + )); + + String vs = + "#version 460 core\n" + + "void main() { gl_Position = vec4(0.0); }\n"; + String fs = + "#version 460 core\n" + + "uniform usampler3D wsr_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " uvec4 v = texelFetch(wsr_sampler, ivec3(0), 0);\n" + + " fragColor = vec4(float(v.r));\n" + + "}\n"; + + Transformer vt = parse(vs); + Transformer ft = parse(fs); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.VERTEX, vt); + trees.put(PatchShaderType.FRAGMENT, ft); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String fout = format(ft); + assertFalse(fout.contains("usampler3D wsr_sampler"), fout); + assertTrue(fout.contains("uimage3D wsr_img"), fout); + assertTrue(fout.contains("imageLoad(wsr_img,"), fout); + + String vout = format(vt); + assertFalse(vout.contains("uimage3D"), "vertex must be untouched: " + vout); + assertFalse(vout.contains("wsr_img"), vout); + } + + @Test + void multipleCandidates_sameStage_rewriteAllWithoutAnchorBug() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false), + new SamplerToStorageImageRewriter.Candidate("wsr_lod_sampler", "wsr_lod_img", "r8ui", 3, false), + new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false) + )); + + String src = + "#version 460 core\n" + + "uniform mat4 someMatrix;\n" + + "uniform usampler3D wsr_sampler;\n" + + "uniform usampler3D wsr_lod_sampler;\n" + + "uniform usampler3D voxel_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " uint a = texelFetch(wsr_sampler, ivec3(0), 0).r;\n" + + " uint b = texelFetch(wsr_lod_sampler, ivec3(0), 0).r;\n" + + " uint c = texelFetch(voxel_sampler, ivec3(0), 0).r;\n" + + " fragColor = vec4(float(a + b + c));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertFalse(out.contains("usampler3D"), "no sampler declarations left: " + out); + assertTrue(out.contains("uimage3D wsr_img"), out); + assertTrue(out.contains("uimage3D wsr_lod_img"), out); + assertTrue(out.contains("uimage3D voxel_img"), out); + assertTrue(out.contains("imageLoad(wsr_img,"), out); + assertTrue(out.contains("imageLoad(wsr_lod_img,"), out); + assertTrue(out.contains("imageLoad(voxel_img,"), out); + } + + @Test + void imageAlreadyDeclared_skipsRewrite() { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("wsr_sampler", "wsr_img", "r16ui", 3, false) + )); + + String src = + "#version 460 core\n" + + "uniform usampler3D wsr_sampler;\n" + + "layout(r16ui) writeonly uniform uimage3D wsr_img;\n" + + "out vec4 fragColor;\n" + + "void main() {\n" + + " uvec4 v = texelFetch(wsr_sampler, ivec3(0), 0);\n" + + " imageStore(wsr_img, ivec3(0), v);\n" + + " fragColor = vec4(float(v.r));\n" + + "}\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("usampler3D wsr_sampler"), "sampler decl must remain: " + out); + assertTrue(out.contains("writeonly"), "writeonly image decl must remain: " + out); + assertEquals(1, occurrences(out, "uniform uimage3D wsr_img"), "exactly one uimage3D wsr_img declaration (no second readonly injected): " + out); + assertFalse(out.contains("readonly"), "no readonly decl injected: " + out); + assertTrue(out.contains("texelFetch(wsr_sampler"), "texelFetch must NOT be rewritten to imageLoad: " + out); + assertTrue(out.contains("imageStore(wsr_img"), "imageStore on writer must survive: " + out); + } + + private static int occurrences(String haystack, String needle) { + int n = 0, i = 0; + while ((i = haystack.indexOf(needle, i)) != -1) { n++; i += needle.length(); } + return n; + } + + @Test + void noActiveCandidates_noOp() { + String src = + "#version 460 core\n" + + "uniform usampler3D wsr_sampler;\n" + + "out vec4 fragColor;\n" + + "void main() { fragColor = vec4(float(texelFetch(wsr_sampler, ivec3(0), 0).r)); }\n"; + + Transformer t = parse(src); + Map trees = new EnumMap<>(PatchShaderType.class); + trees.put(PatchShaderType.FRAGMENT, t); + SamplerToStorageImageRewriter.transformGrouped(trees, null); + + String out = format(t); + assertTrue(out.contains("usampler3D wsr_sampler"), "sampler must remain when no candidates: " + out); + assertFalse(out.contains("uimage3D"), out); + } + + @Test + void integerCustomImages_produceNoCandidates_onNonSdlBackend() { + assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this to mean anything"); + + final ImageInformation voxel = new ImageInformation("voxel_img", "voxel_sampler", TextureType.TEXTURE_3D, + PixelFormat.RED_INTEGER, InternalTextureFormat.R16UI, PixelType.UNSIGNED_INT, + 512, 256, 512, true, false, 0.0f, 0.0f); + + assertTrue(SamplerToStorageImageRewriter.buildCandidates(List.of(voxel)).isEmpty(), "integer custom images must not become storage images off SDL-GPU"); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java index f25248f3a..da0ec04ff 100644 --- a/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java +++ b/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java @@ -1,11 +1,15 @@ package net.coderbot.iris.pipeline.transform; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.taumc.glsl.ShaderParser; -import java.lang.reflect.Field; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -15,21 +19,206 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.Set; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull; class ShaderTransformerTest { + private static boolean savedImageLoadStore; + + private static void setImageLoadStore(boolean value) throws Exception { + Reflect.setStatic(RenderSystem.class, "supportsImageLoadStore", value); + } + + private static boolean getImageLoadStore() throws Exception { + return Reflect.getStatic(RenderSystem.class, "supportsImageLoadStore"); + } + @BeforeAll static void initShaderTransformer() throws Exception { - Field maxGlsl = RenderSystem.class.getDeclaredField("maxGlslVersion"); - maxGlsl.setAccessible(true); - maxGlsl.setInt(null, 460); + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460); + + savedImageLoadStore = getImageLoadStore(); + setImageLoadStore(true); ShaderTransformer.clearCache(); ShaderTransformer.init(); } + @AfterAll + static void restoreCapabilities() throws Exception { + setImageLoadStore(savedImageLoadStore); + ShaderTransformer.clearCache(); + TransformPatcher.clearCache(); + ShaderTransformer.init(); + } + + private static int versionOf(String shader) { + final Matcher m = Pattern.compile("#version\\s+(\\d+)").matcher(shader); + assertTrue(m.find(), "no #version in\n\n" + shader); + return Integer.parseInt(m.group(1)); + } + + @Test + void storageImageRewrite_hoistsEmittedVersion() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false))); + try { + final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }"; + final String fragment = String.join("\n", + "#version 330 core", + "uniform usampler3D voxel_sampler;", + "void main(){ gl_FragColor = vec4(float(texelFetch(voxel_sampler, ivec3(0), 0).r)); }", + ""); + + final Map out = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(out); + final String fsh = out.get(PatchShaderType.FRAGMENT); + final String vsh = out.get(PatchShaderType.VERTEX); + + assertTrue(fsh.contains("imageLoad"), "fixture must actually exercise the rewrite\n\n" + fsh); + assertFalse(fsh.contains("usampler3D voxel_sampler"), fsh); + + assertTrue(versionOf(fsh) >= 420, "injected imageLoad needs GLSL 420\n\n" + fsh); + assertEquals(330, versionOf(vsh), "the vertex declares no candidate sampler and must not be inflated\n\n" + vsh); + } finally { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + } + + @Test + void filteredRead_doesNotHoistVersion() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false))); + try { + final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }"; + final String fragment = String.join("\n", + "#version 330 core", + "uniform usampler3D voxel_sampler;", + "void main(){ gl_FragColor = vec4(float(texture(voxel_sampler, vec3(0.5)).r)); }", + ""); + + final Map out = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(out); + final String fsh = out.get(PatchShaderType.FRAGMENT); + + assertTrue(fsh.contains("usampler3D voxel_sampler"), "rewrite must abort on a filtered read\n\n" + fsh); + assertFalse(fsh.contains("imageLoad"), fsh); + assertEquals(330, versionOf(fsh), fsh); + } finally { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + } + + @Test + void noCandidates_versionUnchanged() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }"; + final String fragment = "#version 330 core\nvoid main(){ gl_FragColor = vec4(1.0); }"; + + final Map out = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(out); + assertTrue(out.get(PatchShaderType.VERTEX).startsWith("#version 330 core\n"), out.get(PatchShaderType.VERTEX)); + assertTrue(out.get(PatchShaderType.FRAGMENT).startsWith("#version 330 core\n"), out.get(PatchShaderType.FRAGMENT)); + } + + @Test + void computeStorageImageRewrite_hoistsEmittedVersion() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + SamplerToStorageImageRewriter.setActiveCandidates(Set.of(new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false))); + try { + final String compute = String.join("\n", + "#version 330 core", + "layout(local_size_x = 8) in;", + "uniform usampler3D voxel_sampler;", + "out vec4 unused;", + "void main(){ unused = vec4(float(texelFetch(voxel_sampler, ivec3(gl_GlobalInvocationID), 0).x)); }", + ""); + + final String out = TransformPatcher.patchCompute("shadowcomp", compute, null, null); + assertNotNull(out); + assertTrue(out.contains("imageLoad"), "fixture must actually exercise the rewrite\n\n" + out); + assertTrue(versionOf(out) >= 420, "injected imageLoad needs GLSL 420\n\n" + out); + } finally { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + } + + @Test + void packDeclaredImageTypeHoistsWithoutImageLoad() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + final String vertex = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }"; + final String fragment = String.join("\n", + "#version 330 core", + "layout(r16ui) readonly uniform uimage3D voxel_img;", + "void main(){ gl_FragColor = vec4(float(imageSize(voxel_img).x)); }", + ""); + + final Map out = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(out); + final String fsh = out.get(PatchShaderType.FRAGMENT); + assertTrue(versionOf(fsh) >= 420, "uimage3D declaration alone must hoist to 420\n\n" + fsh); + } + + @Test + void computeIntegerSamplerBecomesStorageImage() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + SamplerToStorageImageRewriter.setActiveCandidates(Set.of( + new SamplerToStorageImageRewriter.Candidate("voxel_sampler", "voxel_img", "r16ui", 3, false))); + try { + final String compute = String.join("\n", + "#version 460 core", + "layout(local_size_x = 8) in;", + "uniform usampler3D voxel_sampler;", + "layout(r16ui) writeonly uniform uimage3D floodfill_img;", + "void main() {", + " uint v = texelFetch(voxel_sampler, ivec3(gl_GlobalInvocationID), 0).x;", + " imageStore(floodfill_img, ivec3(gl_GlobalInvocationID), uvec4(v, 0u, 0u, 0u));", + "}", + ""); + final String out = TransformPatcher.patchCompute("shadowcomp", compute, null, null); + assertNotNull(out); + final String norm = out.replaceAll("\\s+", " "); + assertFalse(norm.contains("usampler3D voxel_sampler"), + "an integer sampler cannot be bound on SDL_GPU and must become a storage image\n\n" + out); + assertTrue(norm.contains("uimage3D voxel_img"), "expected the rewritten storage image\n\n" + out); + assertTrue(norm.contains("imageLoad ( voxel_img"), "texelFetch must become imageLoad\n\n" + out); + } finally { + SamplerToStorageImageRewriter.setActiveCandidates(Set.of()); + } + } + + @Test + void samplerAliasesSurvive_onNonSdlBackend() { + assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this to mean anything"); + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + + final String vertex = "#version 330 core\nvoid main(){gl_Position = vec4(0.0);}"; + final String fragment = String.join("\n", + "#version 330 core", + "uniform sampler2D gtexture;", + "in vec2 uv;", + "void main(){ gl_FragColor = texture2D(gtexture, uv); }", + ""); + + final Map transformed = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(transformed); + final String out = transformed.get(PatchShaderType.FRAGMENT); + assertNotNull(out); + assertTrue(out.contains("gtexture"), "the pack's own sampler name must survive off SDL-GPU\n\n" + out); + } + @Test void transformIsDeterministicUnderConcurrency() throws ExecutionException, InterruptedException { TransformPatcher.clearCache(); diff --git a/src/test/java/net/coderbot/iris/rendertarget/ParityFlipStateTest.java b/src/test/java/net/coderbot/iris/rendertarget/ParityFlipStateTest.java new file mode 100644 index 000000000..73a5bfacd --- /dev/null +++ b/src/test/java/net/coderbot/iris/rendertarget/ParityFlipStateTest.java @@ -0,0 +1,82 @@ +package net.coderbot.iris.rendertarget; + +import com.google.common.collect.ImmutableSet; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ParityFlipStateTest { + + @Test + void paritySetExcludesClearedBuffers() { + ParityFlipState state = new ParityFlipState(true); + state.finalizeParitySet(ImmutableSet.of(1, 2, 7), IntArrayList.of(2)); + assertTrue(state.isEnabled()); + assertEquals(ImmutableSet.of(1, 7), state.parityBuffers()); + } + + @Test + void emptyParitySetDisables() { + ParityFlipState state = new ParityFlipState(true); + state.finalizeParitySet(ImmutableSet.of(2), IntArrayList.of(2)); + assertFalse(state.isEnabled()); + state.onFrameStart(); + assertFalse(state.isOdd()); + } + + @Test + void resolveXorsParityMembersOnOddFramesOnly() { + ParityFlipState state = new ParityFlipState(true); + state.finalizeParitySet(ImmutableSet.of(1, 7), IntArrayList.of()); + + ImmutableSet even = ImmutableSet.of(1, 3); + assertEquals(even, state.resolve(even)); + + state.onFrameStart(); + assertTrue(state.isOdd()); + assertEquals(ImmutableSet.of(3, 7), state.resolve(even)); + + state.onFrameStart(); + assertFalse(state.isOdd()); + assertEquals(even, state.resolve(even)); + } + + @Test + void disabledStateIsIdentity() { + ParityFlipState state = new ParityFlipState(false); + state.finalizeParitySet(ImmutableSet.of(1), IntArrayList.of()); + state.onFrameStart(); + assertFalse(state.isOdd()); + ImmutableSet set = ImmutableSet.of(1, 2); + assertEquals(set, state.resolve(set)); + assertFalse(state.affectsAny(new int[] { 1 })); + } + + @Test + void resetForcesEvenAfterFullClear() { + ParityFlipState state = new ParityFlipState(true); + state.finalizeParitySet(ImmutableSet.of(1), IntArrayList.of()); + state.onFrameStart(); + assertTrue(state.isOdd()); + state.reset(); + assertFalse(state.isOdd()); + } + + @Test + void noToggleBeforeFinalize() { + ParityFlipState state = new ParityFlipState(true); + state.onFrameStart(); + assertFalse(state.isOdd()); + } + + @Test + void affectsAnyChecksDrawBuffers() { + ParityFlipState state = new ParityFlipState(true); + state.finalizeParitySet(ImmutableSet.of(4, 5), IntArrayList.of()); + assertTrue(state.affectsAny(new int[] { 0, 5 })); + assertFalse(state.affectsAny(new int[] { 0, 1, 2 })); + } +} diff --git a/src/test/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvesterTest.java b/src/test/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvesterTest.java new file mode 100644 index 000000000..5374fe1e9 --- /dev/null +++ b/src/test/java/net/coderbot/iris/uniforms/PerFrameUniformBlockHarvesterTest.java @@ -0,0 +1,92 @@ +package net.coderbot.iris.uniforms; + +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import net.coderbot.iris.gl.uniform.ManifestCollectingHolder; +import net.coderbot.iris.gl.uniform.UniformManifest; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PerFrameUniformBlockHarvesterTest { + + private static UniformManifest manifest() { + final ManifestCollectingHolder h = new ManifestCollectingHolder(); + final Vector3fc vec = new Vector3f(); + final Matrix4fc mat = new Matrix4f(); + h.uniform3f(PER_FRAME, "cameraPosition", () -> vec) + .uniform3f(PER_FRAME, "fogColor", () -> vec) + .uniform1f(PER_FRAME, "iris_FogStart", () -> 0.0f) + .uniform1f(PER_FRAME, "iris_FogEnd", () -> 0.0f) + .uniform1f(PER_FRAME, "iris_FogDensity", () -> 0.0f) + .uniformMatrix(PER_FRAME, "gbufferModelView", () -> mat) + .uniformMatrix(PER_FRAME, "gbufferModelViewInverse", () -> mat) + .uniformMatrix(PER_FRAME, "gbufferProjection", () -> mat) + .uniformMatrix(PER_FRAME, "shadowModelView", () -> mat); + return h.build(); + } + + private static List blockNames() { + final PerFrameUniformBlock block = PerFrameUniformBlockHarvester.toBlock(manifest(), manifest()); + return block.members().stream().map(PerFrameUniformBlock.Member::name).toList(); + } + + @Test + void liveStateUniformsAreExcluded() { + final List names = blockNames(); + for (String excluded : List.of("fogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity", "gbufferModelView", "gbufferModelViewInverse", "gbufferProjection")) { + assertFalse(names.contains(excluded), excluded + " reads live per-draw state and must stay on the push path"); + } + } + + @Test + void frameGlobalUniformsAreKept() { + final List names = blockNames(); + assertTrue(names.contains("cameraPosition"), "camera position is frame-scoped"); + assertTrue(names.contains("shadowModelView"), "shadow matrices are pure functions of pack directives"); + } + + @Test + void orderIsDeterministic() { + assertEquals(blockNames(), blockNames()); + } + + private static List perPassNames() { + final PerFrameUniformBlock block = PerFrameUniformBlockHarvester.toPerPassBlock(manifest(), manifest()); + return block.members().stream().map(PerFrameUniformBlock.Member::name).toList(); + } + + @Test + void perPassBlockHoldsExactlyTheLiveStateUniforms() { + assertEquals(List.of("fogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity", "gbufferModelView", "gbufferModelViewInverse", "gbufferProjection"), perPassNames()); + } + + @Test + void blocksAreDisjoint() { + final List perFrame = blockNames(); + for (String name : perPassNames()) { + assertFalse(perFrame.contains(name), name + " must live in exactly one block"); + } + } + + @Test + void noBlockIsHarvestedOffTheSdlBackend() { + assertFalse(BackendManager.RENDER_BACKEND.isSDLGPU(), "test backend must not be SDL-GPU for this guard to mean anything"); + GLSMHooks.perFrameUniformBlock = new PerFrameUniformBlock(List.of()); + GLSMHooks.perPassUniformBlock = new PerFrameUniformBlock(List.of()); + PerFrameUniformBlockHarvester.harvest(null); + assertNull(GLSMHooks.perFrameUniformBlock, "harvest must clear the block on any non-SDL backend"); + assertNull(GLSMHooks.perPassUniformBlock, "harvest must clear the per-pass block on any non-SDL backend"); + } +} diff --git a/src/test/java/net/coderbot/iris/uniforms/PreviousMatrixSharingTest.java b/src/test/java/net/coderbot/iris/uniforms/PreviousMatrixSharingTest.java new file mode 100644 index 000000000..62ee85b0b --- /dev/null +++ b/src/test/java/net/coderbot/iris/uniforms/PreviousMatrixSharingTest.java @@ -0,0 +1,45 @@ +package net.coderbot.iris.uniforms; + +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PreviousMatrixSharingTest { + + private final Matrix4f source = new Matrix4f(); + + @BeforeEach + void resetFrameCounter() { + SystemTimeUniforms.COUNTER.reset(); + } + + @Test + void sameNameSharesOneInstance() { + final MatrixUniforms.Previous a = MatrixUniforms.Previous.shared("testShared", () -> source); + final MatrixUniforms.Previous b = MatrixUniforms.Previous.shared("testShared", () -> source); + assertSame(a, b); + assertNotSame(a, MatrixUniforms.Previous.shared("testSharedOther", () -> source)); + } + + @Test + void advancesOncePerFrameAndReturnsLastFrameValue() { + final MatrixUniforms.Previous prev = new MatrixUniforms.Previous(() -> source); + + source.translation(1f, 0f, 0f); + assertEquals(new Matrix4f(), new Matrix4f(prev.get()), "first frame previous is identity"); + + SystemTimeUniforms.COUNTER.beginFrame(); + source.translation(2f, 0f, 0f); + final Matrix4fc frame2First = new Matrix4f(prev.get()); + assertEquals(new Matrix4f().translation(1f, 0f, 0f), frame2First, "frame 2 sees frame 1 value"); + + source.translation(3f, 0f, 0f); + assertEquals(frame2First, new Matrix4f(prev.get())); + + SystemTimeUniforms.COUNTER.beginFrame(); + assertEquals(new Matrix4f().translation(2f, 0f, 0f), new Matrix4f(prev.get()), "frame 3 sees the value captured at frame 2's first read, not later mid-frame mutations"); + } +} diff --git a/src/test/java/net/coderbot/iris/uniforms/custom/CachedUniformValueGenTest.java b/src/test/java/net/coderbot/iris/uniforms/custom/CachedUniformValueGenTest.java new file mode 100644 index 000000000..d04300420 --- /dev/null +++ b/src/test/java/net/coderbot/iris/uniforms/custom/CachedUniformValueGenTest.java @@ -0,0 +1,68 @@ +package net.coderbot.iris.uniforms.custom; + +import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.coderbot.iris.uniforms.custom.cached.Float3VectorCachedUniform; +import net.coderbot.iris.uniforms.custom.cached.FloatCachedUniform; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class CachedUniformValueGenTest { + + @Test + void floatGenAdvancesOnlyOnChange() { + final float[] value = {5.0f}; + final FloatCachedUniform u = new FloatCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value[0]); + + assertEquals(0, u.valueGen()); + u.update(); + assertEquals(1, u.valueGen(), "initial value differs from the 0-default cache"); + u.update(); + u.update(); + assertEquals(1, u.valueGen(), "unchanged value must not advance the generation"); + value[0] = 6.0f; + u.update(); + assertEquals(2, u.valueGen()); + u.update(); + assertEquals(2, u.valueGen()); + } + + @Test + void vectorGenAdvancesOnlyOnChange() { + final Vector3f value = new Vector3f(1, 2, 3); + final Float3VectorCachedUniform u = new Float3VectorCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value); + + u.update(); + final int afterFirst = u.valueGen(); + u.update(); + assertEquals(afterFirst, u.valueGen(), "same vector content must not advance"); + value.set(1, 2, 4); + u.update(); + assertEquals(afterFirst + 1, u.valueGen()); + } + + @Test + void perPassGenComparisonSkipsAndCatchesUp() { + final float[] value = {1.0f}; + final FloatCachedUniform u = new FloatCachedUniform("test", UniformUpdateFrequency.CUSTOM, () -> value[0]); + + int passA = -1; + int passB = -1; + + u.update(); + assertNotEquals(passA, u.valueGen(), "fresh pass must push even for gen 1"); + passA = u.valueGen(); + + u.update(); + assertEquals(passA, u.valueGen(), "unchanged next frame skips for the caught-up pass"); + assertNotEquals(passB, u.valueGen(), "a pass that never pushed still pushes despite no change this frame"); + passB = u.valueGen(); + + value[0] = 2.0f; + u.update(); + assertNotEquals(passA, u.valueGen()); + assertNotEquals(passB, u.valueGen()); + } +} diff --git a/tracy-client/build.gradle.kts b/tracy-client/build.gradle.kts new file mode 100644 index 000000000..6f1339729 --- /dev/null +++ b/tracy-client/build.gradle.kts @@ -0,0 +1,152 @@ +plugins { + `java-library` + `maven-publish` +} + +version = rootProject.version + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(21)) + withSourcesJar() +} + +val rfgObfAttr = Attribute.of("com.gtnewhorizons.retrofuturagradle.obfuscation", String::class.java) +val rfgTransformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean::class.javaObjectType) + +configurations { + listOf("apiElements", "runtimeElements").forEach { name -> + named(name) { + attributes { + attribute(rfgObfAttr, "mcp") + attribute(rfgTransformedAttr, true) + } + } + } +} + +val lwjglNatives: String by extra +val tracyVersion = libs.versions.tracy.get() + +repositories { + mavenLocal() + maven { + name = "GTNH Maven" + url = uri("https://nexus.gtnewhorizons.com/repository/public/") + } + maven { + name = "Minecraft Libraries" + url = uri("https://libraries.minecraft.net") + } + maven { + name = "Forge" + url = uri("https://maven.minecraftforge.net/") + } + maven { + name = "Forge artifact-only" + url = uri("https://maven.minecraftforge.net/") + metadataSources { artifact() } + content { includeModule("net.minecraftforge", "forge") } + } + maven { + name = "taumc" + url = uri("https://maven.taumc.org/releases") + } + maven { + name = "Sonatype Snapshots" + url = uri("https://oss.sonatype.org/content/repositories/snapshots/") + } + maven { + name = "Maven Central Snapshots" + url = uri("https://central.sonatype.com/repository/maven-snapshots/") + } + mavenCentral() +} + +dependencies { + api(project(":glsm")) + + compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false } + compileOnly("net.minecraftforge:forge:1.7.10-10.13.4.1614-1.7.10:universal") { isTransitive = false } + + implementation(libs.lwjgl3) + + compileOnly(libs.log4j.api) + compileOnly(libs.annotations) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) + testRuntimeOnly(libs.lwjgl3) { artifact { classifier = lwjglNatives } } + testImplementation(libs.log4j.api) + testRuntimeOnly(libs.log4j.core) +} + +val generateTracyTags = tasks.register("generateTracyTags") { + val version = tracyVersion + val outDir = layout.buildDirectory.dir("generated/sources/tracyTags") + inputs.property("tracyVersion", version) + outputs.dir(outDir) + doLast { + val file = outDir.get().file("com/gtnewhorizons/angelica/tracy/TracyTags.java").asFile + file.parentFile.mkdirs() + file.writeText( + """ + package com.gtnewhorizons.angelica.tracy; + + // Generated from the version catalog; do not edit + public final class TracyTags { + private TracyTags() {} + public static final String TRACY_VERSION = "$version"; + } + """.trimIndent() + "\n" + ) + } +} +sourceSets["main"].java.srcDir(generateTracyTags) + +tasks.test { + useJUnitPlatform() +} + +tasks.named("jar") { + manifest { + attributes( + "Lwjgl3ify-Aware" to "true" + ) + } +} + +val distJar = tasks.register("distJar") { + archiveBaseName.set("angelica-tracy") + archiveVersion.set(tracyVersion) + from(sourceSets["main"].output) + manifest { + attributes( + "Lwjgl3ify-Aware" to "true", + "FMLCorePlugin" to "com.gtnewhorizons.angelica.tracy.loading.TracyCorePlugin" + ) + } +} + +publishing { + publications { + create("mavenJava") { + groupId = "com.gtnewhorizons.angelica" + artifactId = "angelica-tracy" + version = tracyVersion + artifact(distJar) + } + } + repositories { + if (System.getenv("MAVEN_USER") != null) { + maven { + name = "GTNHMaven" + url = uri(rootProject.findProperty("mavenPublishUrl")?.toString() ?: "https://nexus.gtnewhorizons.com/repository/releases/") + credentials { + username = System.getenv("MAVEN_USER") + password = System.getenv("MAVEN_PASSWORD") + } + } + } + } +} diff --git a/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/SrcLocInterner.java b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/SrcLocInterner.java new file mode 100644 index 000000000..fa69674c3 --- /dev/null +++ b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/SrcLocInterner.java @@ -0,0 +1,37 @@ +package com.gtnewhorizons.angelica.tracy; + +import java.util.concurrent.ConcurrentHashMap; + +final class SrcLocInterner { + interface NativeOps { + long allocSrcLoc(String name, int color); + } + + static final String DYNAMIC_NAME = ""; + + private final ConcurrentHashMap interned = new ConcurrentHashMap<>(); + private final NativeOps ops; + private final int cap; + private final long dynamic; + + SrcLocInterner(NativeOps ops, int cap) { + this.ops = ops; + this.cap = cap; + this.dynamic = ops.allocSrcLoc(DYNAMIC_NAME, 0); + } + + long dynamicSrcLoc() { + return dynamic; + } + + long intern(String name, int color) { + final Long existing = interned.get(name); + if (existing != null) return existing; + if (interned.size() >= cap) return dynamic; + return interned.computeIfAbsent(name, n -> ops.allocSrcLoc(n, color)); + } + + int size() { + return interned.size(); + } +} diff --git a/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyClientBackend.java b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyClientBackend.java new file mode 100644 index 000000000..d1b8cc897 --- /dev/null +++ b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyClientBackend.java @@ -0,0 +1,379 @@ +package com.gtnewhorizons.angelica.tracy; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; +import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend; +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.JNI; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.Pointer; +import org.lwjgl.system.SharedLibrary; +import org.lwjgl.system.libffi.FFICIF; +import org.lwjgl.system.libffi.FFIType; +import org.lwjgl.system.libffi.LibFFI; + +import java.nio.ByteBuffer; +import java.nio.DoubleBuffer; +import java.nio.LongBuffer; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.NULL; +import static org.lwjgl.system.MemoryUtil.memAddress; +import static org.lwjgl.system.MemoryUtil.memPutAddress; +import static org.lwjgl.system.MemoryUtil.memPutByte; +import static org.lwjgl.system.MemoryUtil.memPutInt; +import static org.lwjgl.system.MemoryUtil.nmemAllocChecked; + +@Lwjgl3Aware +public final class TracyClientBackend implements TracyBackend { + private static final Logger LOGGER = LogManager.getLogger("Tracy"); + private static final int MAX_TEXT = 8192; + + private SharedLibrary lib; + private TracyLibrary sym; + private SrcLocInterner interner; + private long emptyString; + private FFICIF plotCif; + + @Override + public boolean init() { + try { + if (Pointer.POINTER_SIZE != 8) { + LOGGER.warn("Tracy: 64-bit JVM required"); + return false; + } + lib = TracyNativeLoader.load(); + if (lib == null) return false; + sym = TracyLibrary.resolve(lib); + if (sym == null) return false; + + emptyString = nmemAllocChecked(1); + memPutByte(emptyString, (byte) 0); + + final PointerBuffer plotArgTypes = MemoryUtil.memAllocPointer(2); + plotArgTypes.put(0, LibFFI.ffi_type_pointer.address()).put(1, LibFFI.ffi_type_double.address()); + plotCif = FFICIF.malloc(); + final int status = LibFFI.ffi_prep_cif(plotCif, LibFFI.FFI_DEFAULT_ABI, LibFFI.ffi_type_void, plotArgTypes); + if (status != LibFFI.FFI_OK) { + LOGGER.warn("Tracy: ffi_prep_cif failed: {}", status); + return false; + } + + interner = new SrcLocInterner(this::allocSrcLoc, SystemProperties.TRACY_MAX_SRC_LOCS); + + JNI.invokeV(sym.startupProfiler); + if (JNI.invokeI(sym.profilerStarted) == 0) { + LOGGER.warn("Tracy: profiler failed to start"); + return false; + } + appInfo("Angelica Tracy profiling (MC 1.7.10, Tracy " + TracyNativeLoader.TRACY_VERSION + ")"); + LOGGER.info("Tracy: client started (Tracy {}, lib {})", TracyNativeLoader.TRACY_VERSION, lib.getPath()); + return true; + } catch (Throwable t) { + LOGGER.warn("Tracy: init failed: {}", t.toString()); + return false; + } + } + + private long allocSrcLoc(String name, int color) { + final ByteBuffer nameUtf8 = MemoryUtil.memUTF8(name); + final long srcLoc = nmemAllocChecked(32); + memPutAddress(srcLoc, memAddress(nameUtf8)); + memPutAddress(srcLoc + 8, emptyString); + memPutAddress(srcLoc + 16, emptyString); + memPutInt(srcLoc + 24, 0); + memPutInt(srcLoc + 28, color); + return srcLoc; + } + + @Override + public long internSrcLoc(String name, int color) { + return interner.intern(name, color); + } + + @Override + public long dynamicSrcLoc() { + return interner.dynamicSrcLoc(); + } + + @Override + public long beginZone(long srcLoc) { + return JNI.invokePJ(srcLoc, 1, sym.zoneBegin); + } + + @Override + public void endZone(long ctx) { + JNI.invokeJV(ctx, sym.zoneEnd); + } + + @Override + public void zoneText(long ctx, String text) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer utf8 = stack.UTF8(truncate(text), false); + JNI.invokeJPPV(ctx, memAddress(utf8), utf8.remaining(), sym.zoneText); + } + } + + @Override + public void zoneValue(long ctx, long value) { + JNI.invokePJV(ctx, value, sym.zoneValue); + } + + @Override + public void frameMark() { + JNI.invokePV(NULL, sym.frameMark); + } + + @Override + public long internFrameName(String name) { + return memAddress(MemoryUtil.memUTF8(name)); + } + + @Override + public void frameMark(long namePtr) { + JNI.invokePV(namePtr, sym.frameMark); + } + + @Override + public long internPlotName(String name, int format) { + final long namePtr = memAddress(MemoryUtil.memUTF8(name)); + JNI.invokePV(namePtr, format, 0, 1, 0, sym.plotConfig); + return namePtr; + } + + @Override + public void plotInt(long namePtr, long value) { + JNI.invokePJV(namePtr, value, sym.plotInt); + } + + @Override + public void plot(long namePtr, double value) { + try (MemoryStack stack = stackPush()) { + final LongBuffer arg0 = stack.longs(namePtr); + final DoubleBuffer arg1 = stack.doubles(value); + final PointerBuffer args = stack.pointers(memAddress(arg0), memAddress(arg1)); + LibFFI.ffi_call(plotCif, sym.plot, null, args); + } + } + + @Override + public void message(String text) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer utf8 = stack.UTF8(truncate(text), false); + JNI.invokePPV(memAddress(utf8), (long) utf8.remaining(), 0, sym.message); + } + } + + private void appInfo(String text) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer utf8 = stack.UTF8(text, false); + JNI.invokePPV(memAddress(utf8), utf8.remaining(), sym.messageAppinfo); + } + } + + @Override + public void setCurrentThreadName(String name) { + try (MemoryStack stack = stackPush()) { + JNI.invokePV(memAddress(stack.UTF8(name, true)), sym.setThreadName); + } + } + + @Override + public boolean isConnected() { + return JNI.invokeI(sym.connected) != 0; + } + + @Override + public void shutdown() { + JNI.invokeV(sym.shutdownProfiler); + } + + private static String truncate(String text) { + return text.length() > MAX_TEXT ? text.substring(0, MAX_TEXT) : text; + } + + /* + * GPU zones: port of TracyOpenGL.hpp GpuCtx (v0.13.1). + */ + private static final int GPU_QUERY_COUNT = 16 * 1024; + private static final byte GPU_CONTEXT_ID = 0; + private static final byte GPU_CONTEXT_TYPE_OPENGL = 1; + + private RenderBackend renderBackend; + private int[] gpuQueries; + private int gpuHead; + private int gpuTail; + private int gpuPendingEnds; + private boolean gpuInitAttempted; + private boolean gpuReady; + private int gpuCollectsSinceSync; + private FFICIF gpuZoneBeginCif; + private FFICIF gpuZoneEndCif; + private FFICIF gpuTimeCif; + private FFICIF gpuTimeSyncCif; + private FFICIF gpuNewContextCif; + private FFICIF gpuContextNameCif; + + @Override + public boolean gpuInit() { + if (gpuInitAttempted) return gpuReady; + gpuInitAttempted = true; + try { + final RenderBackend rb = BackendManager.RENDER_BACKEND; + if (!rb.supportsGpuProfiling()) { + LOGGER.info("Tracy: GPU zones unavailable (render backend has no timer queries)"); + return false; + } + prepGpuCifs(); + renderBackend = rb; + gpuQueries = new int[GPU_QUERY_COUNT]; + emitGpuNewContext(rb.getGpuTimestamp()); + emitGpuContextName("OpenGL"); + gpuReady = true; + LOGGER.info("Tracy: GPU zones enabled"); + } catch (Throwable t) { + LOGGER.warn("Tracy: GPU init failed: {}", t.toString()); + } + return gpuReady; + } + + void prepGpuCifs() { + if (gpuZoneBeginCif != null) return; + gpuZoneBeginCif = prepStructCif(LibFFI.ffi_type_uint64, LibFFI.ffi_type_uint16, LibFFI.ffi_type_uint8); + gpuZoneEndCif = prepStructCif(LibFFI.ffi_type_uint16, LibFFI.ffi_type_uint8); + gpuTimeCif = prepStructCif(LibFFI.ffi_type_sint64, LibFFI.ffi_type_uint16, LibFFI.ffi_type_uint8); + gpuTimeSyncCif = prepStructCif(LibFFI.ffi_type_sint64, LibFFI.ffi_type_uint8); + gpuNewContextCif = prepStructCif(LibFFI.ffi_type_sint64, LibFFI.ffi_type_float, LibFFI.ffi_type_uint8, LibFFI.ffi_type_uint8, LibFFI.ffi_type_uint8); + gpuContextNameCif = prepStructCif(LibFFI.ffi_type_uint8, LibFFI.ffi_type_pointer, LibFFI.ffi_type_uint16); + } + + void emitGpuNewContext(long gpuTime) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer data = stack.calloc(16); + data.putLong(0, gpuTime); + data.putFloat(8, 1.0f); + data.put(12, GPU_CONTEXT_ID); + data.put(13, (byte) 0); + data.put(14, GPU_CONTEXT_TYPE_OPENGL); + LibFFI.ffi_call(gpuNewContextCif, sym.gpuNewContext, null, stack.pointers(memAddress(data))); + } + } + + void emitGpuContextName(String name) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer utf8 = stack.UTF8(name, false); + final ByteBuffer data = stack.calloc(24); + data.put(0, GPU_CONTEXT_ID); + data.putLong(8, memAddress(utf8)); + data.putShort(16, (short) utf8.remaining()); + LibFFI.ffi_call(gpuContextNameCif, sym.gpuContextName, null, stack.pointers(memAddress(data))); + } + } + + void emitGpuZoneBegin(long srcLoc, int queryId) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer data = stack.calloc(16); + data.putLong(0, srcLoc); + data.putShort(8, (short) queryId); + data.put(10, GPU_CONTEXT_ID); + LibFFI.ffi_call(gpuZoneBeginCif, sym.gpuZoneBegin, null, stack.pointers(memAddress(data))); + } + } + + void emitGpuZoneEnd(int queryId) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer data = stack.calloc(4); + data.putShort(0, (short) queryId); + data.put(2, GPU_CONTEXT_ID); + LibFFI.ffi_call(gpuZoneEndCif, sym.gpuZoneEnd, null, stack.pointers(memAddress(data))); + } + } + + void emitGpuTime(long gpuTime, int queryId) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer data = stack.calloc(16); + data.putLong(0, gpuTime); + data.putShort(8, (short) queryId); + data.put(10, GPU_CONTEXT_ID); + LibFFI.ffi_call(gpuTimeCif, sym.gpuTime, null, stack.pointers(memAddress(data))); + } + } + + void emitGpuTimeSync(long gpuTime) { + try (MemoryStack stack = stackPush()) { + final ByteBuffer data = stack.calloc(16); + data.putLong(0, gpuTime); + data.put(8, GPU_CONTEXT_ID); + LibFFI.ffi_call(gpuTimeSyncCif, sym.gpuTimeSync, null, stack.pointers(memAddress(data))); + } + } + + /** Test seam: exercises every GPU struct-by-value FFI marshalling path without GL. */ + private static FFICIF prepStructCif(FFIType... members) { + final PointerBuffer elements = MemoryUtil.memAllocPointer(members.length + 1); + for (int i = 0; i < members.length; i++) elements.put(i, members[i].address()); + elements.put(members.length, NULL); + final FFIType struct = FFIType.calloc().type((short) LibFFI.FFI_TYPE_STRUCT).elements(elements); + final PointerBuffer argTypes = MemoryUtil.memAllocPointer(1); + argTypes.put(0, struct.address()); + final FFICIF cif = FFICIF.malloc(); + final int status = LibFFI.ffi_prep_cif(cif, LibFFI.FFI_DEFAULT_ABI, LibFFI.ffi_type_void, argTypes); + if (status != LibFFI.FFI_OK) throw new IllegalStateException("ffi_prep_cif (gpu struct) failed: " + status); + return cif; + } + + private int nextGpuQuery() { + final int id = gpuHead; + gpuHead = (gpuHead + 1) % GPU_QUERY_COUNT; + int query = gpuQueries[id]; + if (query == 0) { + query = renderBackend.genQuery(); + gpuQueries[id] = query; + } + renderBackend.queryCounter(query); + return id; + } + + @Override + public boolean gpuBeginZone(long srcLoc) { + if (!gpuReady || !isConnected()) return false; + final int inFlight = (gpuHead - gpuTail + GPU_QUERY_COUNT) % GPU_QUERY_COUNT; + if (GPU_QUERY_COUNT - 1 - inFlight < gpuPendingEnds + 2) return false; + final int queryId = nextGpuQuery(); + emitGpuZoneBegin(srcLoc, queryId); + gpuPendingEnds++; + return true; + } + + @Override + public void gpuEndZone() { + if (!gpuReady || gpuPendingEnds == 0) return; + gpuPendingEnds--; + emitGpuZoneEnd(nextGpuQuery()); + } + + @Override + public void gpuCollect() { + if (!gpuReady) return; + if (!isConnected()) { + gpuHead = 0; + gpuTail = 0; + return; + } + if (++gpuCollectsSinceSync >= 100) { + gpuCollectsSinceSync = 0; + emitGpuTimeSync(renderBackend.getGpuTimestamp()); + } + while (gpuTail != gpuHead) { + final int query = gpuQueries[gpuTail]; + if (!renderBackend.isQueryResultAvailable(query)) return; + emitGpuTime(renderBackend.getQueryResult64(query), gpuTail); + gpuTail = (gpuTail + 1) % GPU_QUERY_COUNT; + } + } +} diff --git a/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyLibrary.java b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyLibrary.java new file mode 100644 index 000000000..3bd3da842 --- /dev/null +++ b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyLibrary.java @@ -0,0 +1,74 @@ +package com.gtnewhorizons.angelica.tracy; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.system.SharedLibrary; + +import static org.lwjgl.system.MemoryUtil.NULL; + +@Lwjgl3Aware +final class TracyLibrary { + private static final Logger LOGGER = LogManager.getLogger("Tracy"); + + final long startupProfiler; + final long shutdownProfiler; + final long profilerStarted; + final long connected; + final long zoneBegin; + final long zoneEnd; + final long zoneText; + final long zoneValue; + final long frameMark; + final long plot; + final long plotInt; + final long plotConfig; + final long message; + final long messageAppinfo; + final long setThreadName; + final long gpuZoneBegin; + final long gpuZoneEnd; + final long gpuTime; + final long gpuTimeSync; + final long gpuNewContext; + final long gpuContextName; + + static TracyLibrary resolve(SharedLibrary lib) { + try { + return new TracyLibrary(lib); + } catch (IllegalStateException e) { + LOGGER.warn("Tracy: {}", e.getMessage()); + return null; + } + } + + private TracyLibrary(SharedLibrary lib) { + startupProfiler = req(lib, "___tracy_startup_profiler"); + shutdownProfiler = req(lib, "___tracy_shutdown_profiler"); + profilerStarted = req(lib, "___tracy_profiler_started"); + connected = req(lib, "___tracy_connected"); + zoneBegin = req(lib, "___tracy_emit_zone_begin"); + zoneEnd = req(lib, "___tracy_emit_zone_end"); + zoneText = req(lib, "___tracy_emit_zone_text"); + zoneValue = req(lib, "___tracy_emit_zone_value"); + frameMark = req(lib, "___tracy_emit_frame_mark"); + plot = req(lib, "___tracy_emit_plot"); + plotInt = req(lib, "___tracy_emit_plot_int"); + plotConfig = req(lib, "___tracy_emit_plot_config"); + message = req(lib, "___tracy_emit_message"); + messageAppinfo = req(lib, "___tracy_emit_message_appinfo"); + setThreadName = req(lib, "___tracy_set_thread_name"); + gpuZoneBegin = req(lib, "___tracy_emit_gpu_zone_begin"); + gpuZoneEnd = req(lib, "___tracy_emit_gpu_zone_end"); + gpuTime = req(lib, "___tracy_emit_gpu_time"); + gpuTimeSync = req(lib, "___tracy_emit_gpu_time_sync"); + gpuNewContext = req(lib, "___tracy_emit_gpu_new_context"); + gpuContextName = req(lib, "___tracy_emit_gpu_context_name"); + } + + private static long req(SharedLibrary lib, String name) { + final long address = lib.getFunctionAddress(name); + if (address == NULL) throw new IllegalStateException("missing symbol " + name + " in " + lib.getPath()); + return address; + } +} diff --git a/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyNativeLoader.java b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyNativeLoader.java new file mode 100644 index 000000000..add4a6f9a --- /dev/null +++ b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/TracyNativeLoader.java @@ -0,0 +1,94 @@ +package com.gtnewhorizons.angelica.tracy; + +import com.gtnewhorizons.angelica.config.SystemProperties; +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.system.APIUtil; +import org.lwjgl.system.SharedLibrary; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; + +@Lwjgl3Aware +final class TracyNativeLoader { + private static final Logger LOGGER = LogManager.getLogger("Tracy"); + static final String TRACY_VERSION = TracyTags.TRACY_VERSION; + + private enum OS { + WINDOWS, MACOS, LINUX; + + static OS detect(String osName) { + if (osName.contains("windows")) return WINDOWS; + if (osName.contains("mac")) return MACOS; + if (osName.contains("linux")) return LINUX; + return null; + } + } + + private TracyNativeLoader() {} + + static SharedLibrary load() { + final OS os = OS.detect(System.getProperty("os.name", "").toLowerCase()); + final String arch = System.getProperty("os.arch", "").toLowerCase(); + final boolean arm64 = arch.contains("aarch64") || arch.contains("arm64"); + if (os == null || (arm64 && os != OS.MACOS)) { + LOGGER.warn("Tracy: unsupported platform {}/{}", System.getProperty("os.name"), System.getProperty("os.arch")); + return null; + } + final String platform = os.name().toLowerCase() + (arm64 ? "-arm64" : "-x64"); + final String libName = switch (os) { + case WINDOWS -> "TracyClient.dll"; + case MACOS -> "libTracyClient.dylib"; + case LINUX -> "libTracyClient.so"; + }; + final String resource = "/natives/tracy/" + platform + "/" + libName; + + final byte[] lib; + try (InputStream in = TracyNativeLoader.class.getResourceAsStream(resource)) { + if (in == null) { + LOGGER.warn("Tracy: native resource {} not present in jar", resource); + return null; + } + lib = readAll(in); + } catch (IOException e) { + LOGGER.warn("Tracy: failed reading native resource {}: {}", resource, e.toString()); + return null; + } + + final String ext = libName.substring(libName.lastIndexOf('.') + 1); + final File dir = new File(SystemProperties.TRACY_DIR); + final File target = new File(dir, "libTracyClient-" + TRACY_VERSION + "-" + platform + "." + ext); + try { + if (!target.isFile() || target.length() != lib.length || !Arrays.equals(Files.readAllBytes(target.toPath()), lib)) { + if (!dir.isDirectory() && !dir.mkdirs()) throw new IOException("cannot create " + dir); + final File tmp = File.createTempFile("libTracyClient", "." + ext, dir); + Files.write(tmp.toPath(), lib); + Files.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException e) { + LOGGER.warn("Tracy: failed extracting native to {}: {}", target, e.toString()); + return null; + } + + try { + return APIUtil.apiCreateLibrary(target.getAbsolutePath()); + } catch (Throwable t) { + LOGGER.warn("Tracy: failed loading {}: {}", target, t.toString()); + return null; + } + } + + private static byte[] readAll(InputStream in) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(1 << 20); + final byte[] buf = new byte[16384]; + int n; + while ((n = in.read(buf)) > 0) out.write(buf, 0, n); + return out.toByteArray(); + } +} diff --git a/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/loading/TracyCorePlugin.java b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/loading/TracyCorePlugin.java new file mode 100644 index 000000000..756a90baa --- /dev/null +++ b/tracy-client/src/main/java/com/gtnewhorizons/angelica/tracy/loading/TracyCorePlugin.java @@ -0,0 +1,33 @@ +package com.gtnewhorizons.angelica.tracy.loading; + +import cpw.mods.fml.relauncher.IFMLLoadingPlugin; + +import java.util.Map; + +/// Empty coremod to force early loading +@IFMLLoadingPlugin.MCVersion("1.7.10") +public class TracyCorePlugin implements IFMLLoadingPlugin { + + @Override + public String[] getASMTransformerClass() { + return null; + } + + @Override + public String getModContainerClass() { + return null; + } + + @Override + public String getSetupClass() { + return null; + } + + @Override + public void injectData(Map data) {} + + @Override + public String getAccessTransformerClass() { + return null; + } +} diff --git a/tracy-client/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.profiling.TracyBackend b/tracy-client/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.profiling.TracyBackend new file mode 100644 index 000000000..e1f0a9fcb --- /dev/null +++ b/tracy-client/src/main/resources/META-INF/services/com.gtnewhorizons.angelica.glsm.profiling.TracyBackend @@ -0,0 +1 @@ +com.gtnewhorizons.angelica.tracy.TracyClientBackend diff --git a/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/SrcLocInternerTest.java b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/SrcLocInternerTest.java new file mode 100644 index 000000000..17e2a0dae --- /dev/null +++ b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/SrcLocInternerTest.java @@ -0,0 +1,85 @@ +package com.gtnewhorizons.angelica.tracy; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SrcLocInternerTest { + + static final class RecordingOps implements SrcLocInterner.NativeOps { + final ConcurrentHashMap allocCounts = new ConcurrentHashMap<>(); + final AtomicLong nextAddress = new AtomicLong(0x1000); + + @Override + public long allocSrcLoc(String name, int color) { + allocCounts.merge(name, 1, Integer::sum); + return nextAddress.getAndAdd(32); + } + } + + @Test + void internDedupes() { + final RecordingOps ops = new RecordingOps(); + final SrcLocInterner interner = new SrcLocInterner(ops, 16); + final long a = interner.intern("root", 0); + final long b = interner.intern("root", 0); + assertEquals(a, b); + assertEquals(1, ops.allocCounts.get("root")); + assertNotEquals(a, interner.dynamicSrcLoc()); + } + + @Test + void capFallsBackToDynamicSrcLoc() { + final RecordingOps ops = new RecordingOps(); + final SrcLocInterner interner = new SrcLocInterner(ops, 4); + for (int i = 0; i < 4; i++) { + assertNotEquals(interner.dynamicSrcLoc(), interner.intern("zone" + i, 0)); + } + assertEquals(interner.dynamicSrcLoc(), interner.intern("overflow", 0)); + assertEquals(4, interner.size()); + assertEquals(interner.intern("zone2", 0), interner.intern("zone2", 0)); + } + + @Test + void concurrentInternAllocatesOncePerName() throws Exception { + final RecordingOps ops = new RecordingOps(); + final SrcLocInterner interner = new SrcLocInterner(ops, 1024); + final int threads = 8; + final CountDownLatch start = new CountDownLatch(1); + final List workers = new ArrayList<>(); + final long[][] results = new long[threads][64]; + for (int t = 0; t < threads; t++) { + final int ti = t; + final Thread worker = new Thread(() -> { + try { + start.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + for (int i = 0; i < 64; i++) { + results[ti][i] = interner.intern("zone" + i, 0); + } + }); + worker.start(); + workers.add(worker); + } + start.countDown(); + for (Thread worker : workers) worker.join(10_000); + + for (int i = 0; i < 64; i++) { + for (int t = 1; t < threads; t++) { + assertEquals(results[0][i], results[t][i], "zone" + i); + } + assertEquals(1, ops.allocCounts.get("zone" + i), "zone" + i); + } + assertTrue(interner.size() <= 64); + } +} diff --git a/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/TracyBindingSmokeTest.java b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/TracyBindingSmokeTest.java new file mode 100644 index 000000000..34220f58e --- /dev/null +++ b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/TracyBindingSmokeTest.java @@ -0,0 +1,159 @@ +package com.gtnewhorizons.angelica.tracy; + +import com.gtnewhorizon.gtnhlib.reflect.Fields; +import com.gtnewhorizon.gtnhlib.reflect.Fields.LookupType; +import com.gtnewhorizons.angelica.config.SystemProperties; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.condition.EnabledIf; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnabledIf("nativePresent") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TracyBindingSmokeTest { + + @TempDir + static Path extractDir; + + private static TracyClientBackend backend; + + static boolean nativePresent() { + for (String platform : new String[] {"windows-x64", "linux-x64", "macos-x64", "macos-arm64"}) { + for (String lib : new String[] {"TracyClient.dll", "libTracyClient.so", "libTracyClient.dylib"}) { + if (TracyBindingSmokeTest.class.getResource("/natives/tracy/" + platform + "/" + lib) != null) { + return true; + } + } + } + return false; + } + + private static synchronized TracyClientBackend backend() throws Exception { + if (backend == null) { + Fields.ofClass(SystemProperties.class).getField(LookupType.DECLARED, "TRACY_DIR", String.class).setValue(null, extractDir.toAbsolutePath().toString()); + final TracyClientBackend created = new TracyClientBackend(); + final AtomicReference ok = new AtomicReference<>(Boolean.FALSE); + final Thread init = new Thread(() -> ok.set(created.init()), "Tracy-Init-Test"); + init.setDaemon(true); + init.start(); + init.join(15_000); + assertTrue(ok.get(), "backend init failed"); + backend = created; + } + return backend; + } + + @Test + @Order(1) + void internAndSingleZone() throws Exception { + final TracyClientBackend b = backend(); + final long srcLoc = b.internSrcLoc("smoke", 0); + assertNotEquals(0, srcLoc); + assertEquals(srcLoc, b.internSrcLoc("smoke", 0)); + + final long ctx = b.beginZone(srcLoc); + b.zoneText(ctx, "hello from java"); + b.zoneValue(ctx, 1234567890123L); + b.endZone(ctx); + } + + @Test + @Order(2) + void hammerZonesAcrossThreads() throws Exception { + final TracyClientBackend b = backend(); + final int threads = 4; + final int iterations = 10_000; + final CountDownLatch start = new CountDownLatch(1); + final List workers = new ArrayList<>(); + final AtomicReference failure = new AtomicReference<>(); + for (int t = 0; t < threads; t++) { + final int ti = t; + final Thread worker = new Thread(() -> { + try { + start.await(); + b.setCurrentThreadName("smoke-worker-" + ti); + final long outer = b.internSrcLoc("outer-" + ti, 0); + final long inner = b.internSrcLoc("inner-" + ti, 0); + for (int i = 0; i < iterations; i++) { + final long outerCtx = b.beginZone(outer); + final long innerCtx = b.beginZone(inner); + if ((i & 1023) == 0) b.zoneText(innerCtx, "iter " + i); + b.endZone(innerCtx); + b.endZone(outerCtx); + } + } catch (Throwable e) { + failure.set(e); + } + }, "smoke-worker-" + ti); + worker.start(); + workers.add(worker); + } + start.countDown(); + for (Thread worker : workers) worker.join(60_000); + if (failure.get() != null) throw new AssertionError(failure.get()); + } + + @Test + @Order(3) + void plotsMessagesAndFrameMarks() throws Exception { + final TracyClientBackend b = backend(); + final long plotName = b.internPlotName("smokePlot", 0); + assertNotEquals(0, plotName); + final long frameName = b.internFrameName("smoke tick"); + assertNotEquals(0, frameName); + for (int i = 0; i < 100; i++) { + b.plotInt(plotName, i); + b.plot(plotName, i * 0.5); + b.frameMark(); + b.frameMark(frameName); + } + b.message("smoke test message"); + b.isConnected(); + } + + @Test + @Order(4) + void dynamicSrcLocOverflowPath() throws Exception { + final TracyClientBackend b = backend(); + final long dynamic = b.dynamicSrcLoc(); + assertNotEquals(0, dynamic); + final long ctx = b.beginZone(dynamic); + b.zoneText(ctx, "overflow-name"); + b.endZone(ctx); + } + + @Test + @Order(5) + void gpuEmitStructMarshalling() throws Exception { + final TracyClientBackend b = backend(); + final long srcLoc = b.internSrcLoc("gpu-smoke", 0); + b.prepGpuCifs(); + b.emitGpuNewContext(0); + b.emitGpuContextName("SelfTest"); + b.emitGpuZoneBegin(srcLoc, 0); + b.emitGpuZoneEnd(1); + b.emitGpuTime(1000, 0); + b.emitGpuTime(2000, 1); + b.emitGpuTimeSync(3000); + } + + @Test + @Order(6) + void shutdownFlushes() throws Exception { + backend().shutdown(); + } +} diff --git a/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/ZoneStackTest.java b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/ZoneStackTest.java new file mode 100644 index 000000000..1c9c7fdb5 --- /dev/null +++ b/tracy-client/src/test/java/com/gtnewhorizons/angelica/tracy/ZoneStackTest.java @@ -0,0 +1,131 @@ +package com.gtnewhorizons.angelica.tracy; + +import com.gtnewhorizons.angelica.glsm.profiling.ZoneStack; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ZoneStackTest { + + @Test + void lifoBalance() { + final ZoneStack stack = new ZoneStack(); + assertTrue(stack.push(1)); + assertTrue(stack.push(2)); + assertEquals(2, stack.peek()); + assertEquals(2, stack.pop()); + assertEquals(1, stack.pop()); + assertEquals(0, stack.depth()); + } + + @Test + void popOnEmptyIsSilentNoOp() { + final ZoneStack stack = new ZoneStack(); + assertEquals(ZoneStack.EMPTY, stack.pop()); + assertEquals(ZoneStack.EMPTY, stack.peek()); + assertTrue(stack.push(7)); + assertEquals(7, stack.pop()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + } + + @Test + void growsPastInitialCapacity() { + final ZoneStack stack = new ZoneStack(); + for (long i = 0; i < 256; i++) assertTrue(stack.push(i)); + for (long i = 255; i >= 0; i--) assertEquals(i, stack.pop()); + } + + @Test + void gpuFlagFollowsPop() { + final ZoneStack stack = new ZoneStack(); + assertTrue(stack.push(1, true)); + assertTrue(stack.push(2, false)); + assertTrue(stack.push(3, true)); + assertEquals(3, stack.pop()); + assertTrue(stack.poppedGpu()); + assertEquals(2, stack.pop()); + assertFalse(stack.poppedGpu()); + assertEquals(1, stack.pop()); + assertTrue(stack.poppedGpu()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + assertFalse(stack.poppedGpu()); + } + + @Test + void atCapReflectsDepth() { + final ZoneStack stack = new ZoneStack(); + assertFalse(stack.atCap()); + for (long i = 0; i < 512; i++) stack.push(i); + assertTrue(stack.atCap()); + stack.pop(); + assertFalse(stack.atCap()); + } + + @Test + void overflowSkipsAndPreservesPairing() { + final ZoneStack stack = new ZoneStack(); + for (long i = 0; i < 512; i++) assertTrue(stack.push(i)); + assertFalse(stack.push(9001)); + assertFalse(stack.push(9002)); + assertEquals(ZoneStack.EMPTY, stack.peek()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + for (long i = 511; i >= 0; i--) assertEquals(i, stack.pop()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + } + + @Test + void nameFollowsPop() { + final ZoneStack stack = new ZoneStack(); + assertTrue(stack.push(1, false, "tick")); + assertTrue(stack.push(2, true, "jobs")); + assertTrue(stack.push(3, false, null)); + assertEquals(3, stack.pop()); + assertEquals(null, stack.poppedName()); + assertEquals(2, stack.pop()); + assertEquals("jobs", stack.poppedName()); + assertTrue(stack.poppedGpu()); + assertEquals(1, stack.pop()); + assertEquals("tick", stack.poppedName()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + assertEquals(null, stack.poppedName()); + } + + @Test + void namesSurviveGrowth() { + final ZoneStack stack = new ZoneStack(); + for (int i = 0; i < 256; i++) assertTrue(stack.push(i, false, "z" + i)); + for (int i = 255; i >= 0; i--) { + assertEquals(i, stack.pop()); + assertEquals("z" + i, stack.poppedName()); + } + } + + @Test + void drainToEmptyClearsSkippedAndDepth() { + final ZoneStack stack = new ZoneStack(); + for (long i = 0; i < 512; i++) assertTrue(stack.push(i, false, "d" + i)); + assertFalse(stack.push(9001, false, "over")); + assertTrue(stack.hasSkipped()); + int drained = 0; + while (stack.depth() > 0 || stack.hasSkipped()) { + if (stack.pop() != ZoneStack.EMPTY) drained++; + } + assertEquals(512, drained); + assertFalse(stack.hasSkipped()); + assertEquals(0, stack.depth()); + assertEquals(ZoneStack.EMPTY, stack.pop()); + } + + @Test + void skippedPopReportsNoName() { + final ZoneStack stack = new ZoneStack(); + for (long i = 0; i < 512; i++) stack.push(i, false, "x"); + stack.push(9001, false, "capped"); + assertEquals(ZoneStack.EMPTY, stack.pop()); + assertEquals(null, stack.poppedName()); + assertFalse(stack.poppedGpu()); + } +} diff --git a/tracy-client/src/test/java/net/minecraft/launchwrapper/Launch.java b/tracy-client/src/test/java/net/minecraft/launchwrapper/Launch.java new file mode 100644 index 000000000..06f0ecf94 --- /dev/null +++ b/tracy-client/src/test/java/net/minecraft/launchwrapper/Launch.java @@ -0,0 +1,8 @@ +package net.minecraft.launchwrapper; + +import java.util.Map; + +// Compile-only stub. +public class Launch { + public static Map blackboard; +} diff --git a/umbra/buildSrc/build.gradle.kts b/umbra/buildSrc/build.gradle.kts new file mode 100644 index 000000000..81747e0fc --- /dev/null +++ b/umbra/buildSrc/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + `kotlin-dsl` +} + +repositories { + gradlePluginPortal() + mavenCentral() +} + +// Re-export Gradle's generated typed catalog accessors so applied scripts (dependencies.gradle.kts) can use them. +dependencies { + implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) +} diff --git a/umbra/buildSrc/settings.gradle.kts b/umbra/buildSrc/settings.gradle.kts new file mode 100644 index 000000000..66016b6b9 --- /dev/null +++ b/umbra/buildSrc/settings.gradle.kts @@ -0,0 +1,5 @@ +dependencyResolutionManagement { + versionCatalogs { + create("libs") { from(files("../../gradle/libs.versions.toml")) } + } +} diff --git a/umbra/dependencies.gradle b/umbra/dependencies.gradle deleted file mode 100644 index 536aaf090..000000000 --- a/umbra/dependencies.gradle +++ /dev/null @@ -1,40 +0,0 @@ -configurations { - // Embed in JAR without relocation (compile only, shadowed into JAR) - embedOnly - embedOnly.canBeConsumed = false - embedOnly.canBeResolved = true - compileClasspath.extendsFrom(embedOnly) - runtimeClasspath.extendsFrom(embedOnly) - testCompileClasspath.extendsFrom(embedOnly) - testRuntimeClasspath.extendsFrom(embedOnly) -} - -// Exclude self-reference from all configurations -configurations.all { - exclude group: "com.github.GTNewHorizons", module: "Angelica" -} - -dependencies { - compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false } - - compileOnly('org.jetbrains:annotations:26.0.2') - compileOnly("org.projectlombok:lombok:1.18.42") { transitive = false } - annotationProcessor("org.projectlombok:lombok:1.18.42") - - api("com.github.GTNewHorizons:GTNHLib:0.9.36:dev") - - shadowImplementation(project(":glsm")) { transitive = false } - shadowImplementation(project(":lwjgl3-backend")) { transitive = false } - shadowImplementation("net.minecraftforge:eventbus:7.0-beta.15") - - shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 - shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-32.g7dd88a4-GTNH") { - exclude module: "antlr4" // we only want to shadow the runtime module - } - shadowImplementation("org.antlr:antlr4-runtime:4.13.2") - - embedOnly("org.embeddedt.celeritas:celeritas-common:2.5.8-GTNH) { transitive = false } - embedOnly("org.embeddedt.celeritas:celeritas-lwjgl2-service:2.5.3-GTNH") { transitive = false } - runtimeOnlyNonPublishable("org.embeddedt.celeritas:celeritas-common:2.8.5-GTNH") { transitive = false } - runtimeOnlyNonPublishable("org.embeddedt.celeritas:celeritas-lwjgl2-service:2.5.3-GTNH") { transitive = false } -} diff --git a/umbra/dependencies.gradle.kts b/umbra/dependencies.gradle.kts new file mode 100644 index 000000000..a3271b785 --- /dev/null +++ b/umbra/dependencies.gradle.kts @@ -0,0 +1,49 @@ +import org.gradle.accessors.dm.LibrariesForLibs +import org.gradle.kotlin.dsl.DependencyHandlerScope + +val libs = the() + +val api = configurations["api"] +val compileOnly = configurations["compileOnly"] +val annotationProcessor = configurations["annotationProcessor"] +val shadowImplementation = configurations["shadowImplementation"] +val runtimeOnlyNonPublishable = configurations["runtimeOnlyNonPublishable"] + +// Embed in JAR without relocation (compile only, shadowed into JAR) +val embedOnly by configurations.creating { + isCanBeConsumed = false + isCanBeResolved = true +} +configurations["compileClasspath"].extendsFrom(embedOnly) +configurations["runtimeClasspath"].extendsFrom(embedOnly) +configurations["testCompileClasspath"].extendsFrom(embedOnly) +configurations["testRuntimeClasspath"].extendsFrom(embedOnly) + +configurations.configureEach { + exclude(group = "com.github.GTNewHorizons", module = "Angelica") +} + +DependencyHandlerScope.of(dependencies).apply { + compileOnly(libs.retrofuturabootstrap) { isTransitive = false } + + compileOnly(libs.annotations) + compileOnly(libs.lombok) { isTransitive = false } + annotationProcessor(libs.lombok) + + api(libs.gtnhlib) { artifact { classifier = "dev" } } + + shadowImplementation(project(":glsm")) { isTransitive = false } + shadowImplementation(project(":lwjgl3-backend")) { isTransitive = false } + shadowImplementation(libs.eventbus) + + shadowImplementation(libs.jcpp) // Apache 2.0 + shadowImplementation(libs.glsl.transformation.lib) { + exclude(module = "antlr4") // we only want to shadow the runtime module + } + shadowImplementation(libs.antlr4.runtime) + + embedOnly(libs.celeritas.common) { isTransitive = false } + embedOnly(libs.celeritas.lwjgl2.service) { isTransitive = false } + runtimeOnlyNonPublishable(libs.celeritas.common) { isTransitive = false } + runtimeOnlyNonPublishable(libs.celeritas.lwjgl2.service) { isTransitive = false } +} diff --git a/umbra/repositories.gradle b/umbra/repositories.gradle new file mode 100644 index 000000000..033d07fda --- /dev/null +++ b/umbra/repositories.gradle @@ -0,0 +1,5 @@ +// Add any additional repositories for your dependencies here + +repositories { + mavenLocal() +} diff --git a/umbra/settings.gradle.kts b/umbra/settings.gradle.kts index f908dd244..da5e1c374 100644 --- a/umbra/settings.gradle.kts +++ b/umbra/settings.gradle.kts @@ -16,7 +16,15 @@ pluginManagement { } plugins { - id("com.gtnewhorizons.gtnhsettingsconvention") version ("2.0.24") + id("com.gtnewhorizons.gtnhsettingsconvention") version ("2.0.27") +} + +apply(from = file("../gradle/lwjgl-natives.settings.gradle.kts")) + +dependencyResolutionManagement { + versionCatalogs { + create("libs") { from(files("../gradle/libs.versions.toml")) } + } } include("glsm") diff --git a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/ffp/MixinTessellator_CoreProfile.java b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/ffp/MixinTessellator_CoreProfile.java index 403fe8748..f25022eac 100644 --- a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/ffp/MixinTessellator_CoreProfile.java +++ b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/ffp/MixinTessellator_CoreProfile.java @@ -1,7 +1,5 @@ package com.gtnewhorizons.umbra.mixins.early.ffp; -import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; -import com.gtnewhorizons.angelica.glsm.ITessellatorData; import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import net.minecraft.client.renderer.Tessellator; import org.spongepowered.asm.mixin.Mixin; @@ -10,24 +8,8 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -/** - * Intercepts Tessellator.draw() to use streaming VBO+VAO for core profile rendering. - * Implements ITessellatorData so TessellatorStreamingDrawer can access Tessellator fields - * without depending on Minecraft classes. - */ @Mixin(Tessellator.class) -public class MixinTessellator_CoreProfile implements ITessellatorData { - - @Shadow public boolean isDrawing; - @Shadow public int vertexCount; - @Shadow public int[] rawBuffer; - @Shadow public int rawBufferIndex; - @Shadow public int rawBufferSize; - @Shadow public int drawMode; - @Shadow public boolean hasTexture; - @Shadow public boolean hasColor; - @Shadow public boolean hasNormals; - @Shadow public boolean hasBrightness; +public class MixinTessellator_CoreProfile { @Shadow public void reset() {} @@ -37,21 +19,6 @@ public class MixinTessellator_CoreProfile implements ITessellatorData { @Inject(method = "draw", at = @At("HEAD"), cancellable = true) private void umbra$coreProfileDraw(CallbackInfoReturnable cir) { - if (TessellatorManager.shouldInterceptDraw((Tessellator)(Object)this)) return; - cir.setReturnValue(TessellatorStreamingDrawer.draw((ITessellatorData) this)); + cir.setReturnValue(TessellatorStreamingDrawer.draw((Tessellator)(Object)this)); } - - @Override public boolean isDrawing() { return isDrawing; } - @Override public void setDrawing(boolean drawing) { isDrawing = drawing; } - @Override public int getVertexCount() { return vertexCount; } - @Override public int[] getRawBuffer() { return rawBuffer; } - @Override public int getRawBufferIndex() { return rawBufferIndex; } - @Override public int getRawBufferSize() { return rawBufferSize; } - @Override public void setRawBufferSize(int size) { rawBufferSize = size; } - @Override public void setRawBuffer(int[] buffer) { rawBuffer = buffer; } - @Override public int getDrawMode() { return drawMode; } - @Override public boolean hasTexture() { return hasTexture; } - @Override public boolean hasColor() { return hasColor; } - @Override public boolean hasNormals() { return hasNormals; } - @Override public boolean hasBrightness() { return hasBrightness; } } diff --git a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/glsm/MixinSplashProgressCaching.java b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/glsm/MixinSplashProgressCaching.java index 35c902783..78060da04 100644 --- a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/glsm/MixinSplashProgressCaching.java +++ b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/glsm/MixinSplashProgressCaching.java @@ -1,7 +1,6 @@ package com.gtnewhorizons.umbra.mixins.early.glsm; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; @@ -9,24 +8,14 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -/** - * Controls GLSM state during splash screen lifecycle. - * Initializes splash tessellator on start, marks splash complete on finish. - */ @SuppressWarnings("deprecation") @Mixin(value = cpw.mods.fml.client.SplashProgress.class, remap = false) public class MixinSplashProgressCaching { private static final Logger LOGGER = LogManager.getLogger("Umbra"); - @Inject(method = "start", at = @At("HEAD")) - private static void umbra$initSplashTessellator(CallbackInfo ci) { - ImmediateModeRecorder.initSplashTessellator(); - } - @Inject(method = "finish", at = @At("RETURN")) private static void umbra$enableCachingOnFinish(CallbackInfo ci) { - ImmediateModeRecorder.destroySplashTessellator(); - GLStateManager.markSplashComplete(); + GLStateManager.markSplashComplete("SplashProgress.finish"); LOGGER.info("Splash Complete"); } } diff --git a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/startup/MixinInitGLStateManager.java b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/startup/MixinInitGLStateManager.java index 582bb528a..8207ab25c 100644 --- a/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/startup/MixinInitGLStateManager.java +++ b/umbra/src/mixin/java/com/gtnewhorizons/umbra/mixins/early/startup/MixinInitGLStateManager.java @@ -21,8 +21,6 @@ public class MixinInitGLStateManager { GLStateManager.setDrawableGL(Display.getDrawable()); GLStateManager.initialize(GLSMInitConfig.builder() .displaySize(mc.displayWidth, mc.displayHeight) - .framebufferSupported(OpenGlHelper.framebufferSupported) - .fboEnabled(mc.gameSettings.fboEnable) .directDrawer(TessellatorStreamingDrawer::drawDirect) .streamingDrawerDestroy(TessellatorStreamingDrawer::destroy) .build());