diff --git a/README.md b/README.md index cf824098d..59372bc12 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Please reach out to @embeddedt on Discord if you have concerns regarding the lic * rdh, for leading several key improvements, including faster & better occlusion culling, better AO rendering, etc * douira, for researching and writing the [paper](https://douira.dev/assets/document/douira-master-thesis.pdf) on which the translucency sorting v3 implementation is based * grondag, for developing [bitraster](https://github.com/vram-guild/bitraster), the library we vendor for rasterized occlusion culling +* djefrey, for developing [Colorwheel](https://github.com/djefrey/Colorwheel), which our Flywheel backend for shader packs is ported from * XFactHD, Pepper, and anyone else I've forgotten to mention, for providing valuable code insights [![YourKit logo](https://www.yourkit.com/images/yklogo.png)](https://www.yourkit.com/) diff --git a/buildSrc/src/main/kotlin/celeritas.platform-conventions.gradle.kts b/buildSrc/src/main/kotlin/celeritas.platform-conventions.gradle.kts index f6c01bba4..6227e53cf 100644 --- a/buildSrc/src/main/kotlin/celeritas.platform-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/celeritas.platform-conventions.gradle.kts @@ -212,13 +212,29 @@ tasks.named("processResources") { val isFabric = modLoader == ModLoader.FABRIC val modId = rootProject.property("mod_id").toString() val mixinConfigs = modMixinConfigs + // The shader pack Flywheel backend depends on Flywheel internals that changed in 1.0.6, and replaces Colorwheel. + val minFlywheelVersion = if (versionedProperty("flywheel_version") != null) "1.0.6" else null + inputs.property("minFlywheelVersion", minFlywheelVersion ?: "") doLast { val outputDir = Path.of(outputs.files.asPath) - if (isNeoForge) { - val modsTOML = outputDir.resolve("META-INF/mods.toml") + val modsTOML = outputDir.resolve("META-INF/mods.toml") + if (minFlywheelVersion != null && !isFabric && Files.exists(modsTOML)) { + val loaderDependency = { id: String, type: String, mandatory: Boolean, range: String -> + "\n\n[[dependencies.${modId}]]\nmodId = \"${id}\"\nmandatory = ${mandatory}\ntype = \"${type}\"\nversionRange = \"${range}\"\nordering = \"NONE\"\nside = \"CLIENT\"" + } + modsTOML.toFile().appendText(loaderDependency("flywheel", "optional", false, "[${minFlywheelVersion},)")) + modsTOML.toFile().appendText(if (isNeoForge) { + loaderDependency("colorwheel", "incompatible", false, "*") + } else { + // Forge has no incompatible dependencies, but rejects an optional one whose range nothing satisfies. + loaderDependency("colorwheel", "optional", false, "(,0)") + }) + } + + if (isNeoForge) { if (Files.exists(modsTOML)) { modsTOML.toFile().appendText("\n\n[[mixins]]\nconfig = \"${modId}.mixins.json\"") @@ -234,6 +250,10 @@ tasks.named("processResources") { parse["mixins"] = mixinConfigs.toList() + if (minFlywheelVersion != null) { + parse["breaks"] = mapOf("flywheel" to "<${minFlywheelVersion}", "colorwheel" to "*") + } + file.writeText(JsonOutput.prettyPrint(JsonOutput.toJson(parse))) } } diff --git a/buildSrc/src/main/kotlin/celeritas.shader-conventions.gradle.kts b/buildSrc/src/main/kotlin/celeritas.shader-conventions.gradle.kts index 3472f38dd..b416631d6 100644 --- a/buildSrc/src/main/kotlin/celeritas.shader-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/celeritas.shader-conventions.gradle.kts @@ -1,4 +1,6 @@ +import bs.ModLoader import org.embeddedt.embeddium.gradle.build.extensions.celeritasMixinConfigs +import org.embeddedt.embeddium.gradle.build.extensions.versionedProperty plugins { id("java-library") @@ -45,4 +47,42 @@ dependencies { add(additionalDepConfig, it) } } -} \ No newline at end of file +} + +// The Iris code compiled for every shader target calls into the Flywheel backend. +val flywheelVersion = requireNotNull(versionedProperty("flywheel_version")) { + "Shader targets compile the Flywheel backend; set flywheel_version_${ModLoader.getMinecraftVersion(project).replace('.', '_')} in gradle.properties" +} + +sourceSets { + main { + java.srcDir("src/main/flywheel_java") + resources.srcDir("src/main/flywheel_resources") + } +} + +modMixinConfigs.add("mixins.oculus.compat.flywheel.json") + +repositories { + exclusiveContent { + forRepository { + maven { + name = "Create Maven" + url = uri("https://maven.createmod.net") + } + } + filter { + includeGroup("dev.engine-room.flywheel") + } + } +} + +dependencies { + val modLoader = requireNotNull(ModLoader.fromProject(project)) + val minecraftVersion = ModLoader.getMinecraftVersion(project) + // Forge and Fabric jars are published obfuscated and need the loader's remapping configuration. + val configurationName = if (modLoader == ModLoader.NEOFORGE) "compileOnly" else "modCompileOnly" + add(configurationName, "dev.engine-room.flywheel:flywheel-${modLoader.friendlyName}-${minecraftVersion}:${flywheelVersion}") { + isTransitive = false + } +} diff --git a/gradle.properties b/gradle.properties index 703f535cd..533e76aa5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -107,3 +107,7 @@ forge_1_18_2=1.18.2-40.2.21 forge_1_19_2=1.19.2-43.4.4 forge_1_20_1=1.20.1-47.3.0 forge_1_21_1=1.21.1-52.0.24 + +# Flywheel (compiled against for the in-tree shader backend) +flywheel_version_1_20_1=1.0.6 +flywheel_version_1_21_1=1.0.6 diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlBackend.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlBackend.java new file mode 100644 index 000000000..93db9a385 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlBackend.java @@ -0,0 +1,129 @@ +package net.irisshaders.iris.compat.flywheel; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlEngine; +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlBufferBindings; +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlIndirectDrawManager; +import net.irisshaders.iris.compat.flywheel.instancing.ClrwlInstancedDrawManager; +import dev.engine_room.flywheel.api.backend.Backend; +import dev.engine_room.flywheel.backend.gl.Driver; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.lib.backend.SimpleBackend; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.shaderpack.ShaderPack; + +import java.util.Optional; + +public class ClrwlBackend +{ + public static final Backend IRIS_INSTANCING = SimpleBackend.builder() + .engineFactory(level -> new ClrwlEngine(level, 256, ClrwlInstancedDrawManager::build)) + .priority(500) + .supported(() -> GlCompat.SUPPORTS_INSTANCING && isUsingCompatibleShaderPack()) + .register(Colorwheel.rl("instancing")); + + public static final Backend IRIS_INDIRECT = SimpleBackend.builder() + .engineFactory(level -> new ClrwlEngine(level, 256, ClrwlIndirectDrawManager::build)) + .priority(() -> { + // Read from GlCompat in these provider because loading GlCompat + // at the same time the backends are registered causes GlCapabilities to be null. + if (GlCompat.DRIVER == Driver.INTEL) + { + // Intel has very poor performance with indirect rendering, and on top of that has graphics bugs + return 1; + } + else + { + return 1000; + } + }) + .supported(() -> GlCompat.SUPPORTS_INDIRECT && isUsingCompatibleShaderPack() && hasEnoughShaderStorageUnits()) + .register(Colorwheel.rl("indirect")); + + private static ShaderPack warnedIncompatiblePack; + + // Set when rendering with the current pack failed. Reloading creates a new ShaderPack, which retries. + private static ShaderPack failedPack; + + public static void init() + { + ClrwlRenderPasses.init(); + } + + /** + * Stops Flywheel from selecting these backends again until the shader pack is reloaded, so a pack that fails to + * render can't make every level renderer reload fail the same way. + */ + public static void disableForCurrentPack() + { + failedPack = Iris.getCurrentPack().orElse(null); + Colorwheel.LOGGER.error("Disabling the Flywheel backend for shader pack {} until it is reloaded", Iris.getCurrentPackName()); + } + + public static boolean isCurrentBackend(Backend backend) + { + return backend == IRIS_INSTANCING || backend == IRIS_INDIRECT; + } + + public static boolean isUsingCompatibleShaderPack() + { + Optional pack = Iris.getCurrentPack(); + + if (pack.isEmpty() || pack.get() == failedPack) + { + return false; + } + + var programs = pack.get().getProgramSet(Iris.getCurrentDimension()).getClrwlPrograms(); + + if (programs == null) + { + return false; + } + + if (programs.isFallbackMode() && !Iris.getIrisConfig().isFlywheelFallbackMode()) + { + if (warnedIncompatiblePack != pack.get()) + { + warnedIncompatiblePack = pack.get(); + Colorwheel.LOGGER.warn("Shader pack {} has no Flywheel programs; enable flywheelFallbackMode in the Iris config to render Flywheel content through its gbuffers programs", + Iris.getCurrentPackName()); + } + + return false; + } + + return true; + } + + /** + * @return the first SSBO binding above every binding the pack declares + */ + public static int getShaderStorageBase(ShaderPack pack) + { + var irisBufferObjects = pack.getShaderProperties().getBufferObjects(); + + return irisBufferObjects.isEmpty() ? 0 : irisBufferObjects.keySet().intStream().max().getAsInt() + 1; + } + + public static boolean hasEnoughShaderStorageUnits() + { + Optional pack = Iris.getCurrentPack(); + + if (pack.isEmpty()) + { + return false; + } + + int base = getShaderStorageBase(pack.get()); + int maxUnits = SamplerLimits.get().getMaxShaderStorageUnits(); + boolean hasEnoughUnits = base + ClrwlBufferBindings.TOTAL_BINDING_COUNT <= maxUnits; + + if (!hasEnoughUnits) + { + Colorwheel.LOGGER.error("Graphics card doesn't have enough storage units: {} + {} > {}", base, ClrwlBufferBindings.TOTAL_BINDING_COUNT, maxUnits); + } + + return hasEnoughUnits; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlRenderPasses.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlRenderPasses.java new file mode 100644 index 000000000..81b022204 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlRenderPasses.java @@ -0,0 +1,97 @@ +package net.irisshaders.iris.compat.flywheel; + +//? if <1.21 +import com.mojang.blaze3d.vertex.PoseStack; +import dev.engine_room.flywheel.api.backend.BackendManager; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.visualization.VisualizationManager; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.flywheel.engine.ShadowRenderContext; +import net.irisshaders.iris.compat.flywheel.engine.ShadowRenderingPhase; +import net.irisshaders.iris.compat.flywheel.engine.TranslucentRenderContext; +import net.irisshaders.iris.pipeline.ShaderRenderPassEvent; +import net.irisshaders.iris.uniforms.CameraUniforms; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.Minecraft; +import org.joml.Matrix4f; + +/** + * Draws Flywheel content in the shadow and translucent passes. Flywheel only calls engines once per frame, after + * entities; the extra passes go through the same dispatcher so they wait for the frame plan like that call does. + */ +public final class ClrwlRenderPasses +{ + private ClrwlRenderPasses() + { + } + + public static void init() + { + ShaderRenderPassEvent.BUS.addListener(ClrwlRenderPasses::onRenderPass); + } + + private static void onRenderPass(ShaderRenderPassEvent event) + { + var minecraft = Minecraft.getInstance(); + var level = minecraft.level; + + if (level == null || !ClrwlBackend.isCurrentBackend(BackendManager.currentBackend())) + { + return; + } + + var manager = VisualizationManager.get(level); + + if (manager == null) + { + return; + } + + //? if <1.21 { + var modelView = new PoseStack(); + modelView.last().pose().set(event.getModelView()); + //?} else + //var modelView = event.getModelView(); + var projection = new Matrix4f(event.getProjection()); + + RenderContext context = switch (event.getStage()) + { + case TRANSLUCENT -> TranslucentRenderContext.create(minecraft.levelRenderer, level, minecraft.renderBuffers(), + modelView, projection, event.getCamera(), event.getPartialTick()); + case SHADOW_SOLID, SHADOW_TRANSLUCENT -> + { + if (!shouldRenderShadow()) + { + yield null; + } + + var cameraPos = CameraUniforms.getUnshiftedCameraPosition(); + + yield ShadowRenderContext.create(minecraft.levelRenderer, level, minecraft.renderBuffers(), + modelView, projection, + CapturedRenderingState.INSTANCE.getGbufferModelView(), CapturedRenderingState.INSTANCE.getGbufferProjection(), + event.getCamera(), (float) cameraPos.x(), (float) cameraPos.y(), (float) cameraPos.z(), + event.getPartialTick(), + event.getStage() == ShaderRenderPassEvent.Stage.SHADOW_SOLID ? ShadowRenderingPhase.SOLID : ShadowRenderingPhase.TRANSLUCENT); + } + }; + + if (context != null) + { + manager.renderDispatcher().afterEntities(context); + } + } + + private static boolean shouldRenderShadow() + { + var pack = Iris.getCurrentPack(); + + if (pack.isEmpty()) + { + return false; + } + + var programs = pack.get().getProgramSet(Iris.getCurrentDimension()).getClrwlPrograms(); + return programs != null && programs.getClrwlDirectives().shouldRenderShadow(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlSamplers.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlSamplers.java new file mode 100644 index 000000000..3950a1475 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/ClrwlSamplers.java @@ -0,0 +1,28 @@ +package net.irisshaders.iris.compat.flywheel; + +import dev.engine_room.flywheel.backend.gl.GlTextureUnit; + +public class ClrwlSamplers +{ + public static final GlTextureUnit DIFFUSE = GlTextureUnit.T0; + public static final GlTextureUnit OVERLAY = GlTextureUnit.T1; + public static final GlTextureUnit LIGHT = GlTextureUnit.T2; + public static final GlTextureUnit CRUMBLING = GlTextureUnit.T3; + public static final GlTextureUnit INSTANCE_BUFFER = GlTextureUnit.T4; + public static final GlTextureUnit LIGHT_LUT = GlTextureUnit.T5; + public static final GlTextureUnit LIGHT_SECTIONS = GlTextureUnit.T6; + + public static final GlTextureUnit DEPTH_RANGE = GlTextureUnit.T7; + public static final GlTextureUnit NOISE = GlTextureUnit.T8; + public static final GlTextureUnit FIRST_COEFFICIENT = GlTextureUnit.T9; + + public static GlTextureUnit getAccumulate(int idx) + { + return GlTextureUnit.fromGlEnum(GlTextureUnit.T0.glEnum + idx); + } + + public static GlTextureUnit getCoefficient(int idx) + { + return GlTextureUnit.fromGlEnum(FIRST_COEFFICIENT.glEnum + idx); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/Colorwheel.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/Colorwheel.java new file mode 100644 index 000000000..760096777 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/Colorwheel.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.compat.flywheel; + +import net.minecraft.resources.ResourceLocation; +import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices; +import org.embeddedt.embeddium.impl.util.ResourceLocationUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Shared helpers for the Flywheel backend. Must not reference Flywheel classes, since Iris queries + * {@link #isFlywheelLoaded()} whether or not Flywheel is installed. + */ +public final class Colorwheel +{ + public static final Logger LOGGER = LoggerFactory.getLogger("Celeritas/Flywheel"); + + // The Colorwheel release whose shader pack contract (programs, properties, macros) this backend implements. + public static final String FORMATTED_VERSION = "10300"; + + private static final boolean FLYWHEEL_LOADED = EarlyLoaderServices.INSTANCE.isModLoaded("flywheel"); + + private Colorwheel() + { + } + + public static boolean isFlywheelLoaded() + { + return FLYWHEEL_LOADED; + } + + public static ResourceLocation rl(String path) + { + return ResourceLocationUtil.make("celeritas", path); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlIndirectPrograms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlIndirectPrograms.java new file mode 100644 index 000000000..00cb5de63 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlIndirectPrograms.java @@ -0,0 +1,384 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlBufferBindings; +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.component.IrisShaderComponent; +import net.irisshaders.iris.compat.flywheel.compile.component.SsboInstanceComponent; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlCompilationHarness; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlCompile; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlShaderSources; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlPackDirectives; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.backend.compile.IndirectPrograms; +import dev.engine_room.flywheel.backend.compile.OitPrograms; +import dev.engine_room.flywheel.backend.compile.PipelineCompiler; +import dev.engine_room.flywheel.backend.compile.component.InstanceStructComponent; +import dev.engine_room.flywheel.backend.compile.core.CompilationHarness; +import dev.engine_room.flywheel.backend.compile.core.Compile; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import dev.engine_room.flywheel.backend.gl.shader.ShaderType; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.lib.util.ResourceUtil; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +public class ClrwlIndirectPrograms +{ + private interface PipelineProgramsFactory + { + PipelinePrograms build(IrisRenderingPipeline irisPipeline); + } + + public enum Culling + { + GBUFFERS_EARLY("gbuffers_early", Colorwheel.rl("internal/indirect/cull/gbuffers_early.glsl"), ClrwlProgramGroup.GBUFFERS, false, true), + GBUFFERS_LATE("gbuffers_late", Colorwheel.rl("internal/indirect/cull/gbuffers_late.glsl"), ClrwlProgramGroup.GBUFFERS, true, true), + GBUFFERS_FULL("gbuffers_full", Colorwheel.rl("internal/indirect/cull/gbuffers_full.glsl"), ClrwlProgramGroup.GBUFFERS, true, true), + SHADOW_EARLY("shadow_early", Colorwheel.rl("internal/indirect/cull/shadow_early.glsl"), ClrwlProgramGroup.SHADOW, false, true), + SHADOW_LATE("shadow_late", Colorwheel.rl("internal/indirect/cull/shadow_late.glsl"), ClrwlProgramGroup.SHADOW, true, true), + SHADOW_FULL("shadow_full", Colorwheel.rl("internal/indirect/cull/shadow_full.glsl"), ClrwlProgramGroup.SHADOW, true, true); + + private final String name; + private final ResourceLocation shader; + private final ClrwlProgramGroup group; + private final boolean occlusion; + private final boolean frustum; + + Culling(String name, ResourceLocation shader, ClrwlProgramGroup group, boolean occlusion, boolean frustum) + { + this.name = name; + this.shader = shader; + this.group = group; + this.occlusion = occlusion; + this.frustum = frustum; + } + + public String shaderName() + { + return this.name; + } + + public ResourceLocation shader() + { + return this.shader; + } + + public boolean useOcclusion() + { + return occlusion; + } + + public boolean useFrustum() + { + return frustum; + } + + public ClrwlProgramGroup programGroup() + { + return group; + } + + public static class MaterialFilter + { + public static final int SOLID = 0b01; + public static final int TRANSLUCENT = 0b10; + + public static final int ALL = SOLID | TRANSLUCENT; + } + } + + private static final ResourceLocation CULL_SHADER_API_IMPL = Colorwheel.rl("internal/indirect/cull/api_impl.glsl"); + private static final ResourceLocation TRANSFORM_SHADER_MAIN = Colorwheel.rl("internal/indirect/transform.glsl"); + private static final ResourceLocation APPLY_SHADER_MAIN = Colorwheel.rl("internal/indirect/apply.glsl"); + private static final ResourceLocation ZERO_SHADER_MAIN = Colorwheel.rl("internal/indirect/zero_models.glsl"); + private static final ResourceLocation DOWNSAMPLE_FIRST = Colorwheel.rl("internal/indirect/downsample_first.glsl"); + private static final ResourceLocation DOWNSAMPLE_SECOND = Colorwheel.rl("internal/indirect/downsample_second.glsl"); + + public static final List EXTENSIONS = getExtensions(GlCompat.MAX_GLSL_VERSION); + private static final List COMPUTE_EXTENSIONS = getComputeExtensions(GlCompat.MAX_GLSL_VERSION); + + private static final Compile> TRANSFORM = new Compile<>(); + private static final ClrwlCompile CULL = new ClrwlCompile<>(); + private static final Compile UTIL = new Compile<>(); + + private final ClrwlOitPrograms oitPrograms; + private final CompilationHarness> transform; + private final CompilationHarness utils; + private final PipelineProgramsFactory programsFactory; + + // WARNING: this can ONLY be used for utils ! (otherwise, kaboom) + private final IndirectPrograms flwPrograms; + + private ClrwlIndirectPrograms(ClrwlOitPrograms oitPrograms, + CompilationHarness> transform, CompilationHarness utils, + PipelineProgramsFactory programsFactory) + { + this.oitPrograms = oitPrograms; + this.transform = transform; + this.utils = utils; + this.programsFactory = programsFactory; + + try + { + var constructor = IndirectPrograms.class.getDeclaredConstructor(PipelineCompiler.class, CompilationHarness.class, CompilationHarness.class, OitPrograms.class); + constructor.setAccessible(true); + this.flwPrograms = constructor.newInstance(null, null, utils, null); + } + catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) + { + throw new RuntimeException(e); + } + } + + private static List getExtensions(GlslVersion glslVersion) + { + var extensions = ImmutableList.builder(); + if (glslVersion.compareTo(GlslVersion.V400) < 0) + { + extensions.add("GL_ARB_gpu_shader5"); + } + if (glslVersion.compareTo(GlslVersion.V420) < 0) + { + extensions.add("GL_ARB_shading_language_420pack"); + extensions.add("GL_ARB_shader_image_load_store"); + } + if (glslVersion.compareTo(GlslVersion.V430) < 0) + { + extensions.add("GL_ARB_shader_storage_buffer_object"); + extensions.add("GL_ARB_shader_image_size"); + } + if (glslVersion.compareTo(GlslVersion.V460) < 0) + { + extensions.add("GL_ARB_shader_draw_parameters"); + } + return extensions.build(); + } + + private static List getComputeExtensions(GlslVersion glslVersion) + { + var extensions = ImmutableList.builder(); + + extensions.addAll(EXTENSIONS); + + if (glslVersion.compareTo(GlslVersion.V430) < 0) { + extensions.add("GL_ARB_compute_shader"); + } + return extensions.build(); + } + + public static ClrwlIndirectPrograms build(ShaderSources sources, ShaderPack pack, ProgramSet programSet, boolean fallback) + { + if (!GlCompat.SUPPORTS_INDIRECT) + { + return null; + } + + var pipeline = fallback + ? ClrwlPipelines.INDIRECT_FALLBACK + : ClrwlPipelines.INDIRECT; + + var oitPrograms = new ClrwlOitPrograms(sources, pipeline); + var transform = createTransformCompiler(sources); + var util = createUtilCompiler(sources); + + PipelineProgramsFactory programsFactory = (irisPipeline) -> + { + var clrwlSources = new ClrwlShaderSources(sources, programSet, irisPipeline); + return new PipelinePrograms(clrwlSources, pipeline); + }; + + return new ClrwlIndirectPrograms(oitPrograms, transform, util, programsFactory); + } + + private static CompilationHarness> createTransformCompiler(ShaderSources sources) + { + var shader = TRANSFORM.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.COMPUTE) + .nameMapper(instanceType -> "colorwheel/transform_bounding_spheres/" + ResourceUtil.toDebugFileNameNoExtension(instanceType.cullShader())) + .requireExtensions(COMPUTE_EXTENSIONS) + .define("_FLW_SUBGROUP_SIZE", GlCompat.SUBGROUP_SIZE) + .define("_CLRWL_IS_GBUFFERS_PASS", 1) + .onCompile(($, c) -> c.define("_CLRWL_SSBO_BASE", Integer.toString(ClrwlBufferBindings.base()))); + + shader = shader + .withResource(CULL_SHADER_API_IMPL) + .withComponent(InstanceStructComponent::new) + .withResource(InstanceType::cullShader) + .withComponent(SsboInstanceComponent::new) + .withResource(TRANSFORM_SHADER_MAIN); + + return TRANSFORM.program() + .link(shader) + .postLink((key, program) -> ClrwlUniforms.setUniformsBlockBindings(program)) + .harness("transform_bounding_spheres", sources); + } + + /** + * A compiler for cull shaders, parameterized by the instance type. + */ + private static ClrwlCompilationHarness createCullingCompiler(ClrwlShaderSources sources, ClrwlPrograms.Pipeline pipeline) + { + var shader = CULL.shader(GlCompat.MAX_GLSL_VERSION, ClrwlShaderType.COMPUTE) + .nameMapper(cull -> "cull/" + cull.shaderName()) + .requireExtensions(COMPUTE_EXTENSIONS) + .enableExtension("GL_KHR_shader_subgroup_basic") + .enableExtension("GL_KHR_shader_subgroup_ballot") + .define("_FLW_SUBGROUP_SIZE", GlCompat.SUBGROUP_SIZE) + .onCompile((k, c) -> ClrwlPrograms.defineClrwlPass(k.programGroup() == ClrwlProgramGroup.SHADOW, c)); + + if (FORCE_DISABLE_SUBGROUP_BALLOT) + { + shader = shader.define("_CLRWL_FORCE_DISABLE_SUBGROUP_BALLOT", 1); + } + + shader.onCompile((k, c) -> + { + ClrwlPackDirectives directives = sources.programSet().getClrwlPrograms().getClrwlDirectives(); + + if (directives.getOcclusionCulling(k.programGroup()) && k.useOcclusion()) + { + c.define("_CLRWL_OCCLUSION_CULLING", "1"); + } + + if (directives.getFrustumCulling(k.programGroup()) && k.useFrustum()) + { + c.define("_CLRWL_FRUSTUM_CULLING", "1"); + } + }); + + shader = shader + .withResource(CULL_SHADER_API_IMPL) + .onCompile((k, c) -> + { + ClrwlPackDirectives directives = sources.programSet().getClrwlPrograms().getClrwlDirectives(); + + if (k.programGroup() == ClrwlProgramGroup.SHADOW && directives.getOcclusionCulling(ClrwlProgramGroup.SHADOW) && k.useOcclusion()) + { + var computeSrc = sources.programSet().getClrwlPrograms().getShadowDistortSource().orElseThrow(); + var src = sources.clrwlSources().getComputeSource(computeSrc); + c.appendComponent(new IrisShaderComponent(computeSrc.getName(), src.shader())); + } + }) + .withResource(Culling::shader); + + return CULL.program() + .link(shader) + .postLink((key, program) -> ClrwlUniforms.setUniformsBlockBindings(program)) + .harness("culling", sources, ($, h) -> new GlProgram(h)); + } + + /** + * A compiler for utility shaders, directly compiles the shader at the resource location specified by the parameter. + */ + private static CompilationHarness createUtilCompiler(ShaderSources sources) + { + return UTIL.program() + .link(UTIL.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.COMPUTE) + .nameMapper(resourceLocation -> "colorwheel/utilities/" + ResourceUtil.toDebugFileNameNoExtension(resourceLocation)) + .requireExtensions(COMPUTE_EXTENSIONS) + .define("_FLW_SUBGROUP_SIZE", GlCompat.SUBGROUP_SIZE) + .onCompile(($, c) -> c.define("_CLRWL_SSBO_BASE", Integer.toString(ClrwlBufferBindings.base()))) + .withResource(s -> s)) + .harness("utilities", sources); + } + + + public PipelinePrograms createPipelinePrograms(IrisRenderingPipeline irisPipeline) + { + return programsFactory.build(irisPipeline); + } + + public ClrwlOitPrograms getOitPrograms() { return oitPrograms; } + + public GlProgram getTransformProgram(InstanceType instanceType) + { + return this.transform.get(instanceType); + } + + public GlProgram getApplyProgram() + { + return utils.get(APPLY_SHADER_MAIN); + } + + public GlProgram getZeroModelsProgram() + { + return utils.get(ZERO_SHADER_MAIN); + } + + public GlProgram getScatterProgram() + { + return flwPrograms.getScatterProgram(); + } + + public GlProgram getDownsampleFirstProgram() + { + return utils.get(DOWNSAMPLE_FIRST); + } + + public GlProgram getDownsampleSecondProgram() + { + return utils.get(DOWNSAMPLE_SECOND); + } + + // WARNING: Should ONLY be used for utils programs + public IndirectPrograms getFlwPrograms() + { + return flwPrograms; + } + + public void delete() + { + oitPrograms.delete(); + transform.delete(); + utils.delete(); + + // flwPrograms is not deleted as it contains null references (=> kaboom) + } + + public static class PipelinePrograms + { + ClrwlPrograms clrwlPrograms; + ClrwlCompilationHarness cullPrograms; + + public PipelinePrograms(ClrwlShaderSources sources, ClrwlPrograms.Pipeline pipeline) + { + this.clrwlPrograms = new ClrwlPrograms(sources, pipeline); + this.cullPrograms = createCullingCompiler(sources, pipeline); + } + + @Nullable + public ClrwlProgram get(ClrwlShaderKey key) + { + return clrwlPrograms.get(key); + } + + public GlProgram getCullingProgram(Culling culling) + { + return cullPrograms.get(culling); + } + + public void delete() + { + clrwlPrograms.delete(); + cullPrograms.delete(); + } + } + + private static boolean FORCE_DISABLE_SUBGROUP_BALLOT = false; + + public static void toggleSubgroupBallot(boolean enabled) + { + FORCE_DISABLE_SUBGROUP_BALLOT = !enabled; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlInstancedPrograms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlInstancedPrograms.java new file mode 100644 index 000000000..2074d9dc2 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlInstancedPrograms.java @@ -0,0 +1,101 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlShaderSources; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class ClrwlInstancedPrograms +{ + private interface PipelineProgramsFactory + { + PipelinePrograms build(IrisRenderingPipeline irisPipeline); + } + + public static final List EXTENSIONS = getExtensions(GlCompat.MAX_GLSL_VERSION); + + private final ClrwlOitPrograms oitPrograms; + private final PipelineProgramsFactory programsFactory; + + private ClrwlInstancedPrograms(ClrwlOitPrograms oitPrograms, PipelineProgramsFactory programsFactory) + { + this.oitPrograms = oitPrograms; + this.programsFactory = programsFactory; + } + + private static List getExtensions(GlslVersion glslVersion) + { + var extensions = ImmutableList.builder(); + + if (glslVersion.compareTo(GlslVersion.V330) < 0) + { + extensions.add("GL_ARB_shader_bit_encoding"); + } + + return extensions.build(); + } + + public static ClrwlInstancedPrograms build(ShaderSources sources, ShaderPack pack, ProgramSet programSet, boolean fallback) + { + if (!GlCompat.SUPPORTS_INSTANCING) + { + return null; + } + + var pipeline = fallback + ? ClrwlPipelines.INSTANCING_FALLBACK + : ClrwlPipelines.INSTANCING; + + var oitPrograms = new ClrwlOitPrograms(sources, pipeline); + PipelineProgramsFactory programsFactory = (irisPipeline) -> + { + var clrwlSources = new ClrwlShaderSources(sources, programSet, irisPipeline); + return new PipelinePrograms(clrwlSources, pipeline); + }; + + return new ClrwlInstancedPrograms(oitPrograms, programsFactory); + } + + public PipelinePrograms createPipelinePrograms(IrisRenderingPipeline irisPipeline) + { + return programsFactory.build(irisPipeline); + } + + public ClrwlOitPrograms getOitPrograms() + { + return oitPrograms; + } + + public void delete() + { + oitPrograms.delete(); + } + + public static class PipelinePrograms + { + private final ClrwlPrograms clrwlPrograms; + + private PipelinePrograms(ClrwlShaderSources sources, ClrwlPrograms.Pipeline pipeline) + { + this.clrwlPrograms = new ClrwlPrograms(sources, pipeline); + } + + @Nullable + public ClrwlProgram get(ClrwlShaderKey key) + { + return clrwlPrograms.get(key); + } + + public void delete() + { + clrwlPrograms.delete(); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlOitPrograms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlOitPrograms.java new file mode 100644 index 000000000..cb9b00915 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlOitPrograms.java @@ -0,0 +1,103 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import net.irisshaders.iris.compat.flywheel.ClrwlSamplers; +import net.irisshaders.iris.compat.flywheel.compile.component.OitCompositeComponent; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import dev.engine_room.flywheel.backend.compile.core.Compilation; +import dev.engine_room.flywheel.backend.compile.core.CompilationHarness; +import dev.engine_room.flywheel.backend.compile.core.Compile; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import dev.engine_room.flywheel.backend.gl.shader.ShaderType; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.lib.util.ResourceUtil; +import net.minecraft.resources.ResourceLocation; + +import java.util.Collection; +import java.util.List; + +public class ClrwlOitPrograms +{ + public record OitCompositeShaderKey(int[] drawBuffers, int[] ranks, List overrides, boolean isShadow) + { + } + + private static final ResourceLocation FULLSCREEN = ResourceUtil.rl("internal/fullscreen.vert"); + + private static final Compile COMPOSITE = new Compile<>(); + + private final CompilationHarness compositeHarness; + + public ClrwlOitPrograms(ShaderSources sources, ClrwlPrograms.Pipeline pipeline) + { + this.compositeHarness = createCompositePipeline(sources, pipeline); + } + + private static CompilationHarness createCompositePipeline(ShaderSources sources, ClrwlPrograms.Pipeline pipeline) + { + return COMPOSITE.program() + .link(COMPOSITE.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.VERTEX) + .nameMapper(k -> "oit_composite/fullscreen") + .onCompile((k, c) -> defineClrwlPass(k.isShadow(), c)) + .withResource(FULLSCREEN)) + .link(COMPOSITE.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.FRAGMENT) + .nameMapper(k -> "oit_composite/oit_composite" + (k.isShadow() ? "_shadow" : "")) + .onCompile((k, c) -> defineClrwlPass(k.isShadow(), c)) + .onCompile(($, c) -> defineFmaFallback(c, pipeline.extensions())) + .with((k, src) -> new OitCompositeComponent(src, k.drawBuffers(), k.ranks(), k.overrides()))) + .postLink((k, p) -> + { + p.bind(); + p.setUniformBlockBinding(ClrwlUniforms.PASS_BLOCK_NAME, ClrwlUniforms.PASS_INDEX); + + p.setSamplerBinding("_flw_depthRange", ClrwlSamplers.DEPTH_RANGE); + + for (int i = 0; i < k.ranks().length; i++) + { + p.setSamplerBinding("clrwl_coefficients" + i, ClrwlSamplers.getCoefficient(i)); + } + + var drawBuffers = k.drawBuffers(); + + for (int i = 0; i < drawBuffers.length; i++) + { + p.setSamplerBinding("_clrwl_accumulate" + drawBuffers[i], ClrwlSamplers.getAccumulate(i)); + } + + GlProgram.unbind(); + }) + .harness("oit_composite", sources); + } + + public static void defineClrwlPass(boolean isShadow, Compilation c) + { + if (isShadow) + { + c.define("_CLRWL_IS_SHADOW_PASS"); + } + else + { + c.define("_CLRWL_IS_GBUFFERS_PASS"); + } + } + + public static void defineFmaFallback(Compilation c, Collection extensions) + { + if (GlCompat.MAX_GLSL_VERSION.compareTo(GlslVersion.V400) < 0 && !extensions.contains("GL_ARB_gpu_shader5")) + { + c.define("fma(a, b, c)", "((a) * (b) + (c))"); + } + } + + public GlProgram getOitCompositeProgram(int[] drawBuffers, int[] ranks, List overrides, boolean isShadow) + { + return compositeHarness.get(new OitCompositeShaderKey(drawBuffers, ranks, overrides, isShadow)); + } + + public void delete() + { + compositeHarness.delete(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPipelines.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPipelines.java new file mode 100644 index 000000000..f77ebc0a5 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPipelines.java @@ -0,0 +1,97 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.component.SsboInstanceComponent; +import dev.engine_room.flywheel.backend.compile.component.BufferTextureInstanceComponent; +import net.minecraft.resources.ResourceLocation; + +import java.util.Collection; + +public class ClrwlPipelines +{ + public static final ResourceLocation INSTANCING_MAIN_VERT = Colorwheel.rl("internal/instancing/main.vert"); + public static final ResourceLocation INSTANCING_MAIN_GEOM = Colorwheel.rl("internal/instancing/main_geom.glsl"); + public static final ResourceLocation INSTANCING_MAIN_FRAG = Colorwheel.rl("internal/instancing/main.frag"); + + public static final ResourceLocation INDIRECT_MAIN_VERT = Colorwheel.rl("internal/indirect/main.vert"); + public static final ResourceLocation INDIRECT_MAIN_GEOM = Colorwheel.rl("internal/indirect/main_geom.glsl"); + public static final ResourceLocation INDIRECT_MAIN_FRAG = Colorwheel.rl("internal/indirect/main.frag"); + + private static final PipelineBuilder INSTANCING_BUILDER = PipelineBuilder.builder() + .id("instancing") + .extensions(ClrwlInstancedPrograms.EXTENSIONS) + .assembler(BufferTextureInstanceComponent::new) + .vertex(INSTANCING_MAIN_VERT) + .geometry(INSTANCING_MAIN_GEOM) + .fragment(INSTANCING_MAIN_FRAG); + + private static final PipelineBuilder INDIRECT_BUILDER = PipelineBuilder.builder() + .id("indirect") + .extensions(ClrwlIndirectPrograms.EXTENSIONS) + .assembler(SsboInstanceComponent::new) + .vertex(INDIRECT_MAIN_VERT) + .geometry(INDIRECT_MAIN_GEOM) + .fragment(INDIRECT_MAIN_FRAG); + + public static final ClrwlPrograms.Pipeline INSTANCING = INSTANCING_BUILDER.build(false); + public static final ClrwlPrograms.Pipeline INSTANCING_FALLBACK = INSTANCING_BUILDER.build(true); + + public static final ClrwlPrograms.Pipeline INDIRECT = INDIRECT_BUILDER.build(false); + public static final ClrwlPrograms.Pipeline INDIRECT_FALLBACK = INDIRECT_BUILDER.build(true); + + private static class PipelineBuilder + { + private String id; + private Collection extensions; + private ClrwlPrograms.Pipeline.InstanceAssembler assembler; + private ResourceLocation vertex; + private ResourceLocation geometry; + private ResourceLocation fragment; + + static PipelineBuilder builder() + { + return new PipelineBuilder(); + } + + public PipelineBuilder id(String id) + { + this.id = id; + return this; + } + + public PipelineBuilder extensions(Collection extensions) + { + this.extensions = extensions; + return this; + } + + public PipelineBuilder assembler(ClrwlPrograms.Pipeline.InstanceAssembler assembler) + { + this.assembler = assembler; + return this; + } + + public PipelineBuilder vertex(ResourceLocation vertex) + { + this.vertex = vertex; + return this; + } + + public PipelineBuilder geometry(ResourceLocation geometry) + { + this.geometry = geometry; + return this; + } + + public PipelineBuilder fragment(ResourceLocation fragment) + { + this.fragment = fragment; + return this; + } + + public ClrwlPrograms.Pipeline build(boolean fallback) + { + return new ClrwlPrograms.Pipeline(id, fallback, extensions, assembler, vertex, geometry, fragment); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgram.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgram.java new file mode 100644 index 000000000..4ed24430c --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgram.java @@ -0,0 +1,249 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import com.google.common.collect.ImmutableSet; +import net.irisshaders.iris.compat.flywheel.ClrwlSamplers; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlBlendModeOverride; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstanceVisual; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlMaterialEncoder; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlRenderingPhase; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlPackDirectives; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import dev.engine_room.flywheel.api.material.Material; +import dev.engine_room.flywheel.api.material.Transparency; +import dev.engine_room.flywheel.backend.engine.embed.EmbeddingUniforms; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import net.irisshaders.iris.gl.blending.BlendMode; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.mixin.texture.TextureAtlasAccessor; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlas; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3fc; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +import static org.lwjgl.opengl.GL20.glUniform2i; +import static org.lwjgl.opengl.GL20.glUniform4i; + +public class ClrwlProgram extends GlProgram +{ + private final String name; + private final ClrwlProgramId programId; + + private ProgramUniforms uniforms; + private CustomUniforms customUniforms; + private ProgramSamplers samplers; + private ProgramImages images; + + public static ImmutableSet getReservedTextureUnits(int coeffCount) + { + List res = new ArrayList<>(); + + res.add(ClrwlSamplers.DIFFUSE.number); + res.add(ClrwlSamplers.OVERLAY.number); + res.add(ClrwlSamplers.LIGHT.number); + res.add(ClrwlSamplers.CRUMBLING.number); + res.add(ClrwlSamplers.INSTANCE_BUFFER.number); + res.add(ClrwlSamplers.LIGHT_LUT.number); + res.add(ClrwlSamplers.LIGHT_SECTIONS.number); + + // OIT Samplers + res.add(ClrwlSamplers.DEPTH_RANGE.number); + res.add(ClrwlSamplers.NOISE.number); + + for (int i = 0; i < coeffCount; i++) + { + res.add(ClrwlSamplers.getCoefficient(i).number); + } + + return ImmutableSet.copyOf(res); + } + + public ClrwlProgram(String name, ClrwlProgramId programId, int handle) + { + super(handle); + this.name = name; + this.programId = programId; + } + + public void preLink() + { + bindAttribLocation("_flw_aPos", 0); + bindAttribLocation("_flw_aColor", 1); + bindAttribLocation("_flw_aTexCoord", 2); + bindAttribLocation("_flw_aLight", 3); + bindAttribLocation("_flw_aNormal", 4); + bindAttribLocation("_clrwl_aEntity", 5); + bindAttribLocation("_clrwl_aMidTexCoord", 6); + bindAttribLocation("_clrwl_aTangent", 7); + bindAttribLocation("_clrwl_aMidBlock", 8); + bindAttribLocation("_flw_aOverlay", 9); + } + + public void postLink(IrisRenderingPipeline irisPipeline, ClrwlPackDirectives directives) + { + var handle = handle(); + var customUniforms = irisPipeline.getCustomUniforms(); + var oitConfig = directives.getOitConfig(programId.group()); + var oitRanks = oitConfig.coeffRanks(); + + ProgramUniforms.Builder uniformBuilder = ProgramUniforms.builder(name, handle); + ProgramSamplers.Builder samplerBuilder = ProgramSamplers.builder(handle, getReservedTextureUnits(oitRanks.length)); + ProgramImages.Builder imageBuilder = ProgramImages.builder(handle); + + samplerBuilder.addExternalSampler(ClrwlSamplers.DIFFUSE.number, "flw_diffuseTex"); + samplerBuilder.addExternalSampler(ClrwlSamplers.OVERLAY.number, "flw_overlayTex"); + // samplerBuilder.addExternalSampler(ClrwlSamplers.LIGHT.number, "flw_lightTex"); + samplerBuilder.addExternalSampler(ClrwlSamplers.CRUMBLING.number, "_flw_crumblingTex"); + samplerBuilder.addExternalSampler(ClrwlSamplers.INSTANCE_BUFFER.number, "_flw_instances"); + samplerBuilder.addExternalSampler(ClrwlSamplers.LIGHT_LUT.number, "_flw_lightLut"); + samplerBuilder.addExternalSampler(ClrwlSamplers.LIGHT_SECTIONS.number, "_flw_lightSections"); + samplerBuilder.addExternalSampler(ClrwlSamplers.DEPTH_RANGE.number, "_flw_depthRange"); + samplerBuilder.addExternalSampler(ClrwlSamplers.NOISE.number, "_flw_blueNoise"); + + for (int i = 0; i < oitRanks.length; i++) + { + samplerBuilder.addExternalSampler(ClrwlSamplers.getCoefficient(i).number, "clrwl_coefficients" + i); + } + + var isShadowPass = programId.group() == ClrwlProgramGroup.SHADOW; + Supplier> flipped = isShadowPass + ? irisPipeline::getFlippedBeforeShadow + : programId.afterTranslucent() + ? irisPipeline::getFlippedAfterTranslucent + : irisPipeline::getFlippedAfterPrepare; + + CommonUniforms.addDynamicUniforms(uniformBuilder, FogMode.PER_VERTEX); + customUniforms.assignTo(uniformBuilder); + irisPipeline.addGbufferOrShadowSamplers(samplerBuilder, imageBuilder, + flipped, isShadowPass, + false, true, false); // Use Flywheel texture and overlay samplers + customUniforms.mapholderToPass(uniformBuilder, this); + + this.uniforms = uniformBuilder.buildUniforms(); + this.customUniforms = customUniforms; + this.samplers = samplerBuilder.build(); + this.images = imageBuilder.build(); + + ClrwlUniforms.setUniformsBlockBindings(this); + } + + public String name() + { + return name; + } + + public void bind() + { + super.bind(); + + samplers.update(); + uniforms.update(); + customUniforms.push(this); + images.update(); + } + + public static void unbind() + { + ProgramUniforms.clearActiveUniforms(); + ProgramSamplers.clearActiveSamplers(); + } + + public void setClrwlCommonUniforms(Material material, ClrwlBlendModeOverride blendModeOverride, ClrwlRenderingPhase phase) + { + var abstractTexture = Minecraft.getInstance().getTextureManager().getTexture(material.texture()); + int atlasWidth = 0; + int atlasHeight = 0; + + if (abstractTexture instanceof TextureAtlas atlas) + { + atlasWidth = ((TextureAtlasAccessor) atlas).callGetWidth(); + atlasHeight = ((TextureAtlasAccessor) atlas).callGetHeight(); + } + + BlendMode blendMode; + + if (blendModeOverride != null) + { + if (blendModeOverride.blendMode() != null) + { + blendMode = blendModeOverride.blendMode(); + } + else + { + blendMode = Utils.transparencyToBlendMode(Transparency.OPAQUE); + } + } + else + { + blendMode = Utils.transparencyToBlendMode(material.transparency()); + } + + setIVec4("_clrwl_blendFunc", blendMode.srcRgb(), blendMode.dstRgb(), blendMode.srcAlpha(), blendMode.dstAlpha()); + setIVec2("_clrwl_atlasSize", atlasWidth, atlasHeight); + setInt("_clrwl_renderPhase", phase.getValue()); + } + + public void setInstancingUniforms(int baseVertex, int baseInstance, Material material, ClrwlInstanceVisual visual, Vector3fc meshCenter) + { + int packedMaterialProperties = ClrwlMaterialEncoder.packProperties(material); + + setUInt("_flw_baseVertex", baseVertex); + setInt("_flw_baseInstance", baseInstance); + setUInt("_clrwl_packedMaterialUniform", packedMaterialProperties); + + setInt("_clrwl_blockEntityIdUniform", visual.getBlockEntity()); + setInt("_clrwl_entityIdUniform", visual.getEntity()); + setVec4("_clrwl_meshCenterUniform", meshCenter.x(), meshCenter.y(), meshCenter.z(), (float) visual.lightEmission()); + } + + public void setBaseDrawUniform(int baseDraw) + { + setUInt("_flw_baseDraw", baseDraw); + } + + public void setEmbeddedMatrices(Matrix4f model, Matrix3f normal) + { + setMat4(EmbeddingUniforms.MODEL_MATRIX, model); + setMat3(EmbeddingUniforms.NORMAL_MATRIX, normal); + } + + public void free() + { + super.delete(); + } + + public void setIVec2(String glslName, int x, int y) + { + int uniform = getUniformLocation(glslName); + + if (uniform < 0) { + return; + } + + glUniform2i(uniform, x, y); + } + + public void setIVec4(String glslName, int x, int y, int z, int w) + { + int uniform = getUniformLocation(glslName); + + if (uniform < 0) { + return; + } + + glUniform4i(uniform, x, y, z, w); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgramSources.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgramSources.java new file mode 100644 index 000000000..e3c224f18 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlProgramSources.java @@ -0,0 +1,112 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import net.irisshaders.iris.compat.flywheel.compile.transform.ClrwlComputeTransformPatcher; +import net.irisshaders.iris.compat.flywheel.compile.transform.ClrwlTransformOutput; +import net.irisshaders.iris.compat.flywheel.compile.transform.ClrwlTransformPatcher; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlPackPrograms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; + +import java.util.*; + +public class ClrwlProgramSources +{ + private final IrisRenderingPipeline irisPipeline; + private final ProgramSet programSet; + private final Map gbuffersSources; + private final Map computeSources; + + public ClrwlProgramSources(IrisRenderingPipeline irisPipeline, ProgramSet programSet) + { + this.irisPipeline = irisPipeline; + this.programSet = programSet; + this.gbuffersSources = new HashMap<>(); + this.computeSources = new HashMap<>(); + } + + public PatchedGbuffersSources getGbuffersSources(ClrwlProgramId programId, ClrwlPrograms.OitMode oit) + { + ClrwlPackPrograms programAccessor = programSet.getClrwlPrograms(); + ClrwlProgramId realProgramId = programAccessor.getRealClrwlProgram(programId).orElseThrow(); + + var isCrumbling = programId == ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK; + var customOutputs = oit == ClrwlPrograms.OitMode.DEPTH_RANGE || oit == ClrwlPrograms.OitMode.GENERATE_COEFFICIENTS; + + var key = new GbuffersKey(realProgramId, isCrumbling, customOutputs); + + return gbuffersSources.computeIfAbsent(key, this::patchGbuffersSources); + } + + public PatchedComputeSource getComputeSource(ComputeSource source) + { + var key = new ComputeKey(source.getSource().orElseThrow()); + return computeSources.computeIfAbsent(key, this::patchComputeSource); + } + + private PatchedGbuffersSources patchGbuffersSources(GbuffersKey k) + { + ClrwlPackPrograms programAccessor = programSet.getClrwlPrograms(); + ProgramSource sources = programAccessor.getClrwlProgramSource(k.realProgramId()).orElseThrow(); + EnumMap> extensions = new EnumMap<>(ClrwlShaderType.class); + extensions.put(ClrwlShaderType.VERTEX, parseShaderExtensions(sources.getSourceNullable(ShaderType.VERTEX))); + extensions.put(ClrwlShaderType.GEOMETRY, parseShaderExtensions(sources.getSourceNullable(ShaderType.GEOM))); + extensions.put(ClrwlShaderType.FRAGMENT, parseShaderExtensions(sources.getSourceNullable(ShaderType.FRAGMENT))); + int[] drawBuffers = sources.getDirectives().getDrawBuffers(); + + String vertexSource = ClrwlTransformPatcher.patchVertex(sources.getSource(ShaderType.VERTEX).orElseThrow(), k.isCrumbling(), irisPipeline.getTextureMap()); + Optional geometrySource = sources.getSource(ShaderType.GEOM).map(s -> ClrwlTransformPatcher.patchGeometry(s, k.isCrumbling(), irisPipeline.getTextureMap())); + ClrwlTransformOutput fragmentSource = ClrwlTransformPatcher.patchFragment(sources.getSource(ShaderType.FRAGMENT).orElseThrow(), k.isCrumbling(), k.customOutputs(), irisPipeline.getTextureMap()); + + return new PatchedGbuffersSources(vertexSource, geometrySource, fragmentSource, extensions, drawBuffers); + } + + private PatchedComputeSource patchComputeSource(ComputeKey k) + { + var patchedSrc = ClrwlComputeTransformPatcher.patchCompute(k.shader(), irisPipeline.getTextureMap()); + return new PatchedComputeSource(patchedSrc); + } + + private static List parseShaderExtensions(String source) + { + List res = new ArrayList<>(); + + if (source == null) + { + return res; + } + + source.lines().forEach(line -> + { + line = line.trim(); + + if (line.startsWith("#extension ") && line.contains(":")) + { + res.add(line.substring(11).split(":")[0].trim()); + } + }); + + return res; + } + + private record GbuffersKey(ClrwlProgramId realProgramId, boolean isCrumbling, boolean customOutputs) + { + } + + public record PatchedGbuffersSources(String vertex, Optional geometry, ClrwlTransformOutput fragment, + EnumMap> extensions, int[] drawBuffers) + { + } + + public record ComputeKey(String shader) + { + } + + public record PatchedComputeSource(String shader) + { + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPrograms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPrograms.java new file mode 100644 index 000000000..2d3d87031 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlPrograms.java @@ -0,0 +1,413 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.component.*; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlCompilation; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlCompilationHarness; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlCompile; +import net.irisshaders.iris.compat.flywheel.compile.core.ClrwlShaderSources; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlVertex; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlPackDirectives; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.backend.BackendConfig; +import dev.engine_room.flywheel.backend.compile.component.InstanceStructComponent; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.lib.material.CutoutShaders; +import dev.engine_room.flywheel.lib.util.ResourceUtil; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +public class ClrwlPrograms +{ + public enum OitMode + { + OFF("", ""), + DEPTH_RANGE("CLRWL_DEPTH_RANGE", "_depth_range"), + GENERATE_COEFFICIENTS("CLRWL_COLLECT_COEFFS", "_generate_coefficients"), + EVALUATE("CLRWL_EVALUATE", "_resolve"), + ; + + public final String define; + public final String name; + + OitMode(String define, String name) + { + this.define = define; + this.name = name; + } + } + + public record Pipeline(String id, boolean fallback, + Collection extensions, InstanceAssembler assembler, + ResourceLocation vertex, ResourceLocation geometry, ResourceLocation fragment) + { + public interface InstanceAssembler + { + SourceComponent assemble(InstanceType type); + } + } + + public static final ResourceLocation API_IMPL_VERT = Colorwheel.rl("internal/api_impl.vert"); + public static final ResourceLocation API_IMPL_GEOM = Colorwheel.rl("internal/api_impl_geom.glsl"); + public static final ResourceLocation API_IMPL_FRAG = Colorwheel.rl("internal/api_impl.frag"); + + public static final ResourceLocation IRIS_COMPAT_VERT = Colorwheel.rl("internal/iris_compat.vert"); + public static final ResourceLocation IRIS_COMPAT_GEOM = Colorwheel.rl("internal/iris_compat_geom.glsl"); + public static final ResourceLocation IRIS_COMPAT_FRAG = Colorwheel.rl("internal/iris_compat.frag"); + + public static final ResourceLocation OIT_DEPTH_RANGE_FRAG = Colorwheel.rl("internal/oit/depth_range.frag"); + + public static final String CLRWL_POST_FRAGMENT_FCT = "_clrwl_post_shader"; + + private static final ClrwlCompile PIPELINE = new ClrwlCompile<>(); + + private final ClrwlCompilationHarness pipelineHarness; + private final ProgramSet programSet; + + public ClrwlPrograms(ClrwlShaderSources sources, Pipeline pipeline) + { + this.pipelineHarness = createPipeline(sources, pipeline); + this.programSet = sources.programSet(); + } + + private static ClrwlCompilationHarness createPipeline(ClrwlShaderSources sources, Pipeline pipeline) + { + ClrwlPackDirectives directives = sources.programSet().getClrwlPrograms().getClrwlDirectives(); + + var vert = PIPELINE.shader(GlCompat.MAX_GLSL_VERSION, ClrwlShaderType.VERTEX) + .nameMapper(k -> + { + var program = getProgram(k); + var instance = ResourceUtil.toDebugFileNameNoExtension(k.instanceType().vertexShader()); + var material = ResourceUtil.toDebugFileNameNoExtension(k.material().vertexSource()); + var context = k.context().nameLowerCase(); + var debug = k.isDebugEnabled() ? "_debug" : ""; + return "pipeline/" + pipeline.id() + "/" + program.programName() + "/vert/" + instance + "/" + material + "_" + context + debug; + }) + .onCompile((k, c) -> setDefines(k, c, sources, pipeline, ClrwlShaderType.VERTEX)) + .requireExtensions(pipeline.extensions()) + .withResource(API_IMPL_VERT) + .withComponent(k -> new InstanceStructComponent(k.instanceType())) + .withResource(k -> k.instanceType().vertexShader()) + .withResource(k -> k.material().vertexSource()) + .withResource(ClrwlVertex.LAYOUT_SHADER) + .withResource(IRIS_COMPAT_VERT) + .withComponent(k -> pipeline.assembler().assemble(k.instanceType())) + .withComponent(k -> getIrisShaderSource(k, sources, pipeline, ClrwlShaderType.VERTEX)) + .withResource(pipeline.vertex()); + + var geom = PIPELINE.shader(GlCompat.MAX_GLSL_VERSION, ClrwlShaderType.GEOMETRY) + .nameMapper(k -> + { + var program = getProgram(k); + var instance = ResourceUtil.toDebugFileNameNoExtension(k.instanceType().vertexShader()); + var material = ResourceUtil.toDebugFileNameNoExtension(k.material().vertexSource()); + var context = k.context().nameLowerCase(); + var debug = k.isDebugEnabled() ? "_debug" : ""; + return "pipeline/" + pipeline.id() + "/" + program.programName() + "/geom/" + instance + "/" + material + "_" + context + debug; + }) + .condition(ClrwlPrograms::hasGeometryShader) + .onCompile((k, c) -> setDefines(k, c, sources, pipeline, ClrwlShaderType.GEOMETRY)) + .requireExtensions(pipeline.extensions()) + .withResource(API_IMPL_GEOM) + .withResource(IRIS_COMPAT_GEOM) + .withComponent(k -> getIrisShaderSource(k, sources, pipeline, ClrwlShaderType.GEOMETRY)) + .withResource(pipeline.geometry()); + + var frag = PIPELINE.shader(GlCompat.MAX_GLSL_VERSION, ClrwlShaderType.FRAGMENT) + .nameMapper(k -> + { + var program = getProgram(k); + var context = k.context().nameLowerCase(); + var material = ResourceUtil.toDebugFileNameNoExtension(k.material().fragmentSource()); + var light = ResourceUtil.toDebugFileNameNoExtension(k.light().source()); + var debug = k.isDebugEnabled() ? "_debug" : ""; + var cutout = k.cutout() != CutoutShaders.OFF ? "_cutout" : ""; + var oit = k.oit().name; + return "pipeline/" + pipeline.id() + "/" + program.programName() + "/frag/" + material + "/" + light + "_" + context + cutout + debug + oit; + }) + .onCompile((k, c) -> setDefines(k, c, sources, pipeline, ClrwlShaderType.FRAGMENT)) + .requireExtensions(pipeline.extensions()) + .enableExtension("GL_ARB_conservative_depth") + .withResource(API_IMPL_FRAG) + .withResource(k -> k.cutout().source()); + + if (!pipeline.fallback()) + { + frag.withResource(k -> k.material().fragmentSource()) + .withResource(k -> k.fog().source()) + .withResource(k -> k.light().source()) + .withResource(IRIS_COMPAT_FRAG) + .withComponent(k -> getOitInouts(k, directives)) + .with((k, src) -> getIrisShaderSource(k, src, pipeline, ClrwlShaderType.FRAGMENT)) + .withResource(pipeline.fragment()) + .with((k, src) -> getPostShaderFragmentSource(k, src, pipeline, directives)); + } + else + { + frag.withResource(IRIS_COMPAT_FRAG) + .withComponent(k -> getIrisShaderSource(k, sources, pipeline, ClrwlShaderType.FRAGMENT)) + .withResource(pipeline.fragment()) + .with((k, src) -> getFallbackCutoutFragmentSource(k, src, pipeline)); + } + + return PIPELINE.program() + .link(vert).link(geom).link(frag) + .preLink(($, p) -> p.preLink()) + .postLink(($, p) -> p.postLink(sources.irisPipeline(), directives)) + .harness(pipeline.id(), sources, (k, h) -> + { + var instanceName = ResourceUtil.toDebugFileNameNoExtension(k.instanceType().vertexShader()); + var materialName = ResourceUtil.toDebugFileNameNoExtension(k.material().vertexSource()); + var contextName = k.context().nameLowerCase(); + var oitName = k.oit().name; + var program = getProgram(k); + + String name = String.format("%s/%s/%s_%s%s", program.programName(), instanceName, materialName, contextName, oitName); + + return new ClrwlProgram(name, program, h); + }); + } + + private static void setDefines(ClrwlShaderKey k, ClrwlCompilation c, ClrwlShaderSources sources, Pipeline pipeline, ClrwlShaderType type) + { + c.define("CLRWL_IS_" + pipeline.id().toUpperCase(Locale.ROOT)); + + defineClrwlPass(k.isShadow(), c); + defineFmaFallback(c, pipeline.extensions()); + + if (pipeline.fallback()) + { + c.define("_CLRWL_IS_FALLBACK"); + } + else if (k.oit() != OitMode.OFF) + { + c.define("CLRWL_OIT"); + c.define(k.oit().define); + } + + if (k.isDebugEnabled()) + { + c.define("_FLW_DEBUG"); + } + + if (k.cutout() != CutoutShaders.OFF) + { + c.define("_FLW_USE_DISCARD"); + } + + switch (k.context()) + { + case DEFAULT -> {} + case CRUMBLING -> c.define("_FLW_CRUMBLING"); + case EMBEDDED -> c.define("FLW_EMBEDDED"); + } + + switch (BackendConfig.INSTANCE.lightSmoothness()) + { + case FLAT ->c.define("_FLW_LIGHT_SMOOTHNESS", "0"); + case TRI_LINEAR -> c.define("_FLW_LIGHT_SMOOTHNESS", "1"); + case SMOOTH -> c.define("_FLW_LIGHT_SMOOTHNESS", "2"); + case SMOOTH_INNER_FACE_CORRECTED -> + { + c.define("_FLW_LIGHT_SMOOTHNESS", "2"); + c.define("_FLW_INNER_FACE_CORRECTION"); + } + } + + PackDirectives packDirectives = sources.programSet().getPackDirectives(); + + if (packDirectives.isOldLighting()) + { + c.define("CLRWL_OLD_LIGHTING"); + } + + if (packDirectives.shouldUseSeparateAo()) + { + c.define("_CLRWL_SEPARATE_AO"); + } + + var program = getProgram(k); + var src = sources.clrwlSources().getGbuffersSources(program, k.oit()); + var exts = src.extensions().get(type); + + for (var ext : exts) + { + c.enableExtension(ext); + } + } + + public static void defineClrwlPass(boolean isShadow, ClrwlCompilation c) + { + if (isShadow) + { + c.define("_CLRWL_IS_SHADOW_PASS"); + } + else + { + c.define("_CLRWL_IS_GBUFFERS_PASS"); + } + } + + private static void defineFmaFallback(ClrwlCompilation c, Collection extensions) + { + if (GlCompat.MAX_GLSL_VERSION.compareTo(GlslVersion.V400) < 0 && !extensions.contains("GL_ARB_gpu_shader5")) + { + c.define("fma(a, b, c)", "((a) * (b) + (c))"); + } + } + + private static boolean hasGeometryShader(ClrwlShaderKey key, ClrwlShaderSources sources) + { + var program = getProgram(key); + var maybeSrc = sources.programSet().getClrwlPrograms().getClrwlProgramSource(program); + return maybeSrc.map(src -> src.getSource(ShaderType.GEOM).isPresent()).orElse(false); + } + + private static ClrwlProgramId getProgram(ClrwlShaderKey k) + { + return ClrwlProgramId.fromTransparency(k.transparency(), k.isShadow()); + } + + private static SourceComponent getIrisShaderSource(ClrwlShaderKey k, ClrwlShaderSources sources, Pipeline pipeline, ClrwlShaderType type) + { + var program = getProgram(k); + var src = sources.clrwlSources().getGbuffersSources(program, k.oit()); + var name = program.programName(); + + switch (type) + { + case VERTEX -> { return new IrisShaderComponent(name + ".vsh", src.vertex()); } + case GEOMETRY -> { return new IrisShaderComponent(name + ".gsh", src.geometry().orElseThrow()); } + case FRAGMENT -> { return new IrisShaderComponent(name + ".fsh", src.fragment().code()); } + } + + throw new RuntimeException("Got unexpected ShaderType: " + type); + } + + private static SourceComponent getOitInouts(ClrwlShaderKey k, ClrwlPackDirectives directives) + { + var programGroup = ClrwlProgramGroup.fromShadow(k.isShadow()); + + if (k.oit() == OitMode.GENERATE_COEFFICIENTS) + { + var ranks = directives.getOitConfig(programGroup).coeffRanks(); + return new OitCoefficientsOutputComponent(ranks); + } + else if (k.oit() == OitMode.EVALUATE) + { + var ranks = directives.getOitConfig(programGroup).coeffRanks(); + return new OitCoefficientsSamplersComponent(ranks.length); + } + else + { + return new EmptyComponent(); + } + } + + private static SourceComponent getPostShaderFragmentSource(ClrwlShaderKey k, ClrwlShaderSources sources, Pipeline pipeline, ClrwlPackDirectives directives) + { + var programId = getProgram(k); + var programGroup = programId.group(); + + switch (k.oit()) + { + case DEPTH_RANGE -> + { + return sources.flwSources().get(OIT_DEPTH_RANGE_FRAG); + } + + case GENERATE_COEFFICIENTS -> + { + var src = sources.clrwlSources().getGbuffersSources(programId, k.oit()); + var drawBuffers = src.drawBuffers(); + var config = directives.getOitConfig(programGroup); + + Map coeffFrag = new HashMap<>(); + + for (int i = 0; i < drawBuffers.length; i++) + { + int buffer = drawBuffers[i]; + var maybeCoeffId = Utils.findFirst(config.accumulateOverrides(), e -> e.drawBuffer() == buffer) + .flatMap(ClrwlOitAccumulateOverride::coefficientId); + + if (maybeCoeffId.isPresent()) + { + coeffFrag.putIfAbsent(maybeCoeffId.get(), i); + } + } + + return new OitCollectCoeffsComponent(config.coeffRanks(), coeffFrag, src.fragment().outputs()); + } + + case EVALUATE -> + { + var src = sources.clrwlSources().getGbuffersSources(programId, k.oit()); + var drawBuffers = src.drawBuffers(); + var config = directives.getOitConfig(programGroup); + var outputs = src.fragment().outputs(); + + return new OitEvaluateComponent(drawBuffers, config.coeffRanks(), config.accumulateOverrides(), outputs); + } + } + + return new NoopFunctionComponent(CLRWL_POST_FRAGMENT_FCT); + } + + private static SourceComponent getFallbackCutoutFragmentSource(ClrwlShaderKey k, ClrwlShaderSources sources, Pipeline pipeline) + { + var programId = getProgram(k); + var src = sources.clrwlSources().getGbuffersSources(programId, k.oit()); + return new FallbackCutoutComponent(src.fragment().outputs()); + } + + @Nullable + public ClrwlProgram get(ClrwlShaderKey key) + { + if (brokenShaders.contains(key)) + { + return null; + } + + try + { + return pipelineHarness.get(key); + } + catch (Exception e) + { + handleBrokenShader(key, e); + return null; + } + } + + private final Set brokenShaders = new HashSet<>(); + + private void handleBrokenShader(ClrwlShaderKey key, Exception e) + { + var program = getProgram(key); + + brokenShaders.add(key); + + ClrwlProgramId realProgramId = programSet.getClrwlPrograms().getRealClrwlProgram(program).orElse(program); + String shaderPath = realProgramId.programName() + "/" + key.getPath(); + + Colorwheel.LOGGER.error("Could not compile shader: " + shaderPath, e); + } + + public void delete() + { + pipelineHarness.delete(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlShaderKey.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlShaderKey.java new file mode 100644 index 000000000..011f142ba --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/ClrwlShaderKey.java @@ -0,0 +1,34 @@ +package net.irisshaders.iris.compat.flywheel.compile; + +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlFrameUniforms; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.material.*; +import dev.engine_room.flywheel.backend.compile.ContextShader; +import dev.engine_room.flywheel.lib.util.ResourceUtil; + +public record ClrwlShaderKey(InstanceType instanceType, + MaterialShaders material, + FogShader fog, + CutoutShader cutout, + LightShader light, + Transparency transparency, + ContextShader context, + boolean isShadow, + boolean isDebugEnabled, + ClrwlPrograms.OitMode oit) +{ + public static ClrwlShaderKey fromMaterial(InstanceType instanceType, Material material, ContextShader context, boolean isShadow, ClrwlPrograms.OitMode oit) + { + return new ClrwlShaderKey(instanceType, material.shaders(), material.fog(), material.cutout(), material.light(), material.transparency(), context, isShadow, ClrwlFrameUniforms.debugOn(), oit); + } + + public String getPath() + { + var instanceName = ResourceUtil.toDebugFileNameNoExtension(instanceType.vertexShader()); + var materialName = ResourceUtil.toDebugFileNameNoExtension(material.vertexSource()); + var contextName = context.nameLowerCase(); + var debug = isDebugEnabled ? "_debug" : ""; + + return instanceName + '/' + materialName + '_' + contextName + oit.name + debug; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/EmptyComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/EmptyComponent.java new file mode 100644 index 000000000..ddd4f0218 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/EmptyComponent.java @@ -0,0 +1,28 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; + +import java.util.Collection; +import java.util.List; + +public class EmptyComponent implements SourceComponent +{ + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + return ""; + } + + @Override + public String name() + { + return Colorwheel.rl("empty").getPath(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/FallbackCutoutComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/FallbackCutoutComponent.java new file mode 100644 index 000000000..f8ad164a6 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/FallbackCutoutComponent.java @@ -0,0 +1,58 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.FnSignature; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBlock; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class FallbackCutoutComponent implements SourceComponent +{ + private final Map shaderOutputs; + + public FallbackCutoutComponent(Map shaderOutputs) + { + this.shaderOutputs = shaderOutputs; + } + + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + // output 0 is assumed to be diffuse, too bad if it isn't + var outName = shaderOutputs.get(0); + + var builder = new GlslBuilder(); + var body = new GlslBlock(); + + if (outName != null) + { + body.raw("clrwl_computeDiscard(" + outName + ");"); + } + + builder.function() + .signature(FnSignature.create() + .returnType("void") + .name(ClrwlPrograms.CLRWL_POST_FRAGMENT_FCT) + .build()) + .body(body); + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("fallback_cutout").toString(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/IrisShaderComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/IrisShaderComponent.java new file mode 100644 index 000000000..4192a0ba3 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/IrisShaderComponent.java @@ -0,0 +1,14 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import dev.engine_room.flywheel.backend.glsl.SourceComponent; + +import java.util.Collection; +import java.util.List; + +public record IrisShaderComponent(String name, String source) implements SourceComponent +{ + @Override + public Collection included() { + return List.of(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/NoopFunctionComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/NoopFunctionComponent.java new file mode 100644 index 000000000..b26709fff --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/NoopFunctionComponent.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; + +import java.util.Collection; +import java.util.Collections; + +public class NoopFunctionComponent implements SourceComponent +{ + private final String name; + + public NoopFunctionComponent(String name) + { + this.name = name; + } + + @Override + public Collection included() + { + return Collections.emptyList(); + } + + @Override + public String source() + { + return "void " + name + "() {}"; + } + + @Override + public String name() + { + return Colorwheel.rl(name + "_noop").toString(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsOutputComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsOutputComponent.java new file mode 100644 index 000000000..c3f64195b --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsOutputComponent.java @@ -0,0 +1,57 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.glsl.GlslFragmentOutput; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; + +import java.util.Collection; +import java.util.List; + +public class OitCoefficientsOutputComponent implements SourceComponent +{ + private final int[] ranks; + + public OitCoefficientsOutputComponent(int[] ranks) + { + this.ranks = ranks; + } + + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + var builder = new GlslBuilder(); + int idx = 0; + + for (int i = 0; i < ranks.length; i++) + { + int rank = ranks[i]; + int depth = 1 << (rank - 1); + + for (int d = 0; d < depth; d++) + { + var out = new GlslFragmentOutput() + .binding(idx) + .type("vec4") + .name(("clrwl_coeffs" + i) + d); + + builder.add(out); + idx += 1; + } + } + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("oit_coefficients_output").toString(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsSamplersComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsSamplersComponent.java new file mode 100644 index 000000000..e3accc71c --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCoefficientsSamplersComponent.java @@ -0,0 +1,53 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; +import dev.engine_room.flywheel.backend.glsl.generate.GlslUniform; + +import java.util.Collection; +import java.util.List; + +public class OitCoefficientsSamplersComponent implements SourceComponent +{ + private final int coeffCount; + + public OitCoefficientsSamplersComponent(int coeffCount) + { + this.coeffCount = coeffCount; + } + + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + var builder = new GlslBuilder(); + + addSamplers(builder, coeffCount); + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("oit_coefficients_samplers").toString(); + } + + public static void addSamplers(GlslBuilder builder, int coeffCount) + { + for (int i = 0; i < coeffCount; i++) + { + var uniform = new GlslUniform() + .type("sampler2DArray") + .name("clrwl_coefficients" + i); + + builder.add(uniform); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCollectCoeffsComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCollectCoeffsComponent.java new file mode 100644 index 000000000..489eeadd8 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCollectCoeffsComponent.java @@ -0,0 +1,97 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.FnSignature; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBlock; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; +import dev.engine_room.flywheel.backend.glsl.generate.GlslStmt; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class OitCollectCoeffsComponent implements SourceComponent +{ + private final int[] ranks; + private final Map coeffFrag; + private final Map shaderOutputs; + + public OitCollectCoeffsComponent(int[] ranks, Map coeffFrag, Map shaderOutputs) + { + this.ranks = ranks; + this.coeffFrag = coeffFrag; + this.shaderOutputs = shaderOutputs; + } + + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + var builder = new GlslBuilder(); + var body = new GlslBlock(); + + body.add(GlslStmt.raw("float linearDepth = _clrwl_linear_depth();")); + body.add(GlslStmt.raw("vec2 depthRange = texelFetch(_flw_depthRange, ivec2(gl_FragCoord.xy), 0).rg;")); + body.add(GlslStmt.raw("float delta = depthRange.x + depthRange.y;")); + body.add(GlslStmt.raw("float flw_depth = (linearDepth + depthRange.x) / delta;")); + body.add(GlslStmt.raw("float depth_adjustment = _clrwl_tented_blue_noise(flw_depth) * _flw_oitNoise;")); + body.add(GlslStmt.raw("")); + + for (int i = 0; i < ranks.length; i++) + { + int rank = ranks[i]; + int frag = coeffFrag.get(i); + int depth = 1 << (rank - 1); + + String name = "clrwl_coeffs" + i; + String fragData = shaderOutputs.get(frag); + String transmittance = "transmittance" + i; + String adjusted_depth = "adjusted_depth" + i; + + body.add(GlslStmt.raw("float " + transmittance + " = 1.0 - " + fragData + ".a;")); + body.add(GlslStmt.raw("float " + adjusted_depth + " = flw_depth;")); + + // Don't do the depth adjustment if this fragment is opaque. + body.add(GlslStmt.raw("if (" + transmittance + " > 1e-5) { " + adjusted_depth + " -= depth_adjustment; } ")); + + body.add(GlslStmt.raw("vec4[4] " + name + ";")); + + for (int d = 0; d < depth; d++) + { + body.add(GlslStmt.raw(name + "[" + d +"] = vec4(0.);")); + } + + body.add(GlslStmt.raw("_clrwl_add_transmittance(" + name + ", " + transmittance + ", " + adjusted_depth + ", " + rank + ");")); + + for (int d = 0; d < depth; d++) + { + // clrwl_coeffs12 + String outName = name + d; + + body.add(GlslStmt.raw(outName + " = " + name + "[" + d + "];")); + } + } + + builder.function() + .signature(FnSignature.create() + .returnType("void") + .name(ClrwlPrograms.CLRWL_POST_FRAGMENT_FCT) + .build()) + .body(body); + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("oit_collect_coeffs").toString(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCompositeComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCompositeComponent.java new file mode 100644 index 000000000..5fc7caf64 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitCompositeComponent.java @@ -0,0 +1,137 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.glsl.GlslFragmentOutput; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.FnSignature; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBlock; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; +import dev.engine_room.flywheel.backend.glsl.generate.GlslUniform; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +public class OitCompositeComponent implements SourceComponent +{ + private final ShaderSources sources; + private final int[] drawBuffers; + private final int[] ranks; + private final List overrides; + + public OitCompositeComponent(ShaderSources sources, int[] drawBuffers, int[] ranks, List overrides) + { + this.sources = sources; + this.drawBuffers = drawBuffers; + this.ranks = ranks; + this.overrides = overrides; + } + + @Override + public Collection included() + { + return List.of( + sources.get(Colorwheel.rl("internal/oit/wavelet.glsl")), + sources.get(Colorwheel.rl("internal/uniforms.glsl")), + sources.get(Colorwheel.rl("internal/depth.glsl")) + ); + } + + @Override + public String source() + { + var builder = new GlslBuilder(); + + OitCoefficientsSamplersComponent.addSamplers(builder, ranks.length); + addAccumulateSamplers(builder, drawBuffers); + builder.uniform().type("sampler2D").name("_flw_depthRange"); + + addOutputs(builder, drawBuffers.length); + + var body = new GlslBlock(); + + body.raw("float minDepth = -texelFetch(_flw_depthRange, ivec2(gl_FragCoord.xy), 0).r;"); + + // Required otherwise depth buffer is corrupted + body.raw("if (minDepth == _flw_cullData.zfar) { discard; }"); + + body.raw("gl_FragDepth = _clrwl_delinearize_depth(minDepth, _flw_cullData.znear, _flw_cullData.zfar);"); + + for (int i = 0; i < ranks.length; i++) + { + var rank = ranks[i]; + + var name = "total_transmittance" + i; + var coeffName = "clrwl_coefficients" + i; + + body.raw("float " + name + " = _clrwl_total_transmittance(" + coeffName + ", " + rank + ");"); + } + + for (int i = 0; i < drawBuffers.length; i++) + { + var drawBuffer = drawBuffers[i]; + Optional coeffId = Utils.findFirst(overrides, e -> e.drawBuffer() == drawBuffer) + .flatMap(ClrwlOitAccumulateOverride::coefficientId); + + var accumulate = "_clrwl_accumulate" + drawBuffer; + var out = "frag" + i; + + if (coeffId.isPresent()) + { + var texelName = "texelTranslucent" + drawBuffer; + var totalName = "total_transmittance" + coeffId.get(); + + body.raw("vec4 " + texelName + " = texelFetch(" + accumulate + ", ivec2(gl_FragCoord.xy), 0);"); + body.raw("if (" + texelName + ".a >= 1e-5) {"); + body.raw(" " + out + " = vec4(" + texelName + ".rgb / " + texelName + ".a, 1. - " + totalName + ");"); + body.raw("} else {"); + body.raw(" " + out + " = vec4(0.0);"); + body.raw("}"); + } + else // Frontmost + { + body.raw(out + " = texelFetch(" + accumulate + ", ivec2(gl_FragCoord.xy), 0);"); + } + } + + builder.function() + .signature(FnSignature.create().returnType("void").name("main").build()) + .body(body); + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("oit_composite").toString(); + } + + public static void addOutputs(GlslBuilder builder, int targetCnt) + { + for (int i = 0; i < targetCnt; i++) + { + var out = new GlslFragmentOutput() + .binding(i) + .type("vec4") + .name("frag" + i); + + builder.add(out); + } + } + + public static void addAccumulateSamplers(GlslBuilder builder, int[] drawBuffers) + { + for (int drawBuffer : drawBuffers) + { + var uniform = new GlslUniform() + .type("sampler2D") + .name("_clrwl_accumulate" + drawBuffer); + + builder.add(uniform); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitEvaluateComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitEvaluateComponent.java new file mode 100644 index 000000000..15e8f07e8 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/OitEvaluateComponent.java @@ -0,0 +1,101 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.generate.FnSignature; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBlock; +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; +import dev.engine_room.flywheel.backend.glsl.generate.GlslStmt; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class OitEvaluateComponent implements SourceComponent +{ + private final int[] drawBuffers; + private final int[] ranks; + private final List overrides; + private final Map shaderOutputs; + + public OitEvaluateComponent(int[] drawBuffers, int[] ranks, List overrides, Map shaderOutputs) + { + this.drawBuffers = drawBuffers; + this.ranks = ranks; + this.overrides = overrides; + this.shaderOutputs = shaderOutputs; + } + + @Override + public Collection included() + { + return List.of(); + } + + @Override + public String source() + { + var builder = new GlslBuilder(); + var body = new GlslBlock(); + + body.add(GlslStmt.raw("float linearDepth = _clrwl_linear_depth();")); + body.add(GlslStmt.raw("vec2 depthRange = texelFetch(_flw_depthRange, ivec2(gl_FragCoord.xy), 0).rg;")); + body.add(GlslStmt.raw("float delta = depthRange.x + depthRange.y;")); + body.add(GlslStmt.raw("float flw_depth = (linearDepth + depthRange.x) / delta;")); + body.add(GlslStmt.raw("float depth_adjustment = _clrwl_tented_blue_noise(flw_depth) * _flw_oitNoise;")); + body.add(GlslStmt.raw("")); + + String transmittance_from_depth = "depth_transmittance"; + body.add(GlslStmt.raw("float " + transmittance_from_depth + " = _clrwl_frontmost_transmittance_from_depth(linearDepth, depthRange);")); + + for (int i = 0; i < drawBuffers.length; i++) + { + int drawBuffer = drawBuffers[i]; + String outName = shaderOutputs.get(i); + + var maybeCoeffId = Utils.findFirst(overrides, e -> e.drawBuffer() == drawBuffer) + .flatMap(ClrwlOitAccumulateOverride::coefficientId); + + if (maybeCoeffId.isPresent()) + { + int coeffId = maybeCoeffId.get(); + int rank = ranks[coeffId]; + + String transmittance = "transmittance" + drawBuffer; + String coeffs = "clrwl_coefficients" + coeffId; + String depth = "depth" + drawBuffer; + String correctedTransmittance = "correctedTransmittance" + drawBuffer; + + body.add(GlslStmt.raw("float " + transmittance + " = 1. - " + outName + ".a;")); + body.add(GlslStmt.raw("float " + depth + " = flw_depth;")); + // Don't do the depth adjustment if this fragment is opaque. + body.add(GlslStmt.raw("if (" + transmittance + " > 1e-5) { " + depth + " -= depth_adjustment; }")); + body.add(GlslStmt.raw("float " + correctedTransmittance + " = _clrwl_signal_corrected_transmittance(" + coeffs + ", " + depth + ", " + transmittance + ", " + rank + ");")); + body.add(GlslStmt.raw(outName + ".rgb *= " + outName + ".a;")); + body.add(GlslStmt.raw(outName + " *= " + correctedTransmittance + ";")); + } + else // Frontmost + { + body.add(GlslStmt.raw(outName + " *= " + transmittance_from_depth +";")); + } + } + + builder.function() + .signature(FnSignature.create() + .returnType("void") + .name(ClrwlPrograms.CLRWL_POST_FRAGMENT_FCT) + .build()) + .body(body); + + return builder.build(); + } + + @Override + public String name() + { + return Colorwheel.rl("oit_evaluate").toString(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/SsboInstanceComponent.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/SsboInstanceComponent.java new file mode 100644 index 000000000..d5450d663 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/component/SsboInstanceComponent.java @@ -0,0 +1,68 @@ +package net.irisshaders.iris.compat.flywheel.compile.component; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlBufferBindings; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.layout.Layout; +import dev.engine_room.flywheel.backend.compile.component.InstanceAssemblerComponent; +import dev.engine_room.flywheel.backend.glsl.generate.*; +import dev.engine_room.flywheel.lib.math.MoreMath; + +import java.util.ArrayList; + +// https://github.com/Engine-Room/Flywheel/blob/b9fbb6fb0cdda7e35b75bd3d0aff6e50004b6dbd/common/src/backend/java/dev/engine_room/flywheel/backend/compile/component/SsboInstanceComponent.java#L15 + +public class SsboInstanceComponent extends InstanceAssemblerComponent +{ + public SsboInstanceComponent(InstanceType type) { + super(type); + } + + @Override + public String name() + { + return Colorwheel.rl("ssbo_instance_assembler").toString(); + } + + @Override + protected void generateUnpacking(GlslBuilder builder) + { + var fnBody = new GlslBlock(); + + int uintCount = MoreMath.ceilingDiv(layout.byteSize(), 4); + + fnBody.add(GlslStmt.raw("uint base = " + UNPACK_ARG + " * " + uintCount + "u;")); + + for (int i = 0; i < uintCount; i++) + { + // Retrieve all the uints for the given instance ahead of time to simplify the unpacking generators. + fnBody.add(GlslStmt.raw("uint u" + i + " = _flw_instances[base + " + i + "u];")); + } + + var unpackArgs = new ArrayList(); + for (Layout.Element element : layout.elements()) + { + unpackArgs.add(unpackElement(element)); + } + + fnBody.ret(GlslExpr.call(STRUCT_NAME, unpackArgs)); + + builder._raw("layout(std430, binding = " + (ClrwlBufferBindings.base() + ClrwlBufferBindings.INSTANCE) + ") restrict readonly buffer InstanceBuffer {\n" + + " uint _flw_instances[];\n" + + "};"); + builder.blankLine(); + builder.function() + .signature(FnSignature.create() + .returnType(STRUCT_NAME) + .name(UNPACK_FN_NAME) + .arg("uint", UNPACK_ARG) + .build()) + .body(fnBody); + } + + @Override + protected GlslExpr access(int uintOffset) + { + return GlslExpr.variable("u" + uintOffset); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilation.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilation.java new file mode 100644 index 000000000..937e171e8 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilation.java @@ -0,0 +1,160 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlBufferBindings; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlGlShader; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import dev.engine_room.flywheel.backend.compile.FlwPrograms; +import dev.engine_room.flywheel.backend.compile.core.Compilation; +import dev.engine_room.flywheel.backend.compile.core.FailedCompilation; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.backend.glsl.SourceFile; +import dev.engine_room.flywheel.lib.util.StringUtil; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.helpers.StringPair; +import net.minecraft.client.Minecraft; +import org.lwjgl.opengl.GL20; + +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.List; + +/** + * Builder style class for compiling shaders. + *

+ * Keeps track of the source files and components used to compile a shader, + * and interprets/pretty prints any errors that occur. + */ +public class ClrwlCompilation +{ + private final List files = new ArrayList<>(); + private final StringBuilder generatedSource = new StringBuilder(); + private final StringBuilder fullSource = new StringBuilder(); + private int generatedLines = 0; + + public ClrwlShaderResult compile(ClrwlShaderType shaderType, String name) + { + int handle = GL20.glCreateShader(shaderType.glEnum); + var source = fullSource.toString(); + + GlCompat.safeShaderSource(handle, source); + GL20.glCompileShader(handle); + + var shaderName = name + "." + shaderType.extension; + dumpSource(source, shaderName); + + var infoLog = GL20.glGetShaderInfoLog(handle); + + if (compiledSuccessfully(handle)) + { + return ClrwlShaderResult.success(new ClrwlGlShader(handle, shaderType, shaderName), infoLog); + } + + GL20.glDeleteShader(handle); + return ClrwlShaderResult.failure(new FailedCompilation(shaderName, files, generatedSource.toString(), source, infoLog)); + } + + public void version(GlslVersion version) + { + fullSource.append("#version ") + .append(version.version) + .append('\n'); + define("_CLRWL_SSBO_BASE", Integer.toString(ClrwlBufferBindings.base())); + } + + public void enableExtension(String ext) + { + fullSource.append("#extension ") + .append(ext) + .append(" : enable\n"); + } + + public void requireExtension(String ext) + { + fullSource.append("#extension ") + .append(ext) + .append(" : require\n"); + } + + public void define(StringPair pair) + { + define(pair.key(), pair.value()); + } + + public void define(String key, String value) + { + fullSource.append("#define ") + .append(key) + .append(' ') + .append(value) + .append('\n'); + } + + public void define(String key) + { + fullSource.append("#define ") + .append(key) + .append('\n'); + } + + public void appendComponent(SourceComponent component) + { + var source = component.source(); + + appendHeader(component, source); + + fullSource.append(source); + } + + private void appendHeader(SourceComponent component, String source) + { + if (component instanceof SourceFile file) { + int fileId = files.size() + 1; + + files.add(file); + + fullSource.append("\n#line 0 ") + .append(fileId) + .append(" // ") + .append(file.name()) + .append('\n'); + } else { + // Add extra newline to keep line numbers consistent + generatedSource.append(source) + .append('\n'); + + fullSource.append("\n#line ") + .append(generatedLines) + .append(" 0 // (generated) ") // all generated code is put in file 0 + .append(component.name()) + .append('\n'); + + generatedLines += StringUtil.countLines(source); + } + } + + private static void dumpSource(String source, String fileName) + { + if (!(Compilation.DUMP_SHADER_SOURCE || Iris.getIrisConfig().areDebugOptionsEnabled())) + { + return; + } + + File file = new File(new File(Minecraft.getInstance().gameDirectory, "colorwheel_sources"), fileName); + // mkdirs of the parent so we don't create a directory named by the leaf file we want to write + file.getParentFile() + .mkdirs(); + try (FileWriter writer = new FileWriter(file)) { + writer.write(source); + } catch (Exception e) { + FlwPrograms.LOGGER.error("Could not dump source.", e); + } + } + + public static boolean compiledSuccessfully(int handle) + { + return GL20.glGetShaderi(handle, GL20.GL_COMPILE_STATUS) == GL20.GL_TRUE; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilationHarness.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilationHarness.java new file mode 100644 index 000000000..3a70606c4 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompilationHarness.java @@ -0,0 +1,51 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import dev.engine_room.flywheel.backend.gl.GlObject; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public class ClrwlCompilationHarness +{ + private final ClrwlShaderSources sources; + private final KeyCompiler compiler; + private final ClrwlShaderCache shaderCache; + private final ClrwlProgramLinker programLinker; + + private final Map programs = new HashMap<>(); + + public ClrwlCompilationHarness(String marker, ClrwlShaderSources sources, KeyCompiler compiler, BiFunction programInit) + { + this.sources = sources; + this.compiler = compiler; + shaderCache = new ClrwlShaderCache(); + programLinker = new ClrwlProgramLinker<>(programInit); + } + + public P get(K key) + { + return programs.computeIfAbsent(key, this::compile); + } + + private P compile(K key) + { + return compiler.compile(key, sources, shaderCache, programLinker); + } + + public void delete() + { + shaderCache.delete(); + + programs.values() + .forEach(GlObject::delete); + + programs.clear(); + } + + public interface KeyCompiler + { + P compile(K key, ClrwlShaderSources sources, ClrwlShaderCache shaderCache, ClrwlProgramLinker programLinker); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompile.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompile.java new file mode 100644 index 000000000..5d615152c --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlCompile.java @@ -0,0 +1,237 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlGlShader; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; +import dev.engine_room.flywheel.lib.util.StringUtil; +import net.minecraft.resources.ResourceLocation; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * A typed provider for shader compiler builders. + *
+ * This could just be a static utility class, but creating an instance of Compile + * and calling the functors on it prevents you from having to specify the key type everywhere. + *
+ * Consider {@code Compile.shader(...)} vs {@code PIPELINE.shader(...)} + * + * @param The type of the key used to compile shaders. + */ +public class ClrwlCompile +{ + public ShaderCompiler shader(GlslVersion glslVersion, ClrwlShaderType shaderType) + { + return new ShaderCompiler<>(glslVersion, shaderType); + } + + public ProgramStitcher program() + { + return new ProgramStitcher<>(); + } + + public static class ShaderCompiler + { + private final GlslVersion glslVersion; + private final ClrwlShaderType shaderType; + private final List> fetchers = new ArrayList<>(); + private BiConsumer compilationCallbacks = ($, $$) -> { + }; + private Function nameMapper = Object::toString; + private BiFunction condition = ($, $$) -> true; + + public ShaderCompiler(GlslVersion glslVersion, ClrwlShaderType shaderType) + { + this.glslVersion = glslVersion; + this.shaderType = shaderType; + } + + public ShaderCompiler nameMapper(Function nameMapper) + { + this.nameMapper = nameMapper; + return this; + } + + public ShaderCompiler condition(BiFunction condition) + { + this.condition = condition; + return this; + } + + public ShaderCompiler with(BiFunction fetch) + { + fetchers.add(fetch); + return this; + } + + public ShaderCompiler withComponents(Collection components) + { + components.forEach(this::withComponent); + return this; + } + + public ShaderCompiler withComponent(SourceComponent component) + { + return withComponent($ -> component); + } + + public ShaderCompiler withComponent(Function sourceFetcher) + { + return with((key, $) -> sourceFetcher.apply(key)); + } + + public ShaderCompiler withResource(Function sourceFetcher) + { + return with((key, c) -> c.flwSources().get(sourceFetcher.apply(key))); + } + + public ShaderCompiler withResource(ResourceLocation resourceLocation) + { + return withResource($ -> resourceLocation); + } + + public ShaderCompiler onCompile(BiConsumer cb) + { + compilationCallbacks = compilationCallbacks.andThen(cb); + return this; + } + + public ShaderCompiler define(String def, int value) + { + return onCompile(($, ctx) -> ctx.define(def, String.valueOf(value))); + } + + public ShaderCompiler enableExtension(String extension) + { + return onCompile(($, ctx) -> ctx.enableExtension(extension)); + } + + public ShaderCompiler enableExtensions(String... extensions) + { + return onCompile(($, ctx) -> { + for (String extension : extensions) + { + ctx.enableExtension(extension); + } + }); + } + + public ShaderCompiler enableExtensions(Collection extensions) + { + return onCompile(($, ctx) -> { + for (String extension : extensions) + { + ctx.enableExtension(extension); + } + }); + } + + public ShaderCompiler requireExtensions(Collection extensions) + { + return onCompile(($, ctx) -> { + for (String extension : extensions) + { + ctx.requireExtension(extension); + } + }); + } + + private boolean shouldCompile(K key, ClrwlShaderSources sources) + { + return condition.apply(key, sources); + } + + private ClrwlGlShader compile(K key, ClrwlShaderCache compiler, ClrwlShaderSources sources) + { + long start = System.nanoTime(); + + var components = new ArrayList(); + for (var fetcher : fetchers) + { + components.add(fetcher.apply(key, sources)); + } + + Consumer cb = ctx -> compilationCallbacks.accept(key, ctx); + var name = nameMapper.apply(key); + var out = compiler.compile(glslVersion, shaderType, name, cb, components); + + long end = System.nanoTime(); + + Colorwheel.LOGGER.debug("Compiled {} in {}", name, StringUtil.formatTime(end - start)); + + return out; + } + } + + public static class ProgramStitcher implements ClrwlCompilationHarness.KeyCompiler + { + private final Map> compilers = new EnumMap<>(ClrwlShaderType.class); + private BiConsumer postLink = (k, p) -> {}; + private BiConsumer preLink = (k, p) -> {}; + + public ClrwlCompilationHarness harness(String marker, ClrwlShaderSources sources, BiFunction programInit) + { + return new ClrwlCompilationHarness(marker, sources, this, programInit); + } + + public ProgramStitcher link(ShaderCompiler compilerBuilder) + { + if (compilers.containsKey(compilerBuilder.shaderType)) + { + throw new IllegalArgumentException("Duplicate shader type: " + compilerBuilder.shaderType); + } + compilers.put(compilerBuilder.shaderType, compilerBuilder); + return this; + } + + public ProgramStitcher postLink(BiConsumer postLink) + { + this.postLink = postLink; + return this; + } + + public ProgramStitcher preLink(BiConsumer preLink) + { + this.preLink = preLink; + return this; + } + + @Override + public P compile(K key, ClrwlShaderSources sources, ClrwlShaderCache shaderCache, ClrwlProgramLinker programLinker) + { + if (compilers.isEmpty()) + { + throw new IllegalStateException("No shader compilers were added!"); + } + + long start = System.nanoTime(); + + List shaders = new ArrayList<>(); + + for (ShaderCompiler compiler : compilers.values()) + { + if (compiler.shouldCompile(key, sources)) + { + shaders.add(compiler.compile(key, shaderCache, sources)); + } + } + + var out = programLinker.link(key, shaders, p -> preLink.accept(key, p)); + + postLink.accept(key, out); + + long end = System.nanoTime(); + + Colorwheel.LOGGER.debug("Linked {} in {}", key, StringUtil.formatTime(end - start)); + + return out; + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlLinkResult.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlLinkResult.java new file mode 100644 index 000000000..1c94896b3 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlLinkResult.java @@ -0,0 +1,37 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import dev.engine_room.flywheel.backend.compile.core.ShaderException; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import org.jetbrains.annotations.NotNull; + +public sealed interface ClrwlLinkResult

+{ + P unwrap(); + + record Success

(P program, String log) implements ClrwlLinkResult

+ { + @Override + @NotNull + public P unwrap() { + return program; + } + } + + record Failure

(String failure) implements ClrwlLinkResult

+ { + @Override + public P unwrap() { + throw new ShaderException.Link(failure); + } + } + + static

ClrwlLinkResult

success(P program, String log) + { + return new Success<>(program, log); + } + + static

ClrwlLinkResult

failure(String failure) + { + return new Failure<>(failure); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlProgramLinker.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlProgramLinker.java new file mode 100644 index 000000000..72b556be5 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlProgramLinker.java @@ -0,0 +1,58 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import net.irisshaders.iris.compat.flywheel.gl.ClrwlGlShader; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Consumer; + +import static org.lwjgl.opengl.GL11.GL_TRUE; +import static org.lwjgl.opengl.GL20.*; + +public class ClrwlProgramLinker +{ + private final BiFunction programInit; + + public ClrwlProgramLinker(BiFunction programInit) + { + this.programInit = programInit; + } + + public P link(K key, List shaders, Consumer

preLink) + { + // this probably doesn't need caching + return linkInternal(key, shaders, preLink).unwrap(); + } + + private ClrwlLinkResult

linkInternal(K key, List shaders, Consumer

preLink) + { + int handle = glCreateProgram(); + var out = programInit.apply(key, handle); + + for (ClrwlGlShader shader : shaders) + { + glAttachShader(handle, shader.handle()); + } + + preLink.accept(out); + + glLinkProgram(handle); + String log = glGetProgramInfoLog(handle); + + if (linkSuccessful(handle)) + { + return ClrwlLinkResult.success(out, log); + } + else + { + out.delete(); + return ClrwlLinkResult.failure(log); + } + } + + private static boolean linkSuccessful(int handle) + { + return glGetProgrami(handle, GL_LINK_STATUS) == GL_TRUE; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderCache.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderCache.java new file mode 100644 index 000000000..dede4849a --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderCache.java @@ -0,0 +1,72 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + + +import net.irisshaders.iris.compat.flywheel.gl.ClrwlGlShader; +import net.irisshaders.iris.compat.flywheel.gl.ClrwlShaderType; +import dev.engine_room.flywheel.backend.glsl.GlslVersion; +import dev.engine_room.flywheel.backend.glsl.SourceComponent; + +import java.util.*; +import java.util.function.Consumer; + +public class ClrwlShaderCache +{ + private final Map inner = new HashMap<>(); + + public ClrwlShaderCache() + { + } + + public ClrwlGlShader compile(GlslVersion glslVersion, ClrwlShaderType shaderType, String name, Consumer callback, List sourceComponents) + { + var key = new ShaderKey(glslVersion, shaderType, name); + var cached = inner.get(key); + if (cached != null) { + return cached.unwrap(); + } + + ClrwlCompilation ctx = new ClrwlCompilation(); + ctx.version(glslVersion); + + callback.accept(ctx); + + expand(sourceComponents, ctx::appendComponent); + + ClrwlShaderResult out = ctx.compile(shaderType, name); + inner.put(key, out); + return out.unwrap(); + } + + public void delete() + { + inner.values() + .stream() + .filter(r -> r instanceof ClrwlShaderResult.Success) + .map(ClrwlShaderResult::unwrap) + .forEach(ClrwlGlShader::delete); + inner.clear(); + } + + private static void expand(List rootSources, Consumer out) + { + var included = new LinkedHashSet(); // use hash set to deduplicate. linked to preserve order + for (var component : rootSources) + { + recursiveDepthFirstInclude(included, component); + included.add(component); + } + included.forEach(out); + } + + private static void recursiveDepthFirstInclude(Set included, SourceComponent component) + { + for (var include : component.included()) + { + recursiveDepthFirstInclude(included, include); + } + included.addAll(component.included()); + } + + private record ShaderKey(GlslVersion glslVersion, ClrwlShaderType shaderType, String name) { + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderResult.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderResult.java new file mode 100644 index 000000000..9315e2da1 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderResult.java @@ -0,0 +1,34 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import net.irisshaders.iris.compat.flywheel.gl.ClrwlGlShader; +import dev.engine_room.flywheel.backend.compile.core.FailedCompilation; +import dev.engine_room.flywheel.backend.compile.core.ShaderException; + +public sealed interface ClrwlShaderResult +{ + ClrwlGlShader unwrap(); + + record Success(ClrwlGlShader shader, String infoLog) implements ClrwlShaderResult + { + @Override + public ClrwlGlShader unwrap() { + return shader; + } + } + + record Failure(FailedCompilation failure) implements ClrwlShaderResult + { + @Override + public ClrwlGlShader unwrap() { + throw new ShaderException.Compile(failure.generateMessage()); + } + } + + static ClrwlShaderResult success(ClrwlGlShader program, String infoLog) { + return new Success(program, infoLog); + } + + static ClrwlShaderResult failure(FailedCompilation failure) { + return new Failure(failure); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderSources.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderSources.java new file mode 100644 index 000000000..1af8e6325 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/core/ClrwlShaderSources.java @@ -0,0 +1,42 @@ +package net.irisshaders.iris.compat.flywheel.compile.core; + +import net.irisshaders.iris.compat.flywheel.compile.ClrwlProgramSources; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; + +public class ClrwlShaderSources +{ + private final ShaderSources flwSources; + private final ProgramSet programSet; + private final ClrwlProgramSources clrwlSources; + private final IrisRenderingPipeline irisPipeline; + + public ClrwlShaderSources(ShaderSources flwSources, ProgramSet programSet, IrisRenderingPipeline irisPipeline) + { + this.flwSources = flwSources; + this.programSet = programSet; + this.irisPipeline = irisPipeline; + this.clrwlSources = new ClrwlProgramSources(irisPipeline, programSet); + } + + public ShaderSources flwSources() + { + return flwSources; + } + + public ProgramSet programSet() + { + return programSet; + } + + public IrisRenderingPipeline irisPipeline() + { + return irisPipeline; + } + + public ClrwlProgramSources clrwlSources() + { + return clrwlSources; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslAssignment.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslAssignment.java new file mode 100644 index 000000000..bea856e37 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslAssignment.java @@ -0,0 +1,28 @@ +package net.irisshaders.iris.compat.flywheel.compile.glsl; + +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; + +public class GlslAssignment implements GlslBuilder.Declaration +{ + private String type; + private String name; + + public GlslAssignment() {} + + public GlslAssignment type(String type) + { + this.type = type; + return this; + } + + public GlslAssignment name(String name) + { + this.name = name; + return this; + } + + public String prettyPrint() + { + return this.type + " " + this.name + ";"; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslFragmentOutput.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslFragmentOutput.java new file mode 100644 index 000000000..fad48af34 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/glsl/GlslFragmentOutput.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.compat.flywheel.compile.glsl; + +import dev.engine_room.flywheel.backend.glsl.generate.GlslBuilder; + +public class GlslFragmentOutput implements GlslBuilder.Declaration +{ + private int binding; + private String type; + private String name; + + public GlslFragmentOutput() {} + + public GlslFragmentOutput binding(int binding) + { + this.binding = binding; + return this; + } + + public GlslFragmentOutput type(String type) + { + this.type = type; + return this; + } + + public GlslFragmentOutput name(String name) + { + this.name = name; + return this; + } + + public String prettyPrint() + { + return "layout(location = " + this.binding + ") out " + this.type + " " + this.name + ";"; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlComputeTransformPatcher.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlComputeTransformPatcher.java new file mode 100644 index 000000000..0686b31fe --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlComputeTransformPatcher.java @@ -0,0 +1,22 @@ +package net.irisshaders.iris.compat.flywheel.compile.transform; + +import dev.engine_room.flywheel.backend.gl.GlCompat; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; + +public class ClrwlComputeTransformPatcher +{ + public static String patchCompute(String shader, Object2ObjectMap, String> textureMap) + { + var parameters = new ClrwlTransformParameters(ShaderType.COMPUTE, false, false, textureMap); + var t = ClrwlTransformPatcher.parse(shader, GlCompat.MAX_GLSL_VERSION.version); + + ClrwlTransformPatcher.replaceMatrices(t); + ClrwlTransformPatcher.finish(t, parameters); + + return ClrwlTransformPatcher.print(t); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformOutput.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformOutput.java new file mode 100644 index 000000000..8cfc269a9 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformOutput.java @@ -0,0 +1,12 @@ +package net.irisshaders.iris.compat.flywheel.compile.transform; + +import java.util.Collections; +import java.util.Map; + +public record ClrwlTransformOutput(String code, Map outputs) +{ + public static ClrwlTransformOutput unprocessed(String code) + { + return new ClrwlTransformOutput(code, Collections.emptyMap()); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformParameters.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformParameters.java new file mode 100644 index 000000000..1c96a70c2 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformParameters.java @@ -0,0 +1,37 @@ +package net.irisshaders.iris.compat.flywheel.compile.transform; + +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; + +// Extends Parameters so that ShaderTransformer.commonPatch can be applied; the patch type is only a placeholder. +public class ClrwlTransformParameters extends Parameters +{ + private final boolean isCrumbling; + private final boolean customOutputs; + + public ClrwlTransformParameters(ShaderType type, boolean isCrumbling, boolean customOutputs, Object2ObjectMap, String> textureMap) + { + super(Patch.VANILLA, textureMap); + super.type = type; + this.isCrumbling = isCrumbling; + this.customOutputs = customOutputs; + } + + public boolean usesCustomOutputs() + { + return customOutputs; + } + + public boolean isCrumbling() + { + return isCrumbling; + } + + @Override + public TextureStage getTextureStage() { return TextureStage.GBUFFERS_AND_SHADOW; } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformPatcher.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformPatcher.java new file mode 100644 index 000000000..8134c4849 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/compile/transform/ClrwlTransformPatcher.java @@ -0,0 +1,307 @@ +package net.irisshaders.iris.compat.flywheel.compile.transform; + +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.ShaderPrinter; +import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClrwlTransformPatcher +{ + public static final Pattern versionPattern = Pattern.compile("^.*#version\\h+(\\d+)\\V*", Pattern.DOTALL); + public static final Pattern extensionPattern = Pattern.compile("^.*#extension\\s+([a-zA-Z0-9_]+)\\s+:\\s+([a-zA-Z0-9_]+)", Pattern.DOTALL); + + private static final Pattern layoutLocationPattern = Pattern.compile("location=(\\d+)"); + private static final Pattern outColorPattern = Pattern.compile("outColor(\\d+)"); + + private static final String LIGHTMAP_SCALE = "1.0 / 240.0"; + private static final String LIGHTMAP_OFFSET = "0.03125"; + private static final String LIGHTMAP_MATRIX = String.format("mat4(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", + LIGHTMAP_SCALE, "0.0", "0.0", "0.0", + "0.0", LIGHTMAP_SCALE, "0.0", "0.0", + "0.0", "0.0", "1.0", "0.0", + LIGHTMAP_OFFSET, LIGHTMAP_OFFSET, "0.0", "1.0" + ); + + /** + * Parses a pack shader with its {@code #version} and {@code #extension} directives removed; Flywheel's + * compilation supplies its own. + */ + static Transformer parse(String input, int version) + { + input = versionPattern.matcher(input).replaceAll(""); + input = extensionPattern.matcher(input).replaceAll(""); + input = ShaderTransformer.renameReservedWords(input, version); + + return new Transformer(ShaderParser.parseShader(input).full()); + } + + static String print(Transformer transformer) + { + StringBuilder out = new StringBuilder(); + transformer.mutateTree(tree -> out.append(ShaderPrinter.getFormattedShader(tree))); + return out.toString(); + } + + static void replaceMatrices(Transformer t) + { + t.replaceExpression("gl_ModelViewMatrix", "flw_view"); + t.replaceExpression("modelViewMatrix", "flw_view"); + t.replaceExpression("gl_ModelViewMatrixInverse", "flw_viewInverse"); + t.replaceExpression("modelViewMatrixInverse", "flw_viewInverse"); + + t.replaceExpression("gl_ProjectionMatrix", "flw_projection"); + t.replaceExpression("projectionMatrix", "flw_projection"); + t.replaceExpression("gl_ProjectionMatrixInverse", "flw_projectionInverse"); + t.replaceExpression("projectionMatrixInverse", "flw_projectionInverse"); + + t.replaceExpression("gl_ModelViewProjectionMatrix", "flw_viewProjection"); + t.replaceExpression("modelViewProjectionMatrix", "flw_viewProjection"); + t.replaceExpression("gl_ModelViewProjectionMatrixInverse", "flw_viewProjectionInverse"); + t.replaceExpression("modelViewProjectionMatrixInverse", "flw_viewProjectionInverse"); + + t.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0)"); + t.replaceExpression("textureMatrix", "mat4(1.0)"); + t.replaceExpression("gl_TextureMatrix[1]", LIGHTMAP_MATRIX); + t.replaceExpression("gl_TextureMatrix[2]", LIGHTMAP_MATRIX); + + t.replaceExpression("gl_NormalMatrix", "clrwl_normal"); + t.replaceExpression("normalMatrix", "clrwl_normal"); + + t.replaceExpression("clrwl_view", "flw_view"); + t.replaceExpression("clrwl_viewInverse", "flw_viewInverse"); + t.replaceExpression("clrwl_viewPrev", "flw_viewPrev"); + t.replaceExpression("clrwl_projection", "flw_projection"); + t.replaceExpression("clrwl_projectionInverse", "flw_projectionInverse"); + t.replaceExpression("clrwl_projectionPrev", "flw_projectionPrev"); + t.replaceExpression("clrwl_viewProjection", "flw_viewProjection"); + t.replaceExpression("clrwl_viewProjectionInverse", "flw_viewProjectionInverse"); + t.replaceExpression("clrwl_viewProjectionPrev", "flw_viewProjectionPrev"); + t.replaceExpression("clrwl_renderOrigin", "flw_renderOrigin"); + t.replaceExpression("clrwl_cameraPos", "flw_cameraPos"); + } + + static void finish(Transformer t, ClrwlTransformParameters parameters) + { + ShaderTransformer.commonPatch(t, parameters, false); + + String diffuse = parameters.isCrumbling() ? "_flw_crumblingTex" : "flw_diffuseTex"; + t.replaceExpression("tex", diffuse); + t.replaceExpression("gtexture", diffuse); + t.replaceExpression("iris_renamed_texture", diffuse); + + t.rename("main", "_clrwl_shader_main"); + } + + private static ClrwlTransformOutput transform(String source, ClrwlTransformParameters parameters) + { + Matcher versionMatcher = versionPattern.matcher(source); + + if (!versionMatcher.find()) + { + throw new IllegalArgumentException("No #version directive found in source code!"); + } + + Transformer t = parse(source, Integer.parseInt(versionMatcher.group(1))); + Map outputs = new HashMap<>(); + + t.replaceExpression("gl_Vertex", "flw_vertexPos"); + t.replaceExpression("gl_Normal", "flw_vertexNormal"); + t.replaceExpression("gl_Color", "flw_vertexColor"); + replaceVec4WithVariableDimension(t, "at_midBlock", "clrwl_vertexMidMesh"); + replaceVec4WithVariableDimension(t, "at_tangent", "clrwl_vertexTangent"); + replaceVec2WithVariableDimension(t, "mc_midTexCoord", "clrwl_vertexMidTexCoord"); + replaceVec2WithVariableDimension(t, "mc_Entity", "clrwl_vertexEntity"); + + t.replaceExpression("gl_MultiTexCoord0", "vec4(flw_vertexTexCoord, 0.0, 1.0)"); + t.replaceExpression("gl_MultiTexCoord1", "vec4(flw_vertexLight * 240.0, 0.0, 1.0)"); + t.replaceExpression("gl_MultiTexCoord2", "vec4(flw_vertexLight * 240.0, 0.0, 1.0)"); + + t.rename("renderStage", "_clrwl_renderPhase"); + t.rename("blendFunc", "_clrwl_blendFunc"); + t.rename("atlasSize", "_clrwl_atlasSize"); + t.replaceExpression("blockEntityId", "_clrwl_blockEntityId"); + t.replaceExpression("entityId", "_clrwl_entityId"); + t.replaceExpression("entityColor", "clrwl_overlayColor"); + + replaceMatrices(t); + + t.rename("clrwl_vertexPos", "flw_vertexPos"); + t.rename("clrwl_vertexColor", "flw_vertexColor"); + t.rename("clrwl_vertexTexCoord", "flw_vertexTexCoord"); + t.rename("clrwl_vertexOverlay", "flw_vertexOverlay"); + t.rename("clrwl_vertexLight", "flw_vertexLight"); + t.rename("clrwl_vertexNormal", "flw_vertexNormal"); + t.rename("clrwl_distance", "flw_distance"); + + t.replaceExpression("clrwl_materialFragment", "_clrwl_materialFragment_hook"); + t.replaceExpression("clrwl_shaderLight", "_clrwl_shaderLight_hook"); + + if (parameters.type == ShaderType.FRAGMENT) + { + patchFragmentOutputs(t, parameters.usesCustomOutputs(), outputs); + } + + finish(t, parameters); + + return new ClrwlTransformOutput(print(t), outputs); + } + + /** + * Collects the pack's fragment outputs by location. With custom outputs, Colorwheel writes the attachments + * itself, so the pack's outputs become plain globals. + */ + private static void patchFragmentOutputs(Transformer t, boolean customOutputs, Map outputs) + { + if (t.containsCall("gl_FragColor")) + { + t.replaceExpression("gl_FragColor", "gl_FragData[0]", GLSLParser::unary_expression); + } + + Map declaredOutputs = new HashMap<>(); + + for (var entry : t.findQualifiers(GLSLLexer.OUT).entrySet()) + { + var declaration = entry.getValue(); + + if (!declaration.fully_specified_type().type_specifier().getText().equals("vec4")) + { + continue; + } + + Matcher location = layoutLocationPattern.matcher(declaration.getText()); + Matcher outColor = outColorPattern.matcher(entry.getKey()); + + if (location.find()) + { + declaredOutputs.put(entry.getKey(), Integer.parseInt(location.group(1))); + } + else if (outColor.matches()) + { + declaredOutputs.put(entry.getKey(), Integer.parseInt(outColor.group(1))); + } + } + + String fragDataPrefix = customOutputs ? "clrwl_FragData" : "iris_FragData"; + Set fragDataIndexes = new HashSet<>(); + t.renameArray("gl_FragData", fragDataPrefix, fragDataIndexes); + + for (int index : fragDataIndexes) + { + outputs.putIfAbsent(index, fragDataPrefix + index); + + if (customOutputs) + { + t.injectVariable("vec4 " + fragDataPrefix + index + ";"); + } + else + { + t.injectFunction("layout (location = " + index + ") out vec4 " + fragDataPrefix + index + ";"); + } + } + + declaredOutputs.forEach((name, index) -> + { + outputs.putIfAbsent(index, name); + + if (customOutputs) + { + t.removeVariable(name); + t.injectVariable("vec4 " + name + ";"); + } + }); + } + + private static int getAttributeDimensionAndDelete(Transformer t, String name, int defaultDimension) + { + int type = t.findType(name); + + if (type == 0) + { + return defaultDimension; + } + + t.removeVariable(name); + + return switch (type) + { + case GLSLLexer.FLOAT -> 1; + case GLSLLexer.VEC2 -> 2; + case GLSLLexer.VEC3 -> 3; + case GLSLLexer.VEC4 -> 4; + default -> defaultDimension; + }; + } + + private static void replaceVec2WithVariableDimension(Transformer t, String name, String vec2) + { + int dimension = getAttributeDimensionAndDelete(t, name, 2); + + if (dimension == 1) + { + t.replaceExpression(name, vec2 + ".x"); + } + else if (dimension == 2) + { + t.replaceExpression(name, vec2); + } + else if (dimension == 3) + { + t.replaceExpression(name, "vec3(" + vec2 + ", 0.0)"); + } + else + { + t.replaceExpression(name, "vec4(" + vec2 + ", 0.0, 1.0)"); + } + } + + private static void replaceVec4WithVariableDimension(Transformer t, String name, String vec4) + { + int dimension = getAttributeDimensionAndDelete(t, name, 4); + + if (dimension == 1) + { + t.replaceExpression(name, vec4 + ".x"); + } + else if (dimension == 2) + { + t.replaceExpression(name, vec4 + ".xy"); + } + else if (dimension == 3) + { + t.replaceExpression(name, vec4 + ".xyz"); + } + else + { + t.replaceExpression(name, vec4); + } + } + + public static String patchVertex(String vertex, boolean isCrumbling, Object2ObjectMap, String> textureMap) + { + return transform(vertex, new ClrwlTransformParameters(ShaderType.VERTEX, isCrumbling, false, textureMap)).code(); + } + + public static String patchGeometry(String geometry, boolean isCrumbling, Object2ObjectMap, String> textureMap) + { + return transform(geometry, new ClrwlTransformParameters(ShaderType.GEOM, isCrumbling, false, textureMap)).code(); + } + + public static ClrwlTransformOutput patchFragment(String fragment, boolean isCrumbling, boolean customOutputs, Object2ObjectMap, String> textureMap) + { + return transform(fragment, new ClrwlTransformParameters(ShaderType.FRAGMENT, isCrumbling, customOutputs, textureMap)); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlAbstractInstancer.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlAbstractInstancer.java new file mode 100644 index 000000000..ac3dc5a9a --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlAbstractInstancer.java @@ -0,0 +1,45 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.instance.Instancer; +import dev.engine_room.flywheel.backend.engine.embed.Environment; + +public abstract class ClrwlAbstractInstancer implements Instancer +{ + public final ClrwlInstanceVisual visual; + public final InstanceType type; + public final Environment environment; + public final Recreate recreate; + + protected ClrwlAbstractInstancer(ClrwlInstancerKey key, Recreate recreate) + { + this.visual = key.visual(); + this.type = key.type(); + this.environment = key.environment(); + this.recreate = recreate; + } + + public abstract ClrwlInstanceHandle.State revealInstance(ClrwlInstanceHandle handle, I instance); + + public abstract int instanceCount(); + + public abstract void parallelUpdate(); + + public abstract void delete(); + + public abstract void clear(); + + @Override + public String toString() { + return "ClrwlAbstractInstancer[" + instanceCount() + ']'; + } + + public record Recreate(ClrwlInstancerKey key, ClrwlDrawManager drawManager) + { + public ClrwlAbstractInstancer recreate() + { + return drawManager.getInstancer(key); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBaseInstancer.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBaseInstancer.java new file mode 100644 index 000000000..18989a99b --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBaseInstancer.java @@ -0,0 +1,176 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.backend.util.AtomicBitSet; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; + +public abstract class ClrwlBaseInstancer extends ClrwlAbstractInstancer implements ClrwlInstanceHandle.State +{ + // Lock for all instances, only needs to be used in methods that may run on the TaskExecutor. + protected final Object lock = new Object(); + protected final ArrayList instances = new ArrayList<>(); + protected final ArrayList> handles = new ArrayList<>(); + + protected final AtomicBitSet changed = new AtomicBitSet(); + protected final AtomicBitSet deleted = new AtomicBitSet(); + + protected ClrwlBaseInstancer(ClrwlInstancerKey key, Recreate recreate) { + super(key, recreate); + } + + + @Override + public ClrwlInstanceHandle.State setChanged(int index) { + notifyDirty(index); + return this; + } + + @Override + public ClrwlInstanceHandle.State setDeleted(int index) { + notifyRemoval(index); + return ClrwlInstanceHandle.Deleted.instance(); + } + + @Override + public ClrwlInstanceHandle.State setVisible(ClrwlInstanceHandle handle, int index, boolean visible) { + if (visible) { + return this; + } + + notifyRemoval(index); + + I instance; + synchronized (lock) { + // I think we need to lock to prevent wacky stuff from happening if the array gets resized. + instance = instances.get(index); + } + + return new ClrwlInstanceHandle.Hidden<>(recreate, instance); + } + + @Override + public I createInstance() { + var handle = new ClrwlInstanceHandle<>(this); + I instance = type.create(handle); + + synchronized (lock) { + handle.index = instances.size(); + addLocked(instance, handle); + return instance; + } + } + + public ClrwlInstanceHandle.State revealInstance(ClrwlInstanceHandle handle, I instance) + { + synchronized (lock) { + handle.index = instances.size(); + addLocked(instance, handle); + } + return this; + } + + @Override + public void stealInstance(@Nullable I instance) { + if (instance == null) { + return; + } + + var instanceHandle = instance.handle(); + + if (!(instanceHandle instanceof ClrwlInstanceHandle)) { + // UB: do nothing + return; + } + + // Should InstanceType have an isInstance method? + @SuppressWarnings("unchecked") var handle = (ClrwlInstanceHandle) instanceHandle; + + // No need to steal if this instance is already owned by this instancer. + if (handle.state == this) { + return; + } + // Not allowed to steal deleted instances. + if (handle.state instanceof ClrwlInstanceHandle.Deleted) { + return; + } + // No need to steal if the instance will recreate to us. + if (handle.state instanceof ClrwlInstanceHandle.Hidden hidden && recreate.equals(hidden.recreate())) { + return; + } + + // FIXME: in theory there could be a race condition here if the instance + // is somehow being stolen by 2 different instancers between threads. + // That seems kinda impossible so I'm fine leaving it as is for now. + + // Add the instance to this instancer. + if (handle.state instanceof ClrwlBaseInstancer other) { + // Remove the instance from its old instancer. + // This won't have any unwanted effect when the old instancer + // is filtering deleted instances later, so is safe. + other.notifyRemoval(handle.index); + + handle.state = this; + // Only lock now that we'll be mutating our state. + synchronized (lock) { + handle.index = instances.size(); + addLocked(instance, handle); + } + } else if (handle.state instanceof ClrwlInstanceHandle.Hidden) { + handle.state = new ClrwlInstanceHandle.Hidden<>(recreate, instance); + } + } + + /** + * Calls must be synchronized on {@link #lock}. + */ + private void addLocked(I instance, ClrwlInstanceHandle handle) { + instances.add(instance); + handles.add(handle); + setIndexChanged(handle.index); + } + + public int instanceCount() { + return instances.size(); + } + + public void notifyDirty(int index) { + if (index < 0 || index >= instanceCount()) { + return; + } + setIndexChanged(index); + } + + protected void setIndexChanged(int index) { + changed.set(index); + } + + public void notifyRemoval(int index) { + if (index < 0 || index >= instanceCount()) { + return; + } + deleted.set(index); + } + + /** + * Clear all instances without freeing resources. + */ + public void clear() { + for (ClrwlInstanceHandle handle : handles) { + // Only clear instances that belong to this instancer. + // If one of these handles was stolen by another instancer, + // clearing it here would cause significant visual artifacts and instance leaks. + // At the same time, we need to clear handles we own to prevent + // instances from changing/deleting positions in this instancer that no longer exist. + if (handle.state == this) { + handle.clear(); + handle.state = ClrwlInstanceHandle.Deleted.instance(); + } + } + instances.clear(); + handles.clear(); + changed.clear(); + deleted.clear(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBlendModeOverride.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBlendModeOverride.java new file mode 100644 index 000000000..b80bf48ca --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlBlendModeOverride.java @@ -0,0 +1,9 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import net.irisshaders.iris.gl.blending.BlendMode; +import org.jetbrains.annotations.Nullable; + +public record ClrwlBlendModeOverride(@Nullable BlendMode blendMode) +{ + public static final ClrwlBlendModeOverride OFF = new ClrwlBlendModeOverride(null); +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlDrawManager.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlDrawManager.java new file mode 100644 index 000000000..d4a3d9286 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlDrawManager.java @@ -0,0 +1,213 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import com.mojang.datafixers.util.Pair; +import net.irisshaders.iris.compat.flywheel.engine.embed.EnvironmentStorage; +import dev.engine_room.flywheel.api.backend.Engine; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.api.task.Plan; +import dev.engine_room.flywheel.backend.FlwBackend; +import dev.engine_room.flywheel.backend.engine.GroupKey; +import dev.engine_room.flywheel.backend.engine.LightStorage; +import dev.engine_room.flywheel.backend.engine.embed.Environment; +import dev.engine_room.flywheel.lib.task.ForEachPlan; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import net.irisshaders.iris.Iris; +import org.embeddedt.embeddium.impl.gl.debug.GLDebug; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.minecraft.client.resources.model.ModelBakery; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Function; + +public abstract class ClrwlDrawManager> +{ + private static final boolean WARN_EMPTY_MODELS = Boolean.getBoolean("flywheel.warnEmptyModels"); + + /** + * A map of instancer keys to instancers. + *
+ * This map is populated as instancers are requested and contains both initialized and uninitialized instancers. + */ + protected final Map, N> instancers = new ConcurrentHashMap<>(); + /** + * A list of instancers that have not yet been initialized. + *
+ * All new instancers land here before having resources allocated in {@link #prepareFrame}. + */ + protected final Queue> initializationQueue = new ConcurrentLinkedQueue<>(); + + /** + * Function object to pass into computeIfAbsent. + *

Create once and cache to avoid allocating every time. + */ + protected final Function, N> createAndDeferInit = this::createAndDeferInit; + + public ClrwlAbstractInstancer getInstancer(ClrwlInstanceVisual visual, Environment environment, InstanceType type, Model model, int bias) + { + return getInstancer(new ClrwlInstancerKey<>(visual, environment, type, model, bias)); + } + + @SuppressWarnings("unchecked") + public ClrwlAbstractInstancer getInstancer(ClrwlInstancerKey key) + { + return (ClrwlAbstractInstancer) instancers.computeIfAbsent(key, createAndDeferInit); + } + + public Plan createFramePlan() + { + // Go wide on instancers to process deletions in parallel. + return ForEachPlan.of(() -> new ArrayList<>(instancers.values()), ClrwlAbstractInstancer::parallelUpdate); + } + + public void prepareFrame(LightStorage lightStorage, EnvironmentStorage environmentStorage) + { + // Thread safety: flush is called from the render thread after all visual updates have been made, + // so there are no:tm: threads we could be racing with. + for (var init : initializationQueue) + { + var instancer = init.instancer(); + + if (instancer.instanceCount() > 0) + { + initialize(init.key(), instancer); + } + else + { + instancers.remove(init.key()); + } + } + + initializationQueue.clear(); + } + + public abstract void preparePass(IrisRenderingPipeline pipeline, boolean isShadow); + public abstract void renderSolid(IrisRenderingPipeline pipeline, boolean isShadow); + public abstract void renderTranslucent(IrisRenderingPipeline pipeline, boolean isShadow); + + public abstract void renderCrumbling(IrisRenderingPipeline pipeline, List crumblingBlocks); + + + public void onRenderOriginChanged() + { + instancers.values() + .forEach(ClrwlAbstractInstancer::clear); + } + + protected abstract N create(ClrwlInstancerKey type); + + protected abstract void initialize(ClrwlInstancerKey key, N instancer); + + private N createAndDeferInit(ClrwlInstancerKey key) + { + var out = create(key); + + // Only queue the instancer for initialization if it has anything to render. + if (checkAndWarnEmptyModel(key.model())) { + // Thread safety: this method is called atomically from within computeIfAbsent, + // so you'd think we don't need extra synchronization to protect the queue, but + // somehow threads can race here and wind up never initializing an instancer. + initializationQueue.add(new UninitializedInstancer<>(key, out)); + } + return out; + } + + private static boolean checkAndWarnEmptyModel(Model model) + { + if (!model.meshes().isEmpty()) { + return true; + } + + if (WARN_EMPTY_MODELS) { + StringBuilder builder = new StringBuilder(); + builder.append("Creating an instancer for a model with no meshes! Stack trace:"); + + StackWalker.getInstance() + .forEach(f -> builder.append("\n\t") + .append(f.toString())); + + FlwBackend.LOGGER.warn(builder.toString()); + } + + return false; + } + + @FunctionalInterface + protected interface State2Instancer> + { + // I tried using a plain Function, I> here, but it exploded with type errors. + @Nullable I apply(ClrwlInstanceHandle.State state); + } + + protected static > Map, Int2ObjectMap>>>> doCrumblingSort(List crumblingBlocks, State2Instancer cast) + { + Map, Int2ObjectMap>>>> byType = new HashMap<>(); + for (Engine.CrumblingBlock block : crumblingBlocks) + { + int progress = block.progress(); + + if (progress < 0 || progress >= ModelBakery.DESTROY_TYPES.size()) + { + continue; + } + + for (Instance instance : block.instances()) + { + // Filter out instances that weren't created by this engine. + // If all is well, we probably shouldn't take the `continue` + // branches but better to do checked casts. + if (!(instance.handle() instanceof ClrwlInstanceHandle impl)) + { + continue; + } + + var instancer = cast.apply(impl.state); + + if (instancer == null) + { + continue; + } + + byType.computeIfAbsent(new GroupKey<>(instancer.type, instancer.environment), $ -> new Int2ObjectArrayMap<>()) + .computeIfAbsent(progress, $ -> new ArrayList<>()) + .add(Pair.of(instancer, impl)); + } + } + return byType; + } + + public void delete() + { + instancers.clear(); + initializationQueue.clear(); + } + + public abstract void triggerFallback(); + + protected String getShaderPackName() + { + return Iris.getCurrentPackName(); + } + + protected ClrwlRenderingPhase currentRenderPhase = ClrwlRenderingPhase.SOLID; + + protected void setPhase(ClrwlRenderingPhase phase, boolean shadow) + { + var name = "Clrwl " + (shadow ? "Shadow " : "") + StringUtils.capitalize(phase.name().toLowerCase(Locale.ROOT).replace("_", " ")); + + GLDebug.popGroup(); + GLDebug.pushGroup(phase.getValue(), name); + + currentRenderPhase = phase; + } + + protected record UninitializedInstancer(ClrwlInstancerKey key, N instancer) { + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlEngine.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlEngine.java new file mode 100644 index 000000000..02b7da4be --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlEngine.java @@ -0,0 +1,389 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.ClrwlBackend; +import net.irisshaders.iris.compat.flywheel.engine.embed.EmbeddedEnvironment; +import net.irisshaders.iris.compat.flywheel.engine.embed.EnvironmentStorage; +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlBufferBindings; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlGbuffersPassUniforms; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlOptionsUniforms; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlShadowPassUniforms; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import dev.engine_room.flywheel.api.backend.Engine; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.instance.Instancer; +import dev.engine_room.flywheel.api.instance.InstancerProvider; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.api.task.Plan; +import dev.engine_room.flywheel.api.visualization.VisualEmbedding; +import dev.engine_room.flywheel.api.visualization.VisualizationContext; +import dev.engine_room.flywheel.backend.compile.FlwPrograms; +import dev.engine_room.flywheel.backend.engine.LightStorage; +import dev.engine_room.flywheel.backend.engine.embed.Environment; +import dev.engine_room.flywheel.backend.gl.GlStateTracker; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.lib.task.SimplePlan; +import it.unimi.dsi.fastutil.longs.LongSet; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.core.Vec3i; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.phys.Vec3; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ClrwlEngine implements Engine +{ + public interface DrawManagerFactory + { + ClrwlDrawManager build(ShaderSources sources, ShaderPack pack, ProgramSet programSet, boolean isFallback); + } + + private final ClrwlDrawManager drawManager; + private final int sqrMaxOriginDistance; + private final EnvironmentStorage environmentStorage; + private final LightStorage lightStorage; + private BlockPos renderOrigin = BlockPos.ZERO; + + private final LevelAccessor level; + private final NamespacedId dimension; + private final ShaderPack pack; + + private final ShadowCulling shadowCulling; + + public ClrwlEngine(LevelAccessor level, int maxOriginDistance, DrawManagerFactory drawManagerFactory) + { + ClientLevel clientLevel = (ClientLevel) level; + this.level = level; + this.dimension = new NamespacedId(clientLevel.dimension().location().getNamespace(), + clientLevel.dimension().location().getPath()); + + this.pack = Iris.getCurrentPack().orElseThrow(); + + var programSet = pack.getProgramSet(dimension); + ClrwlBufferBindings.setBase(ClrwlBackend.getShaderStorageBase(pack)); + var isFallback = (programSet.getClrwlPrograms().isFallbackMode()); + + this.drawManager = drawManagerFactory.build(FlwPrograms.SOURCES, pack, programSet, isFallback); + this.sqrMaxOriginDistance = maxOriginDistance * maxOriginDistance; + this.environmentStorage = new EnvironmentStorage(); + this.lightStorage = new LightStorage(level); + + this.shadowCulling = new ShadowCulling(programSet); + } + + @Override + public VisualizationContext createVisualizationContext() + { + return new ClrwlMainVisualizationContext(); + } + + @Override + public Plan createFramePlan() + { + // render() runs up to three times per frame (shadow, solid, translucent), but must only prepare the frame + // once. Flywheel raises its frame flag after this plan and waits for it before render(), which orders this + // write before the read there. + return drawManager.createFramePlan() + .and(lightStorage.createFramePlan()) + .then(SimplePlan.of(() -> shouldPrepareFrame = true)); + } + + @Override + public Vec3i renderOrigin() + { + return renderOrigin; + } + + @Override + public boolean updateRenderOrigin(Camera camera) + { + Vec3 cameraPos = camera.getPosition(); + double dx = renderOrigin.getX() - cameraPos.x; + double dy = renderOrigin.getY() - cameraPos.y; + double dz = renderOrigin.getZ() - cameraPos.z; + double distanceSqr = dx * dx + dy * dy + dz * dz; + + if (distanceSqr <= sqrMaxOriginDistance) { + return false; + } + + renderOrigin = BlockPos.containing(cameraPos); + drawManager.onRenderOriginChanged(); + return true; + } + + @Override + public void lightSections(LongSet longSet) + { + lightStorage.sections(longSet); + } + + @Override + public void onLightUpdate(SectionPos sectionPos, LightLayer lightLayer) + { + lightStorage.onLightUpdate(sectionPos.asLong()); + } + + private boolean shouldPrepareFrame = false; + + private void prepareFrame(RenderContext context) + { + if (shouldPrepareFrame) + { + shouldPrepareFrame = false; + + environmentStorage.flush(); + shadowCulling.refresh(); + ClrwlUniforms.updateFrame(context); + ClrwlOptionsUniforms.update(Minecraft.getInstance().options); + + drawManager.prepareFrame(lightStorage, environmentStorage); + } + } + + private void preparePass(RenderContext context, IrisRenderingPipeline irisPipeline) + { + if (context instanceof ShadowRenderContext shadowContext) + { + drawManager.preparePass(irisPipeline, true); + ClrwlShadowPassUniforms.update(shadowContext, pack, dimension, shadowCulling); + } + else + { + drawManager.preparePass(irisPipeline, false); + ClrwlGbuffersPassUniforms.update(context, pack, dimension); + } + } + + @Override + public void render(RenderContext context) + { + try (var state = GlStateTracker.getRestoreState()) + { + prepareFrame(context); + + var curPipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (curPipeline instanceof IrisRenderingPipeline irisPipeline) + { + if (context instanceof ShadowRenderContext shadowContext) + { + if (shadowCulling.shouldRenderShadow()) + { + if (shadowContext.phase() == ShadowRenderingPhase.SOLID) + { + preparePass(context, irisPipeline); + drawManager.renderSolid(irisPipeline, true); + } + else + { + drawManager.renderTranslucent(irisPipeline, true); + } + } + } + else if (context instanceof TranslucentRenderContext) + { + drawManager.renderTranslucent(irisPipeline, false); + } + else + { + preparePass(context, irisPipeline); + drawManager.renderSolid(irisPipeline, false); + } + } + else + { + handleInvalidPipeline(curPipeline); + } + } + catch (Exception e) + { + Colorwheel.LOGGER.error("Falling back", e); + drawManager.triggerFallback(); + } + } + + @Override + public void renderCrumbling(RenderContext renderContext, List crumblingBlocks) + { + try (var state = GlStateTracker.getRestoreState()) + { + var curPipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (curPipeline instanceof IrisRenderingPipeline irisPipeline) + { + drawManager.renderCrumbling(irisPipeline, crumblingBlocks); + } + else + { + handleInvalidPipeline(curPipeline); + } + } + catch (Exception e) + { + Colorwheel.LOGGER.error("Falling back", e); + drawManager.triggerFallback(); + } + } + + protected boolean alreadyGotInvalidPipeline = false; + + protected void handleInvalidPipeline(WorldRenderingPipeline worldPipeline) + { + if (alreadyGotInvalidPipeline) + { + return; + } + + Colorwheel.LOGGER.warn("Got unexpected rendering pipeline, rendering issues may occur."); + Colorwheel.LOGGER.warn("Got pipeline: {}", worldPipeline); + + alreadyGotInvalidPipeline = true; + } + + @Override + public void delete() + { + drawManager.delete(); + lightStorage.delete(); + environmentStorage.delete(); + } + + public EnvironmentStorage environmentStorage() { + return environmentStorage; + } + + public LightStorage lightStorage() { + return lightStorage; + } + + public LevelAccessor level() { return level; } + + public Instancer instancer(ClrwlInstanceVisual visual, Environment environment, InstanceType type, Model model, int bias) + { + return drawManager.getInstancer(visual, environment, type, model, bias); + } + + public class ClrwlMainVisualizationContext implements VisualizationContext + { + private final ClrwlInstancerProvider instancerProvider; + private final Map blockEntityCtxs = new HashMap<>(); + private final Map entityCtxs = new HashMap<>(); + + public ClrwlMainVisualizationContext() + { + instancerProvider = new ClrwlInstancerProvider(ClrwlEngine.this, ClrwlInstanceVisual.undefined()); + } + + public VisualizationContext getBlockEntityVisualCtx(int irisId, int lightEmission) + { + return blockEntityCtxs.computeIfAbsent(new ClrwlBlockEntityVisualizationContext.Key(irisId, lightEmission), ClrwlBlockEntityVisualizationContext::new); + } + + public VisualizationContext getEntityVisualCtx(int irisId) + { + return entityCtxs.computeIfAbsent(irisId, ClrwlEntityVisualizationContext::new); + } + + @Override + public InstancerProvider instancerProvider() { + return instancerProvider; + } + + @Override + public Vec3i renderOrigin() { + return ClrwlEngine.this.renderOrigin(); + } + + @Override + public VisualEmbedding createEmbedding(Vec3i renderOrigin) + { + var out = new EmbeddedEnvironment(ClrwlEngine.this, ClrwlInstanceVisual.undefined(), renderOrigin); + environmentStorage.track(out); + return out; + } + } + + private class ClrwlBlockEntityVisualizationContext implements VisualizationContext + { + record Key(int irisId, int lightEmission) + { + } + + private final int irisId; + private final int lightEmission; + private final ClrwlInstancerProvider instancerProvider; + + public ClrwlBlockEntityVisualizationContext(Key key) + { + this.irisId = key.irisId; + this.lightEmission = key.lightEmission; + instancerProvider = new ClrwlInstancerProvider(ClrwlEngine.this, ClrwlInstanceVisual.blockEntity(irisId, lightEmission)); + } + + @Override + public InstancerProvider instancerProvider() + { + return instancerProvider; + } + + @Override + public Vec3i renderOrigin() { + return ClrwlEngine.this.renderOrigin(); + } + + @Override + public VisualEmbedding createEmbedding(Vec3i renderOrigin) + { + var out = new EmbeddedEnvironment(ClrwlEngine.this, ClrwlInstanceVisual.blockEntity(irisId, lightEmission), renderOrigin); + environmentStorage.track(out); + return out; + } + } + + private class ClrwlEntityVisualizationContext implements VisualizationContext + { + private final int irisId; + private final ClrwlInstancerProvider instancerProvider; + + public ClrwlEntityVisualizationContext(int irisId) + { + this.irisId = irisId; + instancerProvider = new ClrwlInstancerProvider(ClrwlEngine.this, ClrwlInstanceVisual.entity(irisId)); + } + + @Override + public InstancerProvider instancerProvider() + { + return instancerProvider; + } + + @Override + public Vec3i renderOrigin() { + return ClrwlEngine.this.renderOrigin(); + } + + @Override + public VisualEmbedding createEmbedding(Vec3i renderOrigin) + { + var out = new EmbeddedEnvironment(ClrwlEngine.this, ClrwlInstanceVisual.entity(irisId), renderOrigin); + environmentStorage.track(out); + return out; + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlFramebuffers.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlFramebuffers.java new file mode 100644 index 000000000..afb5a6e90 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlFramebuffers.java @@ -0,0 +1,200 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlOitPrograms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import net.irisshaders.iris.gl.blending.BufferBlendInformation; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +public class ClrwlFramebuffers +{ + private final IrisRenderingPipeline irisPipeline; + private final ProgramSet programSet; + + private final Map framebuffers = new HashMap<>(); + + @Nullable + private ClrwlOitFramebuffers gbuffersOitFramebuffer; + @Nullable + private ClrwlOitFramebuffers shadowOitFramebuffer; + + private final Map> bufferBlendOverrides = new HashMap<>(); + + public ClrwlFramebuffers(IrisRenderingPipeline irisPipeline, ProgramSet programSet) + { + this.irisPipeline = irisPipeline; + this.programSet = programSet; + } + + @Nullable + public GlFramebuffer getFramebuffer(ClrwlProgramId program) + { + var programSetAccessor = programSet.getClrwlPrograms(); + + return framebuffers.computeIfAbsent(program, (key) -> + { + var maybeSrc = programSetAccessor.getClrwlProgramSource(key); + + if (maybeSrc.isEmpty()) + { + return null; + } + + var src = maybeSrc.get(); + + switch (key.group()) + { + case GBUFFERS -> + { + return irisPipeline.getFlywheelGbuffersFramebuffer(src, program.afterTranslucent()); + } + + case SHADOW -> + { + return irisPipeline.getFlywheelShadowFramebuffer(src); + } + } + + throw new RuntimeException("Unknown program group: " + key.group().groupName()); + }); + } + + @Nullable + public ClrwlOitFramebuffers getOitFramebuffers(ClrwlProgramGroup programGroup, ClrwlOitPrograms oitPrograms, ProgramSet programSet, ProgramDirectives directives) + { + switch (programGroup) + { + case GBUFFERS -> + { + if (gbuffersOitFramebuffer == null) + { + gbuffersOitFramebuffer = new ClrwlOitFramebuffers(programGroup, oitPrograms, irisPipeline, programSet, directives); + } + + return gbuffersOitFramebuffer; + } + case SHADOW -> + { + if (shadowOitFramebuffer == null) + { + shadowOitFramebuffer = new ClrwlOitFramebuffers(programGroup, oitPrograms, irisPipeline, programSet, directives); + } + + return shadowOitFramebuffer; + } + } + + throw new RuntimeException("Unknown program group: " + programGroup); + } + + public Optional getBlendModeOverride(ClrwlProgramId programId) + { + var programSetAccessor = programSet.getClrwlPrograms(); + + if (!programSetAccessor.isFallbackMode()) + { + var directives = programSetAccessor.getClrwlDirectives(); + var realProgramId = programSetAccessor.getRealClrwlProgram(programId); + + return realProgramId.flatMap(directives::getBlendModeOverride).or(programId::defaultBlendOverride); + } + else + { + var maybeSrc = programSetAccessor.getClrwlProgramSource(programId); + + return maybeSrc.flatMap(src -> src.getDirectives().getBlendModeOverride() + .map(bm -> new ClrwlBlendModeOverride(bm.getBlendMode()))) + .or(programId::defaultBlendOverride); + } + } + + public List getBufferBlendModeOverrides(ClrwlProgramId programId) + { + var programSetAccessor = programSet.getClrwlPrograms(); + + if (!programSetAccessor.isFallbackMode()) + { + var realProgram = programSetAccessor.getRealClrwlProgram(programId); + + if (realProgram.isEmpty()) + { + return Collections.emptyList(); + } + + return bufferBlendOverrides.computeIfAbsent(realProgram.get(), (key) -> + { + var directives = programSetAccessor.getClrwlDirectives(); + var maybeSrc = programSetAccessor.getClrwlProgramSource(key); + + return maybeSrc + .map(src -> computeBufferBlendOff(src, directives.getBufferBlendModeOverrides(realProgram.get()))) + .orElse(Collections.emptyList()); + }); + } + else + { + return bufferBlendOverrides.computeIfAbsent(programId, (key) -> + { + var maybeSrc = programSetAccessor.getClrwlProgramSource(programId); + + return maybeSrc + .map(src -> src.getDirectives().getBufferBlendOverrides()) + .orElse(Collections.emptyList()); + }); + } + } + + private List computeBufferBlendOff(ProgramSource source, List blendOverrides) + { + if (blendOverrides.isEmpty()) + { + return Collections.emptyList(); + } + + var drawBuffers = source.getDirectives().getDrawBuffers(); + var list = new ArrayList(); + + for (int i = 0; i < drawBuffers.length; i++) + { + int buf = drawBuffers[i]; + + for (var entry : blendOverrides) + { + if (entry.index() == buf) + { + list.add(new BufferBlendInformation(i, entry.blendMode())); + } + } + } + + return ImmutableList.copyOf(list); + } + + public void delete() + { + + if (gbuffersOitFramebuffer != null) + { + gbuffersOitFramebuffer.delete(); + gbuffersOitFramebuffer = null; + } + + if (shadowOitFramebuffer != null) + { + shadowOitFramebuffer.delete(); + shadowOitFramebuffer = null; + } + + // The framebuffers belong to the Iris render targets, which destroy them with the pipeline. + framebuffers.clear(); + bufferBlendOverrides.clear(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceHandle.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceHandle.java new file mode 100644 index 000000000..e0fc089ae --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceHandle.java @@ -0,0 +1,99 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceHandle; +import dev.engine_room.flywheel.backend.engine.AbstractInstancer; +import org.jetbrains.annotations.UnknownNullability; + +public class ClrwlInstanceHandle implements InstanceHandle +{ + @UnknownNullability + public State state; + public int index; + + public ClrwlInstanceHandle(@UnknownNullability State state) { + this.state = state; + } + + @Override + public void setChanged() { + state = state.setChanged(index); + } + + @Override + public void setDeleted() { + state = state.setDeleted(index); + // invalidate ourselves + clear(); + } + + @Override + public void setVisible(boolean visible) { + state = state.setVisible(this, index, visible); + } + + @Override + public boolean isVisible() { + return state instanceof AbstractInstancer; + } + + public void clear() { + index = -1; + } + + public interface State + { + State setChanged(int index); + + State setDeleted(int index); + + State setVisible(ClrwlInstanceHandle handle, int index, boolean visible); + } + + public record Hidden(ClrwlAbstractInstancer.Recreate recreate, I instance) implements State + { + @Override + public State setChanged(int index) { + return this; + } + + @Override + public State setDeleted(int index) { + return this; + } + + @Override + public State setVisible(ClrwlInstanceHandle handle, int index, boolean visible) { + if (!visible) { + return this; + } + var instancer = recreate.recreate(); + return instancer.revealInstance(handle, instance); + } + } + + public record Deleted() implements State + { + private static final Deleted INSTANCE = new Deleted<>(); + + @SuppressWarnings("unchecked") + public static Deleted instance() { + return (Deleted) INSTANCE; + } + + @Override + public State setChanged(int index) { + return this; + } + + @Override + public State setDeleted(int index) { + return this; + } + + @Override + public State setVisible(ClrwlInstanceHandle handle, int index, boolean visible) { + return this; + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceVisual.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceVisual.java new file mode 100644 index 000000000..0b94c1fee --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstanceVisual.java @@ -0,0 +1,90 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +public record ClrwlInstanceVisual(Type type, int irisId, int lightEmission) +{ + // shaders.properties is incorrect: the default value when entry is missing is -1 + private static final int UNDEFINED_ID = -1; + private static final ClrwlInstanceVisual UNDEFINED = new ClrwlInstanceVisual(Type.UNDEFINED, UNDEFINED_ID, 0); + + public static ClrwlInstanceVisual undefined() + { + return UNDEFINED; + } + + public static ClrwlInstanceVisual blockEntity(int irisId, int lightEmission) + { + return new ClrwlInstanceVisual(Type.BLOCKENTITY, irisId, lightEmission); + } + + public static ClrwlInstanceVisual entity(int irisId) + { + return new ClrwlInstanceVisual(Type.ENTITY, irisId, 0); + } + + public int getBlockEntity() + { + if (type == Type.BLOCKENTITY) + { + return irisId; + } + return UNDEFINED_ID; + } + + public int getEntity() + { + if (type == Type.ENTITY) + { + return irisId; + } + + return UNDEFINED_ID; + } + + @Override + public boolean equals(Object o) + { + if (o instanceof ClrwlInstanceVisual rhs) + { + switch (type) + { + case UNDEFINED -> + { + return rhs.type == Type.UNDEFINED; + } + case BLOCKENTITY -> + { + return rhs.type == Type.BLOCKENTITY && rhs.irisId == this.irisId; + } + case ENTITY -> + { + return rhs.type == Type.ENTITY && rhs.irisId == this.irisId; + } + } + } + + return false; + } + + @Override + public int hashCode() + { + int prime = 31; + int result = 1; + + result = prime * result + this.type.hashCode(); + + if (type != Type.UNDEFINED) + { + result = prime * result + this.irisId; + } + + return result; + } + + public enum Type + { + UNDEFINED, + BLOCKENTITY, + ENTITY + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerKey.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerKey.java new file mode 100644 index 000000000..f8f387ec3 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerKey.java @@ -0,0 +1,36 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.backend.engine.embed.Environment; + +public record ClrwlInstancerKey(ClrwlInstanceVisual visual, Environment environment, InstanceType type, Model model, int bias) +{ + public ClrwlInstancerKey(ClrwlInstanceVisual visual, Environment environment, InstanceType type, Model model, int bias) + { + this.visual = visual; + this.environment = environment; + this.type = type; + this.model = model; + this.bias = bias; + } + + public ClrwlInstanceVisual visual() { return this.visual; } + + public Environment environment() { + return this.environment; + } + + public InstanceType type() { + return this.type; + } + + public Model model() { + return this.model; + } + + public int bias() { + return this.bias; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerProvider.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerProvider.java new file mode 100644 index 000000000..1ec24e7be --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlInstancerProvider.java @@ -0,0 +1,17 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.instance.Instancer; +import dev.engine_room.flywheel.api.instance.InstancerProvider; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.backend.engine.embed.GlobalEnvironment; + +public record ClrwlInstancerProvider(ClrwlEngine engine, ClrwlInstanceVisual visual) implements InstancerProvider +{ + @Override + public Instancer instancer(InstanceType type, Model model, int bias) + { + return engine.instancer(visual, GlobalEnvironment.INSTANCE, type, model, bias); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialEncoder.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialEncoder.java new file mode 100644 index 000000000..253db5115 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialEncoder.java @@ -0,0 +1,77 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.material.*; +import net.minecraft.util.Mth; + +// Materials are unpacked in "flywheel:flywheel/internal/packed_material.glsl" +public final class ClrwlMaterialEncoder +{ + + // The number of bits each property takes up + private static final int BLUR_LENGTH = 1; + private static final int MIPMAP_LENGTH = 1; + private static final int BACKFACE_CULLING_LENGTH = 1; + private static final int POLYGON_OFFSET_LENGTH = 1; + private static final int DEPTH_TEST_LENGTH = Mth.ceillog2(DepthTest.values().length); + private static final int TRANSPARENCY_LENGTH = Mth.ceillog2(Transparency.values().length); + private static final int WRITE_MASK_LENGTH = Mth.ceillog2(WriteMask.values().length); + private static final int USE_OVERLAY_LENGTH = 1; + private static final int USE_LIGHT_LENGTH = 1; + private static final int CARDINAL_LIGHTING_MODE_LENGTH = Mth.ceillog2(CardinalLightingMode.values().length); + private static final int AMBIENT_OCCLUSION_LENGTH = 1; + + // The bit offset of each property + private static final int BLUR_OFFSET = 0; + private static final int MIPMAP_OFFSET = BLUR_OFFSET + BLUR_LENGTH; + private static final int BACKFACE_CULLING_OFFSET = MIPMAP_OFFSET + MIPMAP_LENGTH; + private static final int POLYGON_OFFSET_OFFSET = BACKFACE_CULLING_OFFSET + BACKFACE_CULLING_LENGTH; + private static final int DEPTH_TEST_OFFSET = POLYGON_OFFSET_OFFSET + POLYGON_OFFSET_LENGTH; + private static final int TRANSPARENCY_OFFSET = DEPTH_TEST_OFFSET + DEPTH_TEST_LENGTH; + private static final int WRITE_MASK_OFFSET = TRANSPARENCY_OFFSET + TRANSPARENCY_LENGTH; + private static final int USE_OVERLAY_OFFSET = WRITE_MASK_OFFSET + WRITE_MASK_LENGTH; + private static final int USE_LIGHT_OFFSET = USE_OVERLAY_OFFSET + USE_OVERLAY_LENGTH; + private static final int CARDINAL_LIGHTING_MODE_OFFSET = USE_LIGHT_OFFSET + USE_LIGHT_LENGTH; + private static final int AMBIENT_OCCLUSION_OFFSET = CARDINAL_LIGHTING_MODE_OFFSET + CARDINAL_LIGHTING_MODE_LENGTH; + + // The bit mask for each property + private static final int BLUR_MASK = bitMask(BLUR_LENGTH, BLUR_OFFSET); + private static final int MIPMAP_MASK = bitMask(MIPMAP_LENGTH, MIPMAP_OFFSET); + private static final int BACKFACE_CULLING_MASK = bitMask(BACKFACE_CULLING_LENGTH, BACKFACE_CULLING_OFFSET); + private static final int POLYGON_OFFSET_MASK = bitMask(POLYGON_OFFSET_LENGTH, POLYGON_OFFSET_OFFSET); + private static final int DEPTH_TEST_MASK = bitMask(DEPTH_TEST_LENGTH, DEPTH_TEST_OFFSET); + private static final int TRANSPARENCY_MASK = bitMask(TRANSPARENCY_LENGTH, TRANSPARENCY_OFFSET); + private static final int WRITE_MASK_MASK = bitMask(WRITE_MASK_LENGTH, WRITE_MASK_OFFSET); + private static final int USE_OVERLAY_MASK = bitMask(USE_OVERLAY_LENGTH, USE_OVERLAY_OFFSET); + private static final int USE_LIGHT_MASK = bitMask(USE_LIGHT_LENGTH, USE_LIGHT_OFFSET); + private static final int CARDINAL_LIGHTING_MODE_MASK = bitMask(CARDINAL_LIGHTING_MODE_LENGTH, CARDINAL_LIGHTING_MODE_OFFSET); + private static final int AMBIENT_OCCLUSION_MASK = bitMask(AMBIENT_OCCLUSION_LENGTH, AMBIENT_OCCLUSION_OFFSET); + + private ClrwlMaterialEncoder() { + } + + private static int bitMask(int bitLength, int bitOffset) { + return ((1 << bitLength) - 1) << bitOffset; + } + + // Packed format: + // ambientOcclusion[1] | cardinalLightingMode[2] | useLight[1] | useOverlay[1] | writeMask[2] | transparency[3] | depthTest[4] | polygonOffset[1] | backfaceCulling[1] | mipmap[1] | blur[1] + public static int packProperties(Material material) { + int bits = 0; + + if (material.blur()) bits |= BLUR_MASK; + if (material.mipmap()) bits |= MIPMAP_MASK; + if (material.backfaceCulling()) bits |= BACKFACE_CULLING_MASK; + if (material.polygonOffset()) bits |= POLYGON_OFFSET_MASK; + bits |= (material.depthTest().ordinal() << DEPTH_TEST_OFFSET) & DEPTH_TEST_MASK; + bits |= (material.transparency().ordinal() << TRANSPARENCY_OFFSET) & TRANSPARENCY_MASK; + bits |= (material.writeMask().ordinal() << WRITE_MASK_OFFSET) & WRITE_MASK_MASK; + if (material.useOverlay()) bits |= USE_OVERLAY_MASK; + if (material.useLight()) bits |= USE_LIGHT_MASK; + bits |= (material.cardinalLightingMode() + .ordinal() << CARDINAL_LIGHTING_MODE_OFFSET) & CARDINAL_LIGHTING_MODE_MASK; + + if (material.ambientOcclusion()) bits |= AMBIENT_OCCLUSION_MASK; + + return bits; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialRenderState.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialRenderState.java new file mode 100644 index 000000000..6f7042313 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMaterialRenderState.java @@ -0,0 +1,229 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import dev.engine_room.flywheel.api.material.DepthTest; +import dev.engine_room.flywheel.api.material.Material; +import dev.engine_room.flywheel.api.material.Transparency; +import dev.engine_room.flywheel.api.material.WriteMask; +import dev.engine_room.flywheel.backend.Samplers; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BufferBlendInformation; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.AbstractTexture; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public final class ClrwlMaterialRenderState +{ + public static void setup(Material material, @Nullable ClrwlBlendModeOverride blendOverride, List bufferBlendOverrides) + { + setupTexture(material); + setupBackfaceCulling(material.backfaceCulling()); + setupPolygonOffset(material.polygonOffset()); + setupDepthTest(material.depthTest()); + setupTransparency(material.transparency(), blendOverride, bufferBlendOverrides); + setupWriteMask(material.writeMask()); + } + + public static void setupOit(Material material) + { + setupTexture(material); + setupBackfaceCulling(material.backfaceCulling()); + setupPolygonOffset(material.polygonOffset()); + setupDepthTest(material.depthTest()); + WriteMask mask = material.writeMask(); + boolean writeColor = mask.color(); + RenderSystem.colorMask(writeColor, writeColor, writeColor, writeColor); + } + + private static void setupTexture(Material material) + { + Samplers.DIFFUSE.makeActive(); + AbstractTexture texture = Minecraft.getInstance().getTextureManager().getTexture(material.texture()); + texture.setFilter(material.blur(), material.mipmap()); + int textureId = texture.getId(); + RenderSystem.setShaderTexture(0, textureId); + RenderSystem.bindTexture(textureId); + } + + private static void setupBackfaceCulling(boolean backfaceCulling) + { + if (backfaceCulling) { + RenderSystem.enableCull(); + } else { + RenderSystem.disableCull(); + } + + } + + private static void setupPolygonOffset(boolean polygonOffset) + { + if (polygonOffset) { + RenderSystem.polygonOffset(-1.0F, -10.0F); + RenderSystem.enablePolygonOffset(); + } else { + RenderSystem.polygonOffset(0.0F, 0.0F); + RenderSystem.disablePolygonOffset(); + } + + } + + private static void setupDepthTest(DepthTest depthTest) + { + switch (depthTest) { + case OFF: + RenderSystem.disableDepthTest(); + break; + case NEVER: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(512); + break; + case LESS: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(513); + break; + case EQUAL: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(514); + break; + case LEQUAL: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(515); + break; + case GREATER: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(516); + break; + case NOTEQUAL: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(517); + break; + case GEQUAL: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(518); + break; + case ALWAYS: + RenderSystem.enableDepthTest(); + RenderSystem.depthFunc(519); + } + + } + + private static void setupTransparency(Transparency transparency, @Nullable ClrwlBlendModeOverride blendOverride, List bufferBlendOverrides) + { + if (blendOverride == null) + { + switch (transparency) { + case OPAQUE: + RenderSystem.disableBlend(); + break; + case ADDITIVE: + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE); + break; + case LIGHTNING: + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE); + break; + case GLINT: + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_COLOR, GlStateManager.DestFactor.ONE, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); + break; + case CRUMBLING: + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.DST_COLOR, GlStateManager.DestFactor.SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); + break; + case TRANSLUCENT, ORDER_INDEPENDENT: + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); + break; + } + } + else + { + if (blendOverride.blendMode() == null) + { + RenderSystem.disableBlend(); + } + else + { + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(blendOverride.blendMode().srcRgb(), + blendOverride.blendMode().dstRgb(), + blendOverride.blendMode().srcAlpha(), + blendOverride.blendMode().dstAlpha()); + } + } + + for (var entry : bufferBlendOverrides) + { + if (entry.blendMode() == null) + { + IrisRenderSystem.disableBufferBlend(entry.index()); + } + else + { + IrisRenderSystem.enableBufferBlend(entry.index()); + IrisRenderSystem.blendFuncSeparatei(entry.index(), + entry.blendMode().srcRgb(), + entry.blendMode().dstRgb(), + entry.blendMode().srcAlpha(), + entry.blendMode().dstAlpha()); + } + } + } + + private static void setupWriteMask(WriteMask mask) + { + RenderSystem.depthMask(mask.depth()); + boolean writeColor = mask.color(); + RenderSystem.colorMask(writeColor, writeColor, writeColor, writeColor); + } + + public static void reset() + { + resetTexture(); + resetBackfaceCulling(); + resetPolygonOffset(); + resetDepthTest(); + resetTransparency(); + resetWriteMask(); + } + + private static void resetTexture() + { + Samplers.DIFFUSE.makeActive(); + RenderSystem.setShaderTexture(0, 0); + } + + private static void resetBackfaceCulling() + { + RenderSystem.enableCull(); + } + + private static void resetPolygonOffset() + { + RenderSystem.polygonOffset(0.0F, 0.0F); + RenderSystem.disablePolygonOffset(); + } + + private static void resetDepthTest() + { + RenderSystem.disableDepthTest(); + RenderSystem.depthFunc(515); + } + + private static void resetTransparency() + { + RenderSystem.disableBlend(); + RenderSystem.defaultBlendFunc(); + } + + private static void resetWriteMask() + { + RenderSystem.depthMask(true); + RenderSystem.colorMask(true, true, true, true); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMeshPool.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMeshPool.java new file mode 100644 index 000000000..82d4434b9 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlMeshPool.java @@ -0,0 +1,431 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.model.Mesh; +import dev.engine_room.flywheel.backend.engine.IndexPool; +import dev.engine_room.flywheel.backend.gl.GlPrimitive; +import dev.engine_room.flywheel.backend.gl.array.GlVertexArray; +import dev.engine_room.flywheel.backend.gl.buffer.GlBuffer; +import dev.engine_room.flywheel.backend.gl.buffer.GlBufferUsage; +import dev.engine_room.flywheel.backend.util.ReferenceCounted; +import dev.engine_room.flywheel.lib.memory.MemoryBlock; +import dev.engine_room.flywheel.lib.model.QuadMesh; +import dev.engine_room.flywheel.lib.model.RetexturedMesh; +import net.irisshaders.iris.vertices.NormalHelper; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.joml.Vector4fc; +import org.lwjgl.opengl.GL32; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +// Copy/Paste from MeshPool +// Changes are: +// - use of ColorwheelVertex instead of InternalVertex +// - tangents and midTextCoord being computed on upload +public class ClrwlMeshPool { + private final ClrwlVertexView vertexView; + private final Map meshes = new HashMap<>(); + private final List meshList = new ArrayList<>(); + private final List recentlyAllocated = new ArrayList<>(); + + private final GlBuffer vbo; + private final IndexPool indexPool; + + private boolean dirty; + private boolean anyToRemove; + + /** + * Create a new mesh pool. + */ + public ClrwlMeshPool() { + vertexView = ClrwlVertex.createVertexView(); + vbo = new GlBuffer(GlBufferUsage.DYNAMIC_DRAW); + indexPool = new IndexPool(); + } + + /** + * Allocate a model in the arena. + * + * @param mesh The model to allocate. + * @return A handle to the allocated model. + */ + public PooledMesh alloc(Mesh mesh) { + return meshes.computeIfAbsent(mesh, this::_alloc); + } + + private PooledMesh _alloc(Mesh m) { + PooledMesh bufferedModel = new PooledMesh(m); + meshList.add(bufferedModel); + recentlyAllocated.add(bufferedModel); + + dirty = true; + return bufferedModel; + } + + @Nullable + public ClrwlMeshPool.PooledMesh get(Mesh mesh) { + return meshes.get(mesh); + } + + public void flush() { + if (!dirty) { + return; + } + + if (anyToRemove) { + anyToRemove = false; + processDeletions(); + } + + if (!recentlyAllocated.isEmpty()) { + // Otherwise, just update the index with the new counts. + for (PooledMesh mesh : recentlyAllocated) { + indexPool.updateCount(mesh.mesh.indexSequence(), mesh.indexCount()); + } + indexPool.flush(); + recentlyAllocated.clear(); + } + + uploadAll(); + dirty = false; + } + + private void processDeletions() { + // remove deleted meshes + meshList.removeIf(pooledMesh -> { + boolean deleted = pooledMesh.isDeleted(); + if (deleted) { + meshes.remove(pooledMesh.mesh); + } + return deleted; + }); + } + + private void uploadAll() { + long neededSize = 0; + for (PooledMesh mesh : meshList) { + neededSize += mesh.byteSize(); + } + + final var vertexBlock = MemoryBlock.malloc(neededSize); + final long vertexPtr = vertexBlock.ptr(); + + int byteIndex = 0; + int baseVertex = 0; + for (PooledMesh mesh : meshList) + { + mesh.baseVertex = baseVertex; + + vertexView.ptr(vertexPtr + byteIndex); + vertexView.vertexCount(mesh.vertexCount()); + mesh.mesh.write(vertexView); + + mesh.meshCenter = computeMeshCenter(vertexView); + + if (!vertexView.consumeExtendedWriteFlag()) + { + Mesh baseMesh = mesh.mesh; + + while (baseMesh instanceof RetexturedMesh retextured) + { + baseMesh = retextured.mesh(); + } + + if (baseMesh instanceof QuadMesh quad) + { + computeExtendedQuadData(quad, vertexView); + } + else + { + computeExtendedData(baseMesh, vertexView); + } + } + else + { + // Vertex format is IrisVertexFormats.TERRAIN, therefore the mesh must be a QuadMesh + patchMidUVCoords(mesh.mesh, vertexView); + } + + byteIndex += mesh.byteSize(); + baseVertex += mesh.vertexCount(); + } + + vbo.upload(vertexBlock); + + vertexBlock.free(); + } + + private Vector3f computeMeshCenter(ClrwlVertexView vertexView) + { + float minX = Float.MAX_VALUE; + float minY = Float.MAX_VALUE; + float minZ = Float.MAX_VALUE; + float maxX = -Float.MAX_VALUE; + float maxY = -Float.MAX_VALUE; + float maxZ = -Float.MAX_VALUE; + + for (int i = 0; i < vertexView.vertexCount(); i++) + { + float x = vertexView.x(i); + float y = vertexView.y(i); + float z = vertexView.z(i); + + if (x < minX) + { + minX = x; + } + + if (x > maxX) + { + maxX = x; + } + + if (y < minY) + { + minY = y; + } + + if (y > maxY) + { + maxY = y; + } + + if (z < minZ) + { + minZ = z; + } + + if (z > maxZ) + { + maxZ = z; + } + } + + return new Vector3f((minX + maxX) / 2.0f, (minY + maxY) / 2.0f, (minZ + maxZ) / 2.0f); + } + + private void computeExtendedQuadData(QuadMesh mesh, ClrwlVertexView vertexView) + { + var quadCnt = mesh.vertexCount() / 4; + + var uArr = new float[4]; + var vArr = new float[4]; + var uvCnt = 0; + + for (int q = 0; q < quadCnt; q++) + { + int base = q * 4; + + float normalX = 0; + float normalY = 0; + float normalZ = 0; + uvCnt = 0; + +top: for (int vId = 0; vId < 4; vId++) + { + int idx = base + vId; + + normalX += vertexView.normalX(idx); + normalY += vertexView.normalY(idx); + normalZ += vertexView.normalZ(idx); + + float u = vertexView.u(idx); + float v = vertexView.v(idx); + + for (int i = 0; i < uvCnt; i++) + { + if (uArr[i] == u && vArr[i] == v) + { + continue top; + } + } + + uArr[uvCnt] = u; + vArr[uvCnt] = v; + uvCnt += 1; + } + + normalX /= 4.0F; + normalY /= 4.0F; + normalZ /= 4.0F; + + float midU = 0; + float midV = 0; + + for (int i = 0; i < uvCnt; i++) + { + midU += uArr[i]; + midV += vArr[i]; + } + + midU /= uvCnt; + midV /= uvCnt; + + int tangent = NormalHelper.computeTangent(normalX, normalY, normalZ, + vertexView.x(base + 0), vertexView.y(base + 0), vertexView.z(base + 0), vertexView.u(base + 0), vertexView.v(base + 0), + vertexView.x(base + 1), vertexView.y(base + 1), vertexView.z(base + 1), vertexView.u(base + 1), vertexView.v(base + 1), + vertexView.x(base + 2), vertexView.y(base + 2), vertexView.z(base + 2), vertexView.u(base + 2), vertexView.v(base + 2)); + + for (int vId = 0; vId < 4; vId++) + { + vertexView.packedEntity(base + vId, 0xFFFFFFFF); + vertexView.midU(base + vId, midU); + vertexView.midV(base + vId, midV); + vertexView.packedTangent(base + vId, tangent); + vertexView.packedMidBlock(base + vId, 0xFF << 24); + } + } + } + + private void computeExtendedData(Mesh mesh, ClrwlVertexView vertexView) + { + // TODO + + for (int i = 0; i < mesh.vertexCount(); i++) + { + vertexView.packedEntity(i, 0xFFFFFFFF); + vertexView.midU(i, 0); + vertexView.midV(i, 0); + vertexView.packedTangent(i, 0); + vertexView.packedMidBlock(i, 0xFF << 24); + } + } + + // Some Create blocks, like waterwheels, are QuadMesh but with degenerated triangles + // This causes issues with the method used by Iris to compute midTexCoord + private void patchMidUVCoords(Mesh mesh, ClrwlVertexView vertexView) + { + var quadCnt = mesh.vertexCount() / 4; + + var uArr = new float[4]; + var vArr = new float[4]; + var uvCnt = 0; + + for (int q = 0; q < quadCnt; q++) + { + int base = q * 4; + + uvCnt = 0; + +top: for (int vId = 0; vId < 4; vId++) + { + int idx = base + vId; + float u = vertexView.u(idx); + float v = vertexView.v(idx); + + for (int i = 0; i < uvCnt; i++) + { + if (uArr[i] == u && vArr[i] == v) + { + continue top; + } + } + + uArr[uvCnt] = u; + vArr[uvCnt] = v; + uvCnt += 1; + } + + float midU = 0; + float midV = 0; + + for (int i = 0; i < uvCnt; i++) + { + midU += uArr[i]; + midV += vArr[i]; + } + + midU /= uvCnt; + midV /= uvCnt; + + for (int vId = 0; vId < 4; vId++) + { + vertexView.midU(base + vId, midU); + vertexView.midV(base + vId, midV); + } + } + } + + public void bind(GlVertexArray vertexArray) { + indexPool.bind(vertexArray); + vertexArray.bindVertexBuffer(0, vbo.handle(), 0, ClrwlVertex.STRIDE); + vertexArray.bindAttributes(0, 0, ClrwlVertex.ATTRIBUTES); + } + + public void delete() { + vbo.delete(); + indexPool.delete(); + meshes.clear(); + meshList.clear(); + } + + public class PooledMesh extends ReferenceCounted { + public static final int INVALID_BASE_VERTEX = -1; + + private final Mesh mesh; + private Vector3f meshCenter; + private int baseVertex = INVALID_BASE_VERTEX; + + private PooledMesh(Mesh mesh) + { + this.mesh = mesh; + this.meshCenter = new Vector3f(0, 0, 0); + } + + public int vertexCount() { + return mesh.vertexCount(); + } + + public int byteSize() { + return mesh.vertexCount() * ClrwlVertex.STRIDE; + } + + public int indexCount() { + return mesh.indexCount(); + } + + public int baseVertex() { + return baseVertex; + } + + public int firstIndex() { + return ClrwlMeshPool.this.indexPool.firstIndex(mesh.indexSequence()); + } + + public long firstIndexByteOffset() { + return (long) firstIndex() * Integer.BYTES; + } + + public boolean isInvalid() { + return mesh.vertexCount() == 0 || baseVertex == INVALID_BASE_VERTEX || isDeleted(); + } + + public Vector4fc boundingSphere() + { + return mesh.boundingSphere(); + } + + public Vector3fc meshCenter() + { + return meshCenter; + } + + public void draw(int instanceCount) { + if (instanceCount > 1) { + GL32.glDrawElementsInstancedBaseVertex(GlPrimitive.TRIANGLES.glEnum, mesh.indexCount(), GL32.GL_UNSIGNED_INT, firstIndexByteOffset(), instanceCount, baseVertex); + } else { + GL32.glDrawElementsBaseVertex(GlPrimitive.TRIANGLES.glEnum, mesh.indexCount(), GL32.GL_UNSIGNED_INT, firstIndexByteOffset(), baseVertex); + } + } + + @Override + protected void _delete() { + ClrwlMeshPool.this.dirty = true; + ClrwlMeshPool.this.anyToRemove = true; + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitAccumulateOverride.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitAccumulateOverride.java new file mode 100644 index 000000000..f0b52b736 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitAccumulateOverride.java @@ -0,0 +1,67 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import net.irisshaders.iris.gl.texture.InternalTextureFormat; + +import java.util.Optional; + +public class ClrwlOitAccumulateOverride +{ + private final int drawBuffer; + private Optional coefficientId; // Empty = frontmost + private InternalTextureFormat format; + + public ClrwlOitAccumulateOverride(int drawBuffer, Optional coefficientId, InternalTextureFormat format) + { + this.drawBuffer = drawBuffer; + this.coefficientId = coefficientId; + this.format = format; + } + + public ClrwlOitAccumulateOverride(int drawBuffer, Optional coefficientId) + { + this(drawBuffer, coefficientId, InternalTextureFormat.RGBA8); + } + + public ClrwlOitAccumulateOverride(int drawBuffer, InternalTextureFormat format) + { + this(drawBuffer, Optional.empty(), format); + } + + public int drawBuffer() + { + return drawBuffer; + } + + public Optional coefficientId() + { + return coefficientId; + } + + public void setCoefficientId(Optional newValue) + { + this.coefficientId = newValue; + } + + public InternalTextureFormat format() + { + return format; + } + + public void setFormat(InternalTextureFormat format) + { + this.format = format; + } + + @Override + public boolean equals(Object obj) + { + if (obj instanceof ClrwlOitAccumulateOverride rhs) + { + return this.drawBuffer == rhs.drawBuffer + && this.coefficientId == rhs.coefficientId + && this.format == rhs.format; + } + + return false; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitFramebuffers.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitFramebuffers.java new file mode 100644 index 000000000..85c5a50b8 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlOitFramebuffers.java @@ -0,0 +1,606 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import net.irisshaders.iris.compat.flywheel.ClrwlSamplers; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlOitPrograms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlOitConfig; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import dev.engine_room.flywheel.backend.NoiseTextures; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.gl.GlTextureUnit; +import dev.engine_room.flywheel.lib.math.MoreMath; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendMode; +import net.irisshaders.iris.gl.blending.BlendModeFunction; +import net.irisshaders.iris.gl.blending.BufferBlendInformation; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import net.irisshaders.iris.shadows.ShadowMatrices; +import net.minecraft.client.Minecraft; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL46; + +import java.util.List; + +public class ClrwlOitFramebuffers +{ + public static final float[] CLEAR_TO_ZERO = {0, 0, 0, 0}; + public static final int[] DEPTH_RANGE_DRAW_BUFFERS = {GL46.GL_COLOR_ATTACHMENT0}; + public static final int[] DEPTH_ONLY_DRAW_BUFFERS = {}; + + private final int[] programDrawBuffers; + + private int[] renderTransmittanceDrawBuffers; + private int[] accumulateDrawBuffers; + + private final ClrwlProgramGroup programGroup; + private final ClrwlOitPrograms programs; + private final IrisRenderingPipeline irisPipeline; + private final ClrwlOitConfig config; + + private final float passZFar; + + private final int vao; + + public int mainFbo = -1; + public int coeffsFbo = -1; + + public int depthBounds = -1; + public int[] coefficients; + public int[] accumulate; + + private int lastWidth = -1; + private int lastHeight = -1; + + public ClrwlOitFramebuffers(ClrwlProgramGroup programGroup, ClrwlOitPrograms programs, IrisRenderingPipeline irisPipeline, ProgramSet programSet, ProgramDirectives directives) + { + ClrwlOitConfig config = programSet.getClrwlPrograms().getClrwlDirectives().getOitConfig(programGroup); + PackDirectives packDirectives = programSet.getPackDirectives(); + + this.programGroup = programGroup; + this.programs = programs; + this.irisPipeline = irisPipeline; + this.config = config; + this.programDrawBuffers = directives.getDrawBuffers(); + + if (GlCompat.SUPPORTS_DSA) + { + vao = GL46.glCreateVertexArrays(); + } + else + { + vao = GL32.glGenVertexArrays(); + } + + switch (programGroup) + { + case GBUFFERS -> + { + passZFar = Minecraft.getInstance().gameRenderer.getDepthFar(); + } + + case SHADOW -> + { + var shadowDirectives = packDirectives.getShadowDirectives(); + + if (shadowDirectives.getFov() != null) + { + passZFar = ShadowMatrices.FAR; + } + else + { + passZFar = shadowDirectives.getFarPlane(); + } + } + + default -> + { + passZFar = 4242.0f; + } + } + } + + public void delete() + { + deleteTextures(); + GL32.glDeleteVertexArrays(vao); + } + + private void deleteTextures() + { + // We sometimes get the same texture ID back when creating new textures, + // so bind zero to clear the GlStateManager + + if (depthBounds != -1) + { + GL32.glDeleteTextures(depthBounds); + depthBounds = -1; + } + + if (coefficients != null) + { + for (int i = 0; i < coefficients.length; i++) + { + ClrwlSamplers.getCoefficient(i).makeActive(); + RenderSystem.bindTexture(0); + } + + GL32.glDeleteTextures(coefficients); + coefficients = null; + } + + if (accumulate != null) + { + GL32.glDeleteTextures(accumulate); + accumulate = null; + } + + if (mainFbo != -1) + { + GL32.glDeleteFramebuffers(mainFbo); + mainFbo = -1; + } + + if (coeffsFbo != -1) + { + GL32.glDeleteFramebuffers(coeffsFbo); + coeffsFbo = -1; + } + + ClrwlSamplers.DEPTH_RANGE.makeActive(); + RenderSystem.bindTexture(0); + } + + /** + * Set up the framebuffer. + */ + public void prepare() + { + var depthInfo = ProgramGroupDepthInfo.of(irisPipeline, programGroup); + + maybeResizeFBOS(depthInfo.width(), depthInfo.height()); + + if (this.coeffsFbo != -1) + { + for (int i = 0; i < coefficients.length; i++) + { + int buffer = coefficients[i]; + + ClrwlSamplers.getCoefficient(i).makeActive(); + + // Bind zero to render system to make sure we clear their internal state + RenderSystem.bindTexture(0); + GL32.glBindTexture(GL32.GL_TEXTURE_2D_ARRAY, buffer); + } + } + + ClrwlSamplers.DEPTH_RANGE.makeActive(); + RenderSystem.bindTexture(depthBounds); + + ClrwlSamplers.NOISE.makeActive(); + NoiseTextures.BLUE_NOISE.bind(); + + if (coeffsFbo != -1) + { + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, coeffsFbo); + GL32.glFramebufferTexture(GL32.GL_FRAMEBUFFER, GL32.GL_DEPTH_ATTACHMENT, depthInfo.textureId(), 0); + } + + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, mainFbo); + GL32.glFramebufferTexture(GL32.GL_FRAMEBUFFER, GL32.GL_DEPTH_ATTACHMENT, depthInfo.textureId(), 0); + } + + /** + * Render out the min and max depth per fragment. + */ + public void prepareDepthRange() + { + // No depth writes, but we'll still use the depth test. + RenderSystem.depthMask(false); + RenderSystem.colorMask(true, true, true, true); + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE); + RenderSystem.blendEquation(GL32.GL_MAX); + + if (GlCompat.SUPPORTS_DSA) + { + GL46.glNamedFramebufferDrawBuffers(mainFbo, DEPTH_RANGE_DRAW_BUFFERS); + GL46.glClearNamedFramebufferfv(mainFbo, GL46.GL_COLOR, 0, new float[]{-passZFar, -passZFar, 0, 0}); + } + else + { + GL32.glDrawBuffers(DEPTH_RANGE_DRAW_BUFFERS); + RenderSystem.clearColor(-passZFar, -passZFar, 0, 0); + RenderSystem.clear(GL32.GL_COLOR_BUFFER_BIT, false); + } + } + + /** + * Generate the coefficients to the transmittance function. + */ + public boolean prepareRenderTransmittance() + { + if (coeffsFbo == -1) // Only frontmost fragments + { + return false; + } + + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, coeffsFbo); + + // No depth writes, but we'll still use the depth test + RenderSystem.depthMask(false); + RenderSystem.colorMask(true, true, true, true); + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE); + RenderSystem.blendEquation(GL32.GL_FUNC_ADD); + + if (GlCompat.SUPPORTS_DSA) + { + GL46.glNamedFramebufferDrawBuffers(coeffsFbo, renderTransmittanceDrawBuffers); + + for (int i = 0; i < renderTransmittanceDrawBuffers.length; i++) + { + GL46.glClearNamedFramebufferfv(coeffsFbo, GL46.GL_COLOR, i, CLEAR_TO_ZERO); + } + } + else + { + GL32.glDrawBuffers(renderTransmittanceDrawBuffers); + RenderSystem.clearColor(0, 0, 0, 0); + RenderSystem.clear(GL32.GL_COLOR_BUFFER_BIT, false); + } + + return true; + } + + /** + * If any fragment has its transmittance fall off to zero, search the transmittance + * function to determine at what depth that occurs and write out to the depth buffer. + */ +// public void renderDepthFromTransmittance() +// { +// if (coeffsFbo == -1) // Only opaques +// { +// return; +// } +// +// // Only write to depth, not color. +// RenderSystem.depthMask(true); +// RenderSystem.colorMask(false, false, false, false); +// RenderSystem.disableBlend(); +// RenderSystem.depthFunc(GL32.GL_ALWAYS); +// +// if (GlCompat.SUPPORTS_DSA) +// { +// GL46.glNamedFramebufferDrawBuffers(coeffsFbo, DEPTH_ONLY_DRAW_BUFFERS); +// } +// else +// { +// GL32.glDrawBuffers(DEPTH_ONLY_DRAW_BUFFERS); +// } +// +// programs.getOitDepthProgram() +// .bind(); +// +// drawFullscreenQuad(); +// } + + /** + * Sample the transmittance function and accumulate. + */ + public void prepareAccumulate() + { + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, mainFbo); + + // No depth writes, but we'll still use the depth test + RenderSystem.depthMask(false); + RenderSystem.colorMask(true, true, true, true); + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE); + RenderSystem.blendEquation(GL32.GL_FUNC_ADD); + + if (GlCompat.SUPPORTS_DSA) + { + GL46.glNamedFramebufferDrawBuffers(mainFbo, accumulateDrawBuffers); + + for (int i = 0; i < accumulateDrawBuffers.length; i++) + { + GL46.glClearNamedFramebufferfv(mainFbo, GL46.GL_COLOR, i, CLEAR_TO_ZERO); + } + } + else + { + GL32.glDrawBuffers(accumulateDrawBuffers); + RenderSystem.clearColor(0, 0, 0, 0); + RenderSystem.clear(GL32.GL_COLOR_BUFFER_BIT, false); + } + } + + /** + * Composite the accumulated luminance onto the main framebuffer. + */ + public void composite(GlFramebuffer target, @Nullable ClrwlBlendModeOverride blendModeOverride, List bufferBlendOverrides, boolean isShadow) + { + target.bind(); + + // The composite shader writes out the closest depth to gl_FragDepth. + // depthMask = true: OIT stuff renders on top of other transparent stuff. + // depthMask = false: other transparent stuff renders on top of OIT stuff. + // If Neo gets wavelet OIT we can use their hooks to be correct with everything. + RenderSystem.depthMask(true); + RenderSystem.colorMask(true, true, true, true); + + BlendMode blendMode; + + if (blendModeOverride == null) + { + // We rely on the blend func to achieve: + // final color = (1 - transmittance_total) * sum(color_f * alpha_f * transmittance_f) / sum(alpha_f * transmittance_f) + // + color_dst * transmittance_total + // + // Though note that the alpha value we emit in the fragment shader is actually (1. - transmittance_total). + // The extra inversion step is so we can have a sane alpha value written out for the fabulous blit shader to consume. + + blendMode = new BlendMode( + BlendModeFunction.SRC_ALPHA.getGlId(), + BlendModeFunction.ONE_MINUS_SRC_ALPHA.getGlId(), + BlendModeFunction.ONE.getGlId(), + BlendModeFunction.ONE_MINUS_SRC_ALPHA.getGlId() + ); + } + else + { + blendMode = blendModeOverride.blendMode(); + } + + if (blendMode == null) + { + RenderSystem.disableBlend(); + } + else + { + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(blendMode.srcRgb(), blendMode.dstRgb(), blendMode.srcAlpha(), blendMode.dstAlpha()); + RenderSystem.blendEquation(GL32.GL_FUNC_ADD); + } + + for (var entry : bufferBlendOverrides) + { + if (entry.blendMode() == null) + { + IrisRenderSystem.disableBufferBlend(entry.index()); + } + else + { + IrisRenderSystem.enableBufferBlend(entry.index()); + IrisRenderSystem.blendFuncSeparatei(entry.index(), entry.blendMode().srcRgb(), entry.blendMode().dstRgb(), entry.blendMode().srcAlpha(), entry.blendMode().dstAlpha()); + } + } + + RenderSystem.depthFunc(GL32.GL_ALWAYS); + + for (int i = 0; i < accumulate.length; i++) + { + ClrwlSamplers.getAccumulate(i).makeActive(); + RenderSystem.bindTexture(accumulate[i]); + } + + programs.getOitCompositeProgram(programDrawBuffers, config.coeffRanks(), config.accumulateOverrides(), isShadow) + .bind(); + + drawFullscreenQuad(); + } + + private void drawFullscreenQuad() + { + // Empty VAO, the actual full screen triangle is generated in the vertex shader + GlStateManager._glBindVertexArray(vao); + GL32.glDrawArrays(GL32.GL_TRIANGLES, 0, 3); + } + + private void maybeResizeFBOS(int width, int height) + { + if (lastWidth == width && lastHeight == height) + { + return; + } + + lastWidth = width; + lastHeight = height; + + deleteTextures(); + + resizeMainFBO(width, height); + resizeCoeffsFBO(width, height); + } + + private void resizeMainFBO(int width, int height) + { + var overrides = config.accumulateOverrides(); + var accumulateCnt = programDrawBuffers.length; + + mainFbo = GlCompat.SUPPORTS_DSA ? GL46.glCreateFramebuffers() : GL32.glGenFramebuffers(); + accumulate = new int[accumulateCnt]; + accumulateDrawBuffers = new int[accumulateCnt]; + + if (GlCompat.SUPPORTS_DSA) + { + depthBounds = GL46.glCreateTextures(GL46.GL_TEXTURE_2D); + + GL46.glTextureStorage2D(depthBounds, 1, GL32.GL_RG32F, width, height); + + for (int i = 0; i < accumulateCnt; i++) + { + var drawBuffer = programDrawBuffers[i]; + var format = InternalTextureFormat.RGBA16F; + + var maybeOverride = Utils.findFirst(overrides, e -> e.drawBuffer() == drawBuffer); + + if (maybeOverride.isPresent()) + { + format = maybeOverride.get().format(); + } + + int buffer = GL46.glCreateTextures(GL46.GL_TEXTURE_2D); + + GL46.glTextureStorage2D(buffer, 1, format.getGlFormat(), width, height); + accumulate[i] = buffer; + } + + GL46.glNamedFramebufferTexture(mainFbo, GL32.GL_COLOR_ATTACHMENT0, depthBounds, 0); + + for (int i = 0; i < accumulateCnt; i++) + { + GL46.glNamedFramebufferTexture(mainFbo, GL32.GL_COLOR_ATTACHMENT1 + i, accumulate[i], 0); + accumulateDrawBuffers[i] = GL32.GL_COLOR_ATTACHMENT1 + i; + } + } + else + { + depthBounds = GL32.glGenTextures(); + + GlTextureUnit.T0.makeActive(); + RenderSystem.bindTexture(0); + + GL32.glBindTexture(GL32.GL_TEXTURE_2D, depthBounds); + GL32.glTexImage2D(GL32.GL_TEXTURE_2D, 0, GL32.GL_RG32F, width, height, 0, GL46.GL_RGBA, GL46.GL_BYTE, 0); + + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_MIN_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_MAG_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_WRAP_S, GL32.GL_CLAMP_TO_EDGE); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_WRAP_T, GL32.GL_CLAMP_TO_EDGE); + + for (int i = 0; i < accumulateCnt; i++) + { + var drawBuffer = programDrawBuffers[i]; + var format = InternalTextureFormat.RGBA16F; + + var maybeOverride = Utils.findFirst(overrides, e -> e.drawBuffer() == drawBuffer); + + if (maybeOverride.isPresent()) + { + format = maybeOverride.get().format(); + } + + int buffer = GL32.glGenTextures(); + + GL32.glBindTexture(GL32.GL_TEXTURE_2D, buffer); + GL32.glTexImage2D(GL32.GL_TEXTURE_2D, 0, format.getGlFormat(), width, height, 0, format.getPixelFormat().getGlFormat(), GL32.GL_UNSIGNED_BYTE, 0); + + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_MIN_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_MAG_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_WRAP_S, GL32.GL_CLAMP_TO_EDGE); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D, GL32.GL_TEXTURE_WRAP_T, GL32.GL_CLAMP_TO_EDGE); + + accumulate[i] = buffer; + } + + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, mainFbo); + + GL46.glFramebufferTexture(GL32.GL_FRAMEBUFFER, GL32.GL_COLOR_ATTACHMENT0, depthBounds, 0); + + for (int i = 0; i < accumulateCnt; i++) + { + GL46.glFramebufferTexture(GL32.GL_FRAMEBUFFER, GL32.GL_COLOR_ATTACHMENT1 + i, accumulate[i], 0); + accumulateDrawBuffers[i] = GL32.GL_COLOR_ATTACHMENT1 + i; + } + } + } + + private void resizeCoeffsFBO(int width, int height) + { + var coeffRanks = config.coeffRanks(); + var coeffCnt = coeffRanks.length; + + if (coeffCnt == 0) // Only opaques + { + return; + } + + if (GlCompat.SUPPORTS_DSA) + { + coeffsFbo = GL46.glCreateFramebuffers(); + coefficients = new int[coeffCnt]; + + int coeffsSum = 0; + + for (int i = 0; i < coeffCnt; i++) + { + int rank = coeffRanks[i]; + int buffer = GL46.glCreateTextures(GL46.GL_TEXTURE_2D_ARRAY); + int depth = MoreMath.ceilingDiv(1 << (rank + 1), 4); + + GL46.glTextureStorage3D(buffer, 1, GL32.GL_RGBA16F, width, height, depth); + coefficients[i] = buffer; + coeffsSum += depth; + } + + renderTransmittanceDrawBuffers = new int[coeffsSum]; + int transmittanceIdx = 0; + + for (int i = 0; i < coeffCnt; i++) + { + int rank = coeffRanks[i]; + int depth = MoreMath.ceilingDiv(1 << (rank + 1), 4); + + for (int j = 0; j < depth; j++) + { + GL46.glNamedFramebufferTextureLayer(coeffsFbo, GL32.GL_COLOR_ATTACHMENT0 + transmittanceIdx, coefficients[i], 0, j); + renderTransmittanceDrawBuffers[transmittanceIdx] = GL32.GL_COLOR_ATTACHMENT0 + transmittanceIdx; + transmittanceIdx += 1; + } + } + } + else + { + coeffsFbo = GL46.glGenFramebuffers(); + + coefficients = new int[coeffCnt]; + + int coeffsSum = 0; + + for (int i = 0; i < coeffCnt; i++) + { + int rank = coeffRanks[i]; + int buffer = GL32.glGenTextures(); + int depth = MoreMath.ceilingDiv(1 << (rank + 1), 4); + + GL32.glBindTexture(GL32.GL_TEXTURE_2D_ARRAY, buffer); + GL32.glTexImage3D(GL32.GL_TEXTURE_2D_ARRAY, 0, GL32.GL_RGBA16F, width, height, depth, 0, GL46.GL_RGBA, GL46.GL_BYTE, 0); + + GL32.glTexParameteri(GL32.GL_TEXTURE_2D_ARRAY, GL32.GL_TEXTURE_MIN_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D_ARRAY, GL32.GL_TEXTURE_MAG_FILTER, GL32.GL_NEAREST); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D_ARRAY, GL32.GL_TEXTURE_WRAP_S, GL32.GL_CLAMP_TO_EDGE); + GL32.glTexParameteri(GL32.GL_TEXTURE_2D_ARRAY, GL32.GL_TEXTURE_WRAP_T, GL32.GL_CLAMP_TO_EDGE); + + coefficients[i] = buffer; + coeffsSum += depth; + } + + GlStateManager._glBindFramebuffer(GL32.GL_FRAMEBUFFER, coeffsFbo); + + renderTransmittanceDrawBuffers = new int[coeffsSum]; + int transmittanceIdx = 0; + + for (int i = 0; i < coeffCnt; i++) + { + int rank = coeffRanks[i]; + int depth = MoreMath.ceilingDiv(1 << (rank + 1), 4); + + for (int j = 0; j < depth; j++) + { + GL46.glFramebufferTextureLayer(GL32.GL_FRAMEBUFFER, GL32.GL_COLOR_ATTACHMENT0 + transmittanceIdx, coefficients[i], 0, j); + renderTransmittanceDrawBuffers[transmittanceIdx] = GL32.GL_COLOR_ATTACHMENT0 + transmittanceIdx; + transmittanceIdx += 1; + } + } + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlRenderingPhase.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlRenderingPhase.java new file mode 100644 index 000000000..985f56913 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlRenderingPhase.java @@ -0,0 +1,24 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +public enum ClrwlRenderingPhase +{ + SOLID, + TRANSLUCENT, + OIT_DEPTH_RANGE, + OIT_COEFFICIENTS, + OIT_ACCUMULATE, + OIT_COMPOSITE, + CRUMBLING, + STAGING_BUFFER_FLUSH, + INDIRECT_DEPTH_PYRAMID, + INDIRECT_CULL, + INDIRECT_CULL_APPLY, + INDIRECT_CULL_RESET, + INDIRECT_CULL_TRANSFORM; + + public int getValue() + { + // ordinal is shifted to prevent collision with Iris or other mod + return 110800 + ordinal(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertex.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertex.java new file mode 100644 index 000000000..6cbab1895 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertex.java @@ -0,0 +1,38 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import dev.engine_room.flywheel.api.layout.FloatRepr; +import dev.engine_room.flywheel.api.layout.Layout; +import dev.engine_room.flywheel.api.layout.LayoutBuilder; +import dev.engine_room.flywheel.backend.LayoutAttributes; +import dev.engine_room.flywheel.backend.gl.array.VertexAttribute; +import net.minecraft.resources.ResourceLocation; + +import java.util.List; + +public final class ClrwlVertex { + public static final Layout LAYOUT = LayoutBuilder.create() + .vector("position", FloatRepr.FLOAT, 3) + .vector("color", FloatRepr.NORMALIZED_UNSIGNED_BYTE, 4) + .vector("tex", FloatRepr.FLOAT, 2) + .vector("light", FloatRepr.UNSIGNED_SHORT, 2) + .vector("normal", FloatRepr.NORMALIZED_BYTE, 4) + .vector("entity", FloatRepr.SHORT, 2) + .vector("midTexCoord", FloatRepr.FLOAT, 2) + .vector("tangent", FloatRepr.NORMALIZED_BYTE, 4) + .vector("midBlock", FloatRepr.BYTE, 4) + .vector("overlay", FloatRepr.SHORT, 2) + .build(); + + public static final List ATTRIBUTES = LayoutAttributes.attributes(LAYOUT); + public static final int STRIDE = LAYOUT.byteSize(); + + public static final ResourceLocation LAYOUT_SHADER = Colorwheel.rl("internal/vertex_input.vert"); + + private ClrwlVertex() { + } + + public static ClrwlVertexView createVertexView() { + return new ClrwlVertexView(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertexView.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertexView.java new file mode 100644 index 000000000..5eed2ce1e --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ClrwlVertexView.java @@ -0,0 +1,293 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.lib.math.DataPacker; +import dev.engine_room.flywheel.lib.vertex.AbstractVertexView; +import org.lwjgl.system.MemoryUtil; + +public class ClrwlVertexView extends AbstractVertexView +{ + public static final long STRIDE = 56; + + private boolean isPreviousWriteExtended = false; + + public void flagWriteAsExtended() + { + isPreviousWriteExtended = true; + } + + public boolean consumeExtendedWriteFlag() + { + var state = isPreviousWriteExtended; + isPreviousWriteExtended = false; + return state; + } + + @Override + public long stride() { + return STRIDE; + } + + @Override + public float x(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE); + } + + @Override + public float y(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 4); + } + + @Override + public float z(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 8); + } + + @Override + public float r(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 12)); + } + + @Override + public float g(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 13)); + } + + @Override + public float b(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 14)); + } + + @Override + public float a(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 15)); + } + + @Override + public float u(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 16); + } + + @Override + public float v(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 20); + } + + @Override + public int light(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 24); + } + + @Override + public float normalX(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 28)); + } + + @Override + public float normalY(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 29)); + } + + @Override + public float normalZ(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 30)); + } + + public short entityX(int index) { + return MemoryUtil.memGetShort(ptr + index * STRIDE + 32); + } + + public short entityY(int index) { + return MemoryUtil.memGetShort(ptr + index * STRIDE + 34); + } + + public int packedEntity(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 32); + } + + public float midU(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 38); + } + + public float midV(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 40); + } + + public float tangentX(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 44)); + } + + public float tangentY(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 45)); + } + + public float tangentZ(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 46)); + } + + public float tangentW(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 47)); + } + + public int packedTangent(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 44); + } + + public byte midBlockX(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 48); + } + + public byte midBlockY(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 49); + } + + public byte midBlockZ(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 50); + } + + public byte midBlockW(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 51); + } + + public int packedMidBlock(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 48); + } + + // Overlay is added at the end to make a single memcpy with IrisTerrainVertexView + @Override + public int overlay(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 52); + } + + + @Override + public void x(int index, float x) { + MemoryUtil.memPutFloat(ptr + index * STRIDE, x); + } + + @Override + public void y(int index, float y) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 4, y); + } + + @Override + public void z(int index, float z) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 8, z); + } + + @Override + public void r(int index, float r) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 12, DataPacker.packNormU8(r)); + } + + @Override + public void g(int index, float g) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 13, DataPacker.packNormU8(g)); + } + + @Override + public void b(int index, float b) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 14, DataPacker.packNormU8(b)); + } + + @Override + public void a(int index, float a) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 15, DataPacker.packNormU8(a)); + } + + @Override + public void u(int index, float u) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 16, u); + } + + @Override + public void v(int index, float v) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 20, v); + } + + @Override + public void light(int index, int light) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 24, light); + } + + @Override + public void normalX(int index, float normalX) + { + MemoryUtil.memPutByte(ptr + index * STRIDE + 28, DataPacker.packNormI8(normalX)); + } + + @Override + public void normalY(int index, float normalY) + { + MemoryUtil.memPutByte(ptr + index * STRIDE + 29, DataPacker.packNormI8(normalY)); + } + + @Override + public void normalZ(int index, float normalZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 30, DataPacker.packNormI8(normalZ)); + } + + public void entityX(int index, short entityX) { + MemoryUtil.memPutShort(ptr + index * STRIDE + 32, entityX); + } + + public void entityY(int index, short entityY) { + MemoryUtil.memPutShort(ptr + index * STRIDE + 34, entityY); + } + + public void packedEntity(int index, int packed) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 32, packed); + } + + public void midU(int index, float midU) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 36, midU); + } + + public void midV(int index, float midV) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 40, midV); + } + + public void tangentX(int index, float tangentX) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 44, DataPacker.packNormI8(tangentX)); + } + + public void tangentY(int index, float tangentY) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 45, DataPacker.packNormI8(tangentY)); + } + + public void tangentZ(int index, float tangentZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 46, DataPacker.packNormI8(tangentZ)); + } + + public void tangentW(int index, float tangentW) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 47, DataPacker.packNormI8(tangentW)); + } + + public void packedTangent(int index, int packed) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 44, packed); + } + + public void midBlockX(int index, byte midX) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 48, midX); + } + + public void midBlockY(int index, byte midY) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 49, midY); + } + + public void midBlockZ(int index, byte midZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 50, midZ); + } + + public void midBlockW(int index, byte midW) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 51, midW); + } + + public void packedMidBlock(int index, int packed) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 48, packed); + } + + @Override + public void overlay(int index, int overlay) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 52, overlay); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/IrisTerrainVertexView.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/IrisTerrainVertexView.java new file mode 100644 index 000000000..f7a52683d --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/IrisTerrainVertexView.java @@ -0,0 +1,308 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.vertex.MutableVertexList; +import dev.engine_room.flywheel.lib.math.DataPacker; +import dev.engine_room.flywheel.lib.vertex.AbstractVertexView; +import dev.engine_room.flywheel.lib.vertex.DefaultVertexList; +import org.lwjgl.system.MemoryUtil; + +public class IrisTerrainVertexView extends AbstractVertexView implements DefaultVertexList +{ + public static final long STRIDE = 12 // Position + + 4 // Color + + 8 // UV0 + + 4 // UV1 + + 4 // Normal + Padding + + 4 // mc_Entity + + 8 // mc_midTexCoord + + 4 // at_tangent + + 4 // at_midBlock + ; + + @Override + public long stride() + { + return STRIDE; + } + + @Override + public void write(MutableVertexList dst, int srcIndex, int dstIndex) + { + if (dst instanceof ClrwlVertexView clrwlView) + { + MemoryUtil.memCopy(ptr + srcIndex * STRIDE, clrwlView.ptr() + dstIndex * ClrwlVertexView.STRIDE, STRIDE); + dst.overlay(dstIndex, overlay(srcIndex)); + + clrwlView.flagWriteAsExtended(); + } + else + { + super.write(dst, srcIndex, dstIndex); + } + } + + @Override + public void write(MutableVertexList dst, int srcStartIndex, int dstStartIndex, int vertexCount) + { + if (dst instanceof ClrwlVertexView clrwlView) + { + for (int i = 0; i < vertexCount; i++) + { + var srcIndex = srcStartIndex + i; + var dstIndex = dstStartIndex + i; + + MemoryUtil.memCopy(ptr + srcIndex * STRIDE, clrwlView.ptr() + dstIndex * ClrwlVertexView.STRIDE, STRIDE); + dst.overlay(dstIndex, overlay(i)); + } + + clrwlView.flagWriteAsExtended(); + } + else + { + super.write(dst, srcStartIndex, dstStartIndex, vertexCount); + } + } + + + @Override + public float x(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE); + } + + @Override + public float y(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 4); + } + + @Override + public float z(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 8); + } + + @Override + public float r(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 12)); + } + + @Override + public float g(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 13)); + } + + @Override + public float b(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 14)); + } + + @Override + public float a(int index) { + return DataPacker.unpackNormU8(MemoryUtil.memGetByte(ptr + index * STRIDE + 15)); + } + + @Override + public float u(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 16); + } + + @Override + public float v(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 20); + } + + @Override + public int light(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 24); + } + + @Override + public float normalX(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 28)); + } + + @Override + public float normalY(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 29)); + } + + @Override + public float normalZ(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 30)); + } + + public short entityX(int index) { + return MemoryUtil.memGetShort(ptr + index * STRIDE + 32); + } + + public short entityY(int index) { + return MemoryUtil.memGetShort(ptr + index * STRIDE + 34); + } + + public float midU(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 38); + } + + public float midV(int index) { + return MemoryUtil.memGetFloat(ptr + index * STRIDE + 40); + } + + public float tangentX(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 44)); + } + + public float tangentY(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 45)); + } + + public float tangentZ(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 46)); + } + + public float tangentW(int index) { + return DataPacker.unpackNormI8(MemoryUtil.memGetByte(ptr + index * STRIDE + 47)); + } + + public int packedTangent(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 44); + } + + public byte midBlockX(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 48); + } + + public byte midBlockY(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 49); + } + + public byte midBlockZ(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 50); + } + + public byte midBlockW(int index) { + return MemoryUtil.memGetByte(ptr + index * STRIDE + 51); + } + + public int packedMidBlock(int index) { + return MemoryUtil.memGetInt(ptr + index * STRIDE + 48); + } + + @Override + public void x(int index, float x) { + MemoryUtil.memPutFloat(ptr + index * STRIDE, x); + } + + @Override + public void y(int index, float y) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 4, y); + } + + @Override + public void z(int index, float z) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 8, z); + } + + @Override + public void r(int index, float r) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 12, DataPacker.packNormU8(r)); + } + + @Override + public void g(int index, float g) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 13, DataPacker.packNormU8(g)); + } + + @Override + public void b(int index, float b) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 14, DataPacker.packNormU8(b)); + } + + @Override + public void a(int index, float a) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 15, DataPacker.packNormU8(a)); + } + + @Override + public void u(int index, float u) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 16, u); + } + + @Override + public void v(int index, float v) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 20, v); + } + + @Override + public void light(int index, int light) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 24, light); + } + + @Override + public void normalX(int index, float normalX) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 28, DataPacker.packNormI8(normalX)); + } + + @Override + public void normalY(int index, float normalY) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 29, DataPacker.packNormI8(normalY)); + } + + @Override + public void normalZ(int index, float normalZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 30, DataPacker.packNormI8(normalZ)); + } + + public void entityX(int index, short entityX) { + MemoryUtil.memPutShort(ptr + index * STRIDE + 32, entityX); + } + + public void entityY(int index, short entityY) { + MemoryUtil.memPutShort(ptr + index * STRIDE + 34, entityY); + } + + public void midU(int index, float midU) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 36, midU); + } + + public void midV(int index, float midV) { + MemoryUtil.memPutFloat(ptr + index * STRIDE + 40, midV); + } + + public void tangentX(int index, float tangentX) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 44, DataPacker.packNormI8(tangentX)); + } + + public void tangentY(int index, float tangentY) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 45, DataPacker.packNormI8(tangentY)); + } + + public void tangentZ(int index, float tangentZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 46, DataPacker.packNormI8(tangentZ)); + } + + public void tangentW(int index, float tangentW) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 47, DataPacker.packNormI8(tangentW)); + } + + public void packedTangent(int index, int packed) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 44, packed); + } + + public void midBlockX(int index, byte midX) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 48, midX); + } + + public void midBlockY(int index, byte midY) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 49, midY); + } + + public void midBlockZ(int index, byte midZ) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 50, midZ); + } + + public void midBlockW(int index, byte midW) { + MemoryUtil.memPutByte(ptr + index * STRIDE + 51, midW); + } + + public void packedMidBlock(int index, int packed) { + MemoryUtil.memPutInt(ptr + index * STRIDE + 48, packed); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ProgramGroupDepthInfo.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ProgramGroupDepthInfo.java new file mode 100644 index 000000000..89552f62c --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ProgramGroupDepthInfo.java @@ -0,0 +1,24 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; + +public record ProgramGroupDepthInfo(int textureId, int width, int height) +{ + public static ProgramGroupDepthInfo of(IrisRenderingPipeline irisPipeline, ClrwlProgramGroup programGroup) + { + return switch (programGroup) + { + case GBUFFERS -> + { + var targets = irisPipeline.getRenderTargets(); + yield new ProgramGroupDepthInfo(targets.getDepthTexture(), targets.getCurrentWidth(), targets.getCurrentHeight()); + } + case SHADOW -> + { + var targets = irisPipeline.getShadowRenderTargets(); + yield new ProgramGroupDepthInfo(targets.getDepthTexture().getTextureId(), targets.getResolution(), targets.getResolution()); + } + }; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowCulling.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowCulling.java new file mode 100644 index 000000000..93944d5f7 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowCulling.java @@ -0,0 +1,144 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.properties.ShadowCullState; +import net.irisshaders.iris.uniforms.CelestialUniforms; +import net.minecraft.client.Minecraft; +import org.joml.Math; +import org.joml.Vector3f; +import org.joml.Vector4f; + +// Based on Iris' ShadowRenderer +// https://github.com/IrisShaders/Iris/blob/328655a88202e3bfcf69f36d616cbc555ec53875/common/src/main/java/net/irisshaders/iris/shadows/ShadowRenderer.java#L295 + +public class ShadowCulling +{ + private final ShadowCullState cullState; + private final float shadowDist; + private final float voxelDist; + private final float distMultiplier; + private final boolean packHasVoxelization; + private final float sunPathRotation; + + private boolean shouldRenderShadow = true; + private float reversedCullDist = 0.0f; + private float cullDist = 0.0f; + private final Vector3f shadowLightVectorFromOrigin = new Vector3f(0.0f); + + public ShadowCulling(ProgramSet programSet) + { + var directives = programSet.getPackDirectives(); + var clrwlDirectives = programSet.getClrwlPrograms().getClrwlDirectives(); + var shadowDirectives = directives.getShadowDirectives(); + + cullState = clrwlDirectives.getShadowCullState(); + shadowDist = shadowDirectives.getDistance(); + voxelDist = shadowDirectives.getVoxelDistance(); + packHasVoxelization = packHasVoxelization(programSet); + sunPathRotation = directives.getSunPathRotation(); + + var multiplier = shadowDirectives.getDistanceRenderMul(); + + if (cullState == ShadowCullState.REVERSED && multiplier < 0.0f) + { + multiplier = 1.0f; + } + + distMultiplier = multiplier; + } + + public void refresh() + { + var renderDistance = Minecraft.getInstance().options.getEffectiveRenderDistance() * 16; + + shouldRenderShadow = true; + + Vector4f shadowLightPosition = new CelestialUniforms(sunPathRotation).getShadowLightPositionInWorldSpace(); + shadowLightVectorFromOrigin.set(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z()); + + if ((cullState == ShadowCullState.DEFAULT && packHasVoxelization) || cullState == ShadowCullState.DISTANCE) + { + float distance = shadowDist * distMultiplier; + + if (distance == 0.0f) + { + shouldRenderShadow = false; + reversedCullDist = 0.0f; + cullDist = 0.0f; + } + else + { + reversedCullDist = 0.0f; + cullDist = Math.min(distance, renderDistance); + } + } + else if (cullState == ShadowCullState.REVERSED) + { + reversedCullDist = voxelDist * distMultiplier; + cullDist = Math.min(shadowDist * distMultiplier, renderDistance); + } + else // ADVANCED + { + var distance = shadowDist * distMultiplier; + + if (distance < 0.0f) + { + distance = IrisVideoSettings.shadowDistance * 16; + } + + reversedCullDist = 0.0f; + cullDist = Math.min(distance, renderDistance); + } + } + + public boolean shouldRenderShadow() + { + return shouldRenderShadow; + } + + public float getReversedCullDist() + { + return reversedCullDist; + } + + public float getCullDist() + { + return cullDist; + } + + public Vector3f getShadowLightVectorFromOrigin() + { + return shadowLightVectorFromOrigin; + } + + private static boolean packHasVoxelization(ProgramSet programSet) + { + return programSet.get(ProgramId.Shadow) + .map(src -> src.getSource(ShaderType.GEOM).isPresent()) + .orElse(false); + } + + public static boolean useFrustumCulling(ProgramSet programSet, ShadowCullState cullState) + { + switch (cullState) + { + case DEFAULT -> + { + return !packHasVoxelization(programSet); + } + + case DISTANCE -> + { + return false; + } + + default -> + { + return true; + } + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderContext.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderContext.java new file mode 100644 index 000000000..495d6104f --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderContext.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +//? if <1.21 +import com.mojang.blaze3d.vertex.PoseStack; +import dev.engine_room.flywheel.api.backend.RenderContext; +import net.minecraft.client.Camera; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.RenderBuffers; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +public record ShadowRenderContext(LevelRenderer renderer, ClientLevel level, RenderBuffers buffers, + /*? if >=1.21 {*/ /*Matrix4fc modelView, *//*?} else {*/ PoseStack stack, /*?}*/ Matrix4fc projection, Matrix4fc viewProjection, + Matrix4fc playerModelView, Matrix4fc playerProjection, Matrix4fc playerViewProjection, + Camera camera, float camX, float camY, float camZ, + float partialTick, ShadowRenderingPhase phase) implements RenderContext +{ + public static ShadowRenderContext create(LevelRenderer renderer, ClientLevel level, RenderBuffers buffers, + /*? if >=1.21 {*/ /*Matrix4fc modelView, *//*?} else {*/ PoseStack stack, /*?}*/ Matrix4f projection, + Matrix4fc playerModelView, Matrix4fc playerProjection, + Camera camera, float camX, float camY, float camZ, + float partialTick, ShadowRenderingPhase phase) + { + Matrix4f viewProjection = new Matrix4f(projection); + viewProjection.mul(/*? if >=1.21 {*/ /*modelView *//*?} else {*/ stack.last().pose() /*?}*/); + Matrix4f playerViewProjection = new Matrix4f(playerProjection); + playerViewProjection.mul(playerModelView); + + return new ShadowRenderContext(renderer, level, buffers, + /*? if >=1.21 {*/ /*modelView *//*?} else {*/ stack /*?}*/, projection, viewProjection, + playerModelView, playerProjection, playerViewProjection, + camera, camX, camY, camZ, partialTick, phase); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderingPhase.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderingPhase.java new file mode 100644 index 000000000..0077b9af6 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowRenderingPhase.java @@ -0,0 +1,7 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +public enum ShadowRenderingPhase +{ + SOLID, + TRANSLUCENT +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowUniforms.java new file mode 100644 index 000000000..47fc8e47f --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/ShadowUniforms.java @@ -0,0 +1,21 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +import dev.engine_room.flywheel.api.backend.RenderContext; + +public class ShadowUniforms +{ + private ShadowUniforms() {} + + public static void update(RenderContext context) + { +// ShadowFrameUniforms.update(context); +// PlayerUniforms.update(context); +// LevelUniforms.update(context); + } + + public static void bindAll() + { +// ShadowFrameUniforms.bind(); +// PlayerUniforms. + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/TranslucentRenderContext.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/TranslucentRenderContext.java new file mode 100644 index 000000000..8f68003d3 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/TranslucentRenderContext.java @@ -0,0 +1,26 @@ +package net.irisshaders.iris.compat.flywheel.engine; + +//? if <1.21 +import com.mojang.blaze3d.vertex.PoseStack; +import dev.engine_room.flywheel.api.backend.RenderContext; +import net.minecraft.client.Camera; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.RenderBuffers; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +public record TranslucentRenderContext(LevelRenderer renderer, ClientLevel level, RenderBuffers buffers, + /*? if >=1.21 {*/ /*Matrix4fc modelView, *//*?} else {*/ PoseStack stack, /*?}*/ Matrix4fc projection, Matrix4fc viewProjection, + Camera camera, float partialTick) implements RenderContext +{ + public static TranslucentRenderContext create(LevelRenderer renderer, ClientLevel level, RenderBuffers buffers, + /*? if >=1.21 {*/ /*Matrix4fc modelView, *//*?} else {*/ PoseStack stack, /*?}*/ Matrix4f projection, + Camera camera, float partialTick) + { + Matrix4f viewProjection = new Matrix4f(projection); + viewProjection.mul(/*? if >=1.21 {*/ /*modelView *//*?} else {*/ stack.last().pose() /*?}*/); + + return new TranslucentRenderContext(renderer, level, buffers, /*? if >=1.21 {*/ /*modelView *//*?} else {*/ stack /*?}*/, projection, viewProjection, camera, partialTick); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EmbeddedEnvironment.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EmbeddedEnvironment.java new file mode 100644 index 000000000..65e2ad0e2 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EmbeddedEnvironment.java @@ -0,0 +1,136 @@ +package net.irisshaders.iris.compat.flywheel.engine.embed; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlEngine; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstanceVisual; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.instance.Instancer; +import dev.engine_room.flywheel.api.instance.InstancerProvider; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.api.visualization.VisualEmbedding; +import dev.engine_room.flywheel.backend.compile.ContextShader; +import dev.engine_room.flywheel.backend.engine.embed.EmbeddingUniforms; +import dev.engine_room.flywheel.backend.engine.embed.Environment; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import dev.engine_room.flywheel.lib.util.ExtraMemoryOps; +import net.minecraft.core.Vec3i; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3f; +import org.joml.Matrix3fc; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +public class EmbeddedEnvironment implements VisualEmbedding, Environment +{ + private final ClrwlEngine engine; + private final ClrwlInstanceVisual visual; + private final Vec3i renderOrigin; + @Nullable + private final EmbeddedEnvironment parent; + private final InstancerProvider instancerProvider; + + private final Matrix4f pose = new Matrix4f(); + private final Matrix3f normal = new Matrix3f(); + private final Matrix4f poseComposed = new Matrix4f(); + private final Matrix3f normalComposed = new Matrix3f(); + + public int matrixIndex = 0; + + private boolean deleted = false; + + public EmbeddedEnvironment(ClrwlEngine engine, ClrwlInstanceVisual visual, Vec3i renderOrigin, @Nullable EmbeddedEnvironment parent) + { + this.engine = engine; + this.visual = visual; + this.renderOrigin = renderOrigin; + this.parent = parent; + + instancerProvider = new InstancerProvider() { + @Override + public Instancer instancer(InstanceType type, Model model, int bias) { + // Kinda cursed usage of anonymous classes here, but it does the job. + return engine.instancer(visual, EmbeddedEnvironment.this, type, model, bias); + } + }; + } + + public EmbeddedEnvironment(ClrwlEngine engine, ClrwlInstanceVisual visual, Vec3i renderOrigin) + { + this(engine, visual, renderOrigin, null); + } + + @Override + public void transforms(Matrix4fc pose, Matrix3fc normal) + { + this.pose.set(pose); + this.normal.set(normal); + } + + @Override + public InstancerProvider instancerProvider() { + return instancerProvider; + } + + @Override + public Vec3i renderOrigin() { + return renderOrigin; + } + + @Override + public VisualEmbedding createEmbedding(Vec3i renderOrigin) { + var out = new EmbeddedEnvironment(engine, visual, renderOrigin, this); + engine.environmentStorage() + .track(out); + return out; + } + + @Override + public ContextShader contextShader() { + return ContextShader.EMBEDDED; + } + + @Override + public void setupDraw(GlProgram program) + { + program.setMat4(EmbeddingUniforms.MODEL_MATRIX, poseComposed); + program.setMat3(EmbeddingUniforms.NORMAL_MATRIX, normalComposed); + } + + @Override + public int matrixIndex() { + return matrixIndex; + } + + public void flush(long ptr) { + poseComposed.identity(); + normalComposed.identity(); + + composeMatrices(poseComposed, normalComposed); + + ExtraMemoryOps.putMatrix4f(ptr, poseComposed); + ExtraMemoryOps.putMatrix3fPadded(ptr + 16 * Float.BYTES, normalComposed); + } + + private void composeMatrices(Matrix4f pose, Matrix3f normal) { + if (parent != null) { + parent.composeMatrices(pose, normal); + pose.mul(this.pose); + normal.mul(this.normal); + } else { + pose.set(this.pose); + normal.set(this.normal); + } + } + + public boolean isDeleted() { + return deleted; + } + + /** + * Called by visuals + */ + @Override + public void delete() { + deleted = true; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EnvironmentStorage.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EnvironmentStorage.java new file mode 100644 index 000000000..b1138c635 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/embed/EnvironmentStorage.java @@ -0,0 +1,54 @@ +package net.irisshaders.iris.compat.flywheel.engine.embed; + +import dev.engine_room.flywheel.backend.engine.CpuArena; +import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet; +import it.unimi.dsi.fastutil.objects.ReferenceSet; + +public class EnvironmentStorage +{ + public static final int MATRIX_SIZE_BYTES = (16 + 12) * Float.BYTES; + + protected final Object lock = new Object(); + + protected final ReferenceSet environments = new ReferenceLinkedOpenHashSet<>(); + + // Note than the arena starts indexing at zero, but we reserve zero for the identity matrix. + // Any time an ID from the arena is written we want to add one to it. + public final CpuArena arena = new CpuArena(MATRIX_SIZE_BYTES, 32); + + { + // Reserve the identity matrix. Burns a few bytes but oh well. + arena.alloc(); + } + + public void track(EmbeddedEnvironment environment) + { + synchronized (lock) + { + if (environments.add(environment)) + { + environment.matrixIndex = arena.alloc(); + } + } + } + + public void flush() + { + environments.removeIf(embeddedEnvironment -> + { + var deleted = embeddedEnvironment.isDeleted(); + if (deleted && embeddedEnvironment.matrixIndex > 0) { + arena.free(embeddedEnvironment.matrixIndex); + } + return deleted; + }); + for (EmbeddedEnvironment environment : environments) + { + environment.flush(arena.indexToPointer(environment.matrixIndex)); + } + } + + public void delete() { + arena.delete(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFogUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFogUniforms.java new file mode 100644 index 000000000..496d0dd35 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFogUniforms.java @@ -0,0 +1,31 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import com.mojang.blaze3d.shaders.FogShape; +import com.mojang.blaze3d.systems.RenderSystem; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; + +public final class ClrwlFogUniforms extends UniformWriter +{ + private static final int SIZE = 4 * 7; + static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.FOG_INDEX, SIZE); + + public static void update() + { + long ptr = BUFFER.ptr(); + + var color = RenderSystem.getShaderFogColor(); + + ptr = writeFloat(ptr, color[0]); + ptr = writeFloat(ptr, color[1]); + ptr = writeFloat(ptr, color[2]); + ptr = writeFloat(ptr, color[3]); + ptr = writeFloat(ptr, RenderSystem.getShaderFogStart()); + ptr = writeFloat(ptr, RenderSystem.getShaderFogEnd()); + + var fogShape = RenderSystem.getShaderFogShape(); + // Shouldn't ever be null, but we've seen crashes here. + ptr = writeInt(ptr, (fogShape == null ? FogShape.SPHERE : fogShape).getIndex()); + + BUFFER.markDirty(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFrameUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFrameUniforms.java new file mode 100644 index 000000000..c920af7bd --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlFrameUniforms.java @@ -0,0 +1,119 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.visualization.VisualizationManager; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import net.minecraft.client.Camera; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Vec3i; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector2f; +import org.joml.Vector3f; + +public final class ClrwlFrameUniforms extends UniformWriter +{ + private static final int SIZE = 5 * 16 + 2 * 8 // Camera + + 4 * 4; // Remaining + + public static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.FRAME_INDEX, SIZE); + + private static final Vector3f CAMERA_POS = new Vector3f(); + private static final Vector3f CAMERA_POS_PREV = new Vector3f(); + private static final Vector3f CAMERA_LOOK = new Vector3f(); + private static final Vector3f CAMERA_LOOK_PREV = new Vector3f(); + private static final Vector2f CAMERA_ROT = new Vector2f(); + private static final Vector2f CAMERA_ROT_PREV = new Vector2f(); + + private static boolean firstWrite = true; + + private static int debugMode = DebugMode.OFF.ordinal(); + + private ClrwlFrameUniforms() { + } + + public static void debugMode(DebugMode mode) { + debugMode = mode.ordinal(); + } + + public static void update(RenderContext context) + { + long ptr = BUFFER.ptr(); + setPrev(); + + Vec3i renderOrigin = VisualizationManager.getOrThrow(context.level()) + .renderOrigin(); + var camera = context.camera(); + Vec3 cameraPos = camera.getPosition(); + var camX = (float) (cameraPos.x - renderOrigin.getX()); + var camY = (float) (cameraPos.y - renderOrigin.getY()); + var camZ = (float) (cameraPos.z - renderOrigin.getZ()); + + CAMERA_POS.set(camX, camY, camZ); + CAMERA_LOOK.set(camera.getLookVector()); + CAMERA_ROT.set(camera.getXRot(), camera.getYRot()); + + if (firstWrite) + { + setPrev(); + } + + ptr = writeRenderOrigin(ptr, renderOrigin); + + ptr = writeCamera(ptr); + + ptr = writeCameraIn(ptr, camera); + + ptr = writeInt(ptr, debugMode); + + // OIT noise factor + ptr = writeFloat(ptr, 0.07f); + + firstWrite = false; + BUFFER.markDirty(); + } + + private static long writeRenderOrigin(long ptr, Vec3i renderOrigin) + { + ptr = writeIVec3(ptr, renderOrigin.getX(), renderOrigin.getY(), renderOrigin.getZ()); + return ptr; + } + + private static void setPrev() + { + CAMERA_POS_PREV.set(CAMERA_POS); + CAMERA_LOOK_PREV.set(CAMERA_LOOK); + CAMERA_ROT_PREV.set(CAMERA_ROT); + } + + private static long writeCamera(long ptr) + { + ptr = writeVec3(ptr, CAMERA_POS.x, CAMERA_POS.y, CAMERA_POS.z); + ptr = writeVec3(ptr, CAMERA_POS_PREV.x, CAMERA_POS_PREV.y, CAMERA_POS_PREV.z); + ptr = writeVec3(ptr, CAMERA_LOOK.x, CAMERA_LOOK.y, CAMERA_LOOK.z); + ptr = writeVec3(ptr, CAMERA_LOOK_PREV.x, CAMERA_LOOK_PREV.y, CAMERA_LOOK_PREV.z); + ptr = writeVec2(ptr, CAMERA_ROT.x, CAMERA_ROT.y); + ptr = writeVec2(ptr, CAMERA_ROT_PREV.x, CAMERA_ROT_PREV.y); + return ptr; + } + + private static long writeCameraIn(long ptr, Camera camera) + { + if (!camera.isInitialized()) + { + ptr = writeInt(ptr, 0); + ptr = writeInt(ptr, 0); + return ptr; + } + + Level level = camera.getEntity().level(); + BlockPos blockPos = camera.getBlockPosition(); + Vec3 cameraPos = camera.getPosition(); + return writeInFluidAndBlock(ptr, level, blockPos, cameraPos); + } + + public static boolean debugOn() + { + return debugMode != DebugMode.OFF.ordinal(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlGbuffersPassUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlGbuffersPassUniforms.java new file mode 100644 index 000000000..2e214f141 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlGbuffersPassUniforms.java @@ -0,0 +1,294 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlDepthPyramid; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.visualization.VisualizationManager; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import dev.engine_room.flywheel.backend.mixin.LevelRendererAccessor; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.core.Vec3i; +import net.minecraft.world.phys.Vec3; +import org.joml.Math; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.lwjgl.system.MemoryUtil; + +public final class ClrwlGbuffersPassUniforms extends UniformWriter +{ + private static final int SIZE = 96 // Frustum + + 32 // Cull + + 64 * 9 // View + Projection + + 48 // Normal + + 6 * 8; // Remaining + + public static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.PASS_INDEX, SIZE); + + private static final Matrix4f VIEW = new Matrix4f(); + private static final Matrix4f VIEW_INVERSE = new Matrix4f(); + private static final Matrix4f VIEW_PREV = new Matrix4f(); + private static final Matrix4f PROJECTION = new Matrix4f(); + private static final Matrix4f PROJECTION_INVERSE = new Matrix4f(); + private static final Matrix4f PROJECTION_PREV = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION_INVERSE = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION_PREV = new Matrix4f(); + + private static final Matrix3f NORMAL = new Matrix3f(); + + private static boolean firstWrite = true; + + private static boolean frustumPaused = false; + private static boolean frustumCapture = false; + + private ClrwlGbuffersPassUniforms() { + } + + public static void captureFrustum() + { + frustumPaused = true; + frustumCapture = true; + } + + public static void unpauseFrustum() + { + frustumPaused = false; + } + + public static void update(RenderContext context, ShaderPack pack, NamespacedId dimension) + { + PackDirectives directives = pack.getProgramSet(dimension).getPackDirectives(); + + long ptr = BUFFER.ptr(); + setPrev(); + + Vec3i renderOrigin = VisualizationManager.getOrThrow(context.level()) + .renderOrigin(); + var camera = context.camera(); + Vec3 cameraPos = camera.getPosition(); + var camX = (float) (cameraPos.x - renderOrigin.getX()); + var camY = (float) (cameraPos.y - renderOrigin.getY()); + var camZ = (float) (cameraPos.z - renderOrigin.getZ()); + + VIEW.set(context./*? if >=1.21 {*/ /*modelView() *//*?} else {*/ stack().last().pose() /*?}*/); + VIEW.translate(-camX, -camY, -camZ); + PROJECTION.set(context.projection()); + VIEW_PROJECTION.set(context.viewProjection()); + VIEW_PROJECTION.translate(-camX, -camY, -camZ); + + Matrix4f normal = new Matrix4f(context./*? if >=1.21 {*/ /*modelView() *//*?} else {*/ stack().last().pose() /*?}*/) + .translate(-camX, -camY, -camZ) + .invert() + .transpose(); + normal.get3x3(NORMAL); + + if (firstWrite) + { + setPrev(); + } + + if (firstWrite || !frustumPaused || frustumCapture) + { + writePackedFrustumPlanes(ptr, VIEW_PROJECTION); + frustumCapture = false; + } + + ptr += 96; + + ptr = writeCullData(ptr); + + ptr = writeMatrices(ptr); + + var window = Minecraft.getInstance() + .getWindow(); + ptr = writeVec2(ptr, window.getWidth(), window.getHeight()); + ptr = writeFloat(ptr, (float) window.getWidth() / (float) window.getHeight()); + // default line width: net.minecraft.client.renderer.RenderStateShard.LineStateShard + ptr = writeFloat(ptr, Math.max(2.5F, (float) window.getWidth() / 1920.0F * 2.5F)); + ptr = writeFloat(ptr, Minecraft.getInstance().gameRenderer.getDepthFar()); + + ptr = writeTime(ptr, context); + + firstWrite = false; + BUFFER.markDirty(); + } + + private static void setPrev() + { + VIEW_PREV.set(VIEW); + PROJECTION_PREV.set(PROJECTION); + VIEW_PROJECTION_PREV.set(VIEW_PROJECTION); + } + + private static long writeMatrices(long ptr) + { + ptr = writeMat4(ptr, VIEW); + ptr = writeMat4(ptr, VIEW.invert(VIEW_INVERSE)); + ptr = writeMat4(ptr, VIEW_PREV); + ptr = writeMat4(ptr, PROJECTION); + ptr = writeMat4(ptr, PROJECTION.invert(PROJECTION_INVERSE)); + ptr = writeMat4(ptr, PROJECTION_PREV); + ptr = writeMat4(ptr, VIEW_PROJECTION); + ptr = writeMat4(ptr, VIEW_PROJECTION.invert(VIEW_PROJECTION_INVERSE)); + ptr = writeMat4(ptr, VIEW_PROJECTION_PREV); + ptr = writeMat3(ptr, NORMAL); + return ptr; + } + + private static long writeTime(long ptr, RenderContext context) + { + int ticks = ((LevelRendererAccessor) context.renderer()).flywheel$getTicks(); + float partialTick = context.partialTick(); + float renderTicks = ticks + partialTick; + float renderSeconds = renderTicks / 20f; + float systemSeconds = Util.getMillis() / 1000f; + int systemMillis = (int) (Util.getMillis() % Integer.MAX_VALUE); + + ptr = writeInt(ptr, ticks); + ptr = writeFloat(ptr, partialTick); + ptr = writeFloat(ptr, renderTicks); + ptr = writeFloat(ptr, renderSeconds); + ptr = writeFloat(ptr, systemSeconds); + ptr = writeInt(ptr, systemMillis); + return ptr; + } + + private static long writeCullData(long ptr) + { + var mc = Minecraft.getInstance(); + var mainRenderTarget = mc.getMainRenderTarget(); + + int pyramidWidth = ClrwlDepthPyramid.mip0Size(mainRenderTarget.width); + int pyramidHeight = ClrwlDepthPyramid.mip0Size(mainRenderTarget.height); + int pyramidDepth = ClrwlDepthPyramid.getImageMipLevels(pyramidWidth, pyramidHeight); + + ptr = writeFloat(ptr, GameRenderer.PROJECTION_Z_NEAR); // zNear + ptr = writeFloat(ptr, mc.gameRenderer.getDepthFar()); // zFar + ptr = writeFloat(ptr, PROJECTION.m00()); // P00 + ptr = writeFloat(ptr, PROJECTION.m11()); // P11 + ptr = writeFloat(ptr, pyramidWidth); // pyramidWidth + ptr = writeFloat(ptr, pyramidHeight); // pyramidHeight + ptr = writeInt(ptr, pyramidDepth - 1); // pyramidLevels + ptr = writeInt(ptr, 0); // orthographicProjection + + return ptr; + } + + /** + * Writes the frustum planes of the given projection matrix to the given buffer.

+ * Uses a different format that is friendly towards an optimized instruction-parallel + * implementation of sphere-frustum intersection.

+ * The format is as follows:

+ * {@code vec4(nxX, pxX, nyX, pyX)}
+ * {@code vec4(nxY, pxY, nyY, pyY)}
+ * {@code vec4(nxZ, pxZ, nyZ, pyZ)}
+ * {@code vec4(nxW, pxW, nyW, pyW)}
+ * {@code vec2(nzX, pzX)}
+ * {@code vec2(nzY, pzY)}
+ * {@code vec2(nzZ, pzZ)}
+ * {@code vec2(nzW, pzW)}
+ *

+ * Writes 96 bytes to the buffer. + * + * @param ptr The buffer to write the planes to. + * @param m The projection matrix to compute the frustum planes for. + */ + private static void writePackedFrustumPlanes(long ptr, Matrix4f m) { + float nxX, nxY, nxZ, nxW; + float pxX, pxY, pxZ, pxW; + float nyX, nyY, nyZ, nyW; + float pyX, pyY, pyZ, pyW; + float nzX, nzY, nzZ, nzW; + float pzX, pzY, pzZ, pzW; + + float invl; + nxX = m.m03() + m.m00(); + nxY = m.m13() + m.m10(); + nxZ = m.m23() + m.m20(); + nxW = m.m33() + m.m30(); + invl = Math.invsqrt(nxX * nxX + nxY * nxY + nxZ * nxZ); + nxX *= invl; + nxY *= invl; + nxZ *= invl; + nxW *= invl; + + pxX = m.m03() - m.m00(); + pxY = m.m13() - m.m10(); + pxZ = m.m23() - m.m20(); + pxW = m.m33() - m.m30(); + invl = Math.invsqrt(pxX * pxX + pxY * pxY + pxZ * pxZ); + pxX *= invl; + pxY *= invl; + pxZ *= invl; + pxW *= invl; + + nyX = m.m03() + m.m01(); + nyY = m.m13() + m.m11(); + nyZ = m.m23() + m.m21(); + nyW = m.m33() + m.m31(); + invl = Math.invsqrt(nyX * nyX + nyY * nyY + nyZ * nyZ); + nyX *= invl; + nyY *= invl; + nyZ *= invl; + nyW *= invl; + + pyX = m.m03() - m.m01(); + pyY = m.m13() - m.m11(); + pyZ = m.m23() - m.m21(); + pyW = m.m33() - m.m31(); + invl = Math.invsqrt(pyX * pyX + pyY * pyY + pyZ * pyZ); + pyX *= invl; + pyY *= invl; + pyZ *= invl; + pyW *= invl; + + nzX = m.m03() + m.m02(); + nzY = m.m13() + m.m12(); + nzZ = m.m23() + m.m22(); + nzW = m.m33() + m.m32(); + invl = Math.invsqrt(nzX * nzX + nzY * nzY + nzZ * nzZ); + nzX *= invl; + nzY *= invl; + nzZ *= invl; + nzW *= invl; + + pzX = m.m03() - m.m02(); + pzY = m.m13() - m.m12(); + pzZ = m.m23() - m.m22(); + pzW = m.m33() - m.m32(); + invl = Math.invsqrt(pzX * pzX + pzY * pzY + pzZ * pzZ); + pzX *= invl; + pzY *= invl; + pzZ *= invl; + pzW *= invl; + + MemoryUtil.memPutFloat(ptr, nxX); + MemoryUtil.memPutFloat(ptr + 4, pxX); + MemoryUtil.memPutFloat(ptr + 8, nyX); + MemoryUtil.memPutFloat(ptr + 12, pyX); + MemoryUtil.memPutFloat(ptr + 16, nxY); + MemoryUtil.memPutFloat(ptr + 20, pxY); + MemoryUtil.memPutFloat(ptr + 24, nyY); + MemoryUtil.memPutFloat(ptr + 28, pyY); + MemoryUtil.memPutFloat(ptr + 32, nxZ); + MemoryUtil.memPutFloat(ptr + 36, pxZ); + MemoryUtil.memPutFloat(ptr + 40, nyZ); + MemoryUtil.memPutFloat(ptr + 44, pyZ); + MemoryUtil.memPutFloat(ptr + 48, nxW); + MemoryUtil.memPutFloat(ptr + 52, pxW); + MemoryUtil.memPutFloat(ptr + 56, nyW); + MemoryUtil.memPutFloat(ptr + 60, pyW); + MemoryUtil.memPutFloat(ptr + 64, nzX); + MemoryUtil.memPutFloat(ptr + 68, pzX); + MemoryUtil.memPutFloat(ptr + 72, nzY); + MemoryUtil.memPutFloat(ptr + 76, pzY); + MemoryUtil.memPutFloat(ptr + 80, nzZ); + MemoryUtil.memPutFloat(ptr + 84, pzZ); + MemoryUtil.memPutFloat(ptr + 88, nzW); + MemoryUtil.memPutFloat(ptr + 92, pzW); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlLevelUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlLevelUniforms.java new file mode 100644 index 000000000..94edb227f --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlLevelUniforms.java @@ -0,0 +1,80 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.backend.engine.uniform.LevelUniforms; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +public final class ClrwlLevelUniforms extends UniformWriter +{ + private static final int SIZE = 16 * 4 + 4 * 12; + static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.LEVEL_INDEX, SIZE); + + private ClrwlLevelUniforms() + { + } + + public static void update(RenderContext context) + { + long ptr = BUFFER.ptr(); + + ClientLevel level = context.level(); + float partialTick = context.partialTick(); + + Vec3 skyColor = level.getSkyColor(context.camera().getPosition(), partialTick); + Vec3 cloudColor = level.getCloudColor(partialTick); + ptr = writeVec4(ptr, (float) skyColor.x, (float) skyColor.y, (float) skyColor.z, 1f); + ptr = writeVec4(ptr, (float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 1f); + + ptr = writeVec3(ptr, LevelUniforms.LIGHT0_DIRECTION); + ptr = writeVec3(ptr, LevelUniforms.LIGHT1_DIRECTION); + + long dayTime = level.getDayTime(); + long levelDay = dayTime / 24000L; + float timeOfDay = (float) (dayTime - levelDay * 24000L) / 24000f; + ptr = writeInt(ptr, (int) (levelDay % 0x7FFFFFFFL)); + ptr = writeFloat(ptr, timeOfDay); + + ptr = writeInt(ptr, level.dimensionType().hasSkyLight() ? 1 : 0); + + ptr = writeFloat(ptr, level.getSunAngle(partialTick)); + + ptr = writeFloat(ptr, level.getMoonBrightness()); + ptr = writeInt(ptr, level.getMoonPhase()); + + ptr = writeInt(ptr, level.isRaining() ? 1 : 0); + ptr = writeFloat(ptr, level.getRainLevel(partialTick)); + ptr = writeInt(ptr, level.isThundering() ? 1 : 0); + ptr = writeFloat(ptr, level.getThunderLevel(partialTick)); + + ptr = writeFloat(ptr, level.getSkyDarken(partialTick)); + + ptr = writeInt(ptr, level.effects().constantAmbientLight() ? 1 : 0); + + // TODO: use defines for custom dimension ids + int dimensionId; + ResourceKey dimension = level.dimension(); + if (Level.OVERWORLD.equals(dimension)) + { + dimensionId = 0; + } + else if (Level.NETHER.equals(dimension)) + { + dimensionId = 1; + } + else if (Level.END.equals(dimension)) + { + dimensionId = 2; + } + else + { + dimensionId = -1; + } + ptr = writeInt(ptr, dimensionId); + + BUFFER.markDirty(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlOptionsUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlOptionsUniforms.java new file mode 100644 index 000000000..ca28e8cf9 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlOptionsUniforms.java @@ -0,0 +1,31 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import net.minecraft.client.Options; + +public final class ClrwlOptionsUniforms extends UniformWriter +{ + private static final int SIZE = 4 * 14; + static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.OPTIONS_INDEX, SIZE); + + public static void update(Options options) { + long ptr = BUFFER.ptr(); + + ptr = writeFloat(ptr, options.gamma().get().floatValue()); + ptr = writeInt(ptr, options.fov().get()); + ptr = writeFloat(ptr, options.screenEffectScale().get().floatValue()); + ptr = writeFloat(ptr, options.glintSpeed().get().floatValue()); + ptr = writeFloat(ptr, options.glintStrength().get().floatValue()); + ptr = writeInt(ptr, options.biomeBlendRadius().get()); + ptr = writeInt(ptr, options.ambientOcclusion().get() ? 1 : 0); + ptr = writeInt(ptr, options.bobView().get() ? 1 : 0); + ptr = writeInt(ptr, options.highContrast().get() ? 1 : 0); + ptr = writeFloat(ptr, options.textBackgroundOpacity().get().floatValue()); + ptr = writeInt(ptr, options.backgroundForChatOnly().get() ? 1 : 0); + ptr = writeFloat(ptr, options.darknessEffectScale().get().floatValue()); + ptr = writeFloat(ptr, options.damageTiltStrength().get().floatValue()); + ptr = writeInt(ptr, options.hideLightningFlash().get() ? 1 : 0); + + BUFFER.markDirty(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlPlayerUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlPlayerUniforms.java new file mode 100644 index 000000000..ed87b4079 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlPlayerUniforms.java @@ -0,0 +1,130 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.backend.FlwBackendXplat; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import dev.engine_room.flywheel.backend.mixin.AbstractClientPlayerAccessor; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.util.FastColor; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.scores.PlayerTeam; +import org.jetbrains.annotations.Nullable; + +public final class ClrwlPlayerUniforms extends UniformWriter +{ + private static final int SIZE = 16 * 2 + 8 + 4 * 9; + static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.PLAYER_INDEX, SIZE); + + private ClrwlPlayerUniforms() { + } + + public static void update(RenderContext context) + { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) + { + BUFFER.clear(); + return; + } + + long ptr = BUFFER.ptr(); + + PlayerInfo info = ((AbstractClientPlayerAccessor) player).flywheel$getPlayerInfo(); + + Vec3 eyePos = player.getEyePosition(context.partialTick()); + ptr = writeVec3(ptr, (float) eyePos.x, (float) eyePos.y, (float) eyePos.z); + + ptr = writeTeamColor(ptr, info == null ? null : info.getTeam()); + + ptr = writeEyeBrightness(ptr, player); + + ptr = writeHeldLight(ptr, player); + ptr = writeEyeIn(ptr, player); + + ptr = writeInt(ptr, player.isCrouching() ? 1 : 0); + ptr = writeInt(ptr, player.isSleeping() ? 1 : 0); + ptr = writeInt(ptr, player.isSwimming() ? 1 : 0); + ptr = writeInt(ptr, player.isFallFlying() ? 1 : 0); + + ptr = writeInt(ptr, player.isShiftKeyDown() ? 1 : 0); + + ptr = writeInt(ptr, info == null ? 0 : info.getGameMode() + .getId()); + + BUFFER.markDirty(); + } + + private static long writeTeamColor(long ptr, @Nullable PlayerTeam team) + { + if (team != null) + { + Integer color = team.getColor().getColor(); + + if (color != null) + { + int red = FastColor.ARGB32.red(color); + int green = FastColor.ARGB32.green(color); + int blue = FastColor.ARGB32.blue(color); + return writeVec4(ptr, red / 255f, green / 255f, blue / 255f, 1f); + } + else + { + return writeVec4(ptr, 1f, 1f, 1f, 1f); + } + } + else + { + return writeVec4(ptr, 1f, 1f, 1f, 0f); + } + } + + private static long writeEyeBrightness(long ptr, LocalPlayer player) + { + ClientLevel level = player.clientLevel; + int blockBrightness = level.getBrightness(LightLayer.BLOCK, player.blockPosition()); + int skyBrightness = level.getBrightness(LightLayer.SKY, player.blockPosition()); + int maxBrightness = level.getMaxLightLevel(); + + return writeVec2(ptr, (float) blockBrightness / (float) maxBrightness, + (float) skyBrightness / (float) maxBrightness); + } + + private static long writeHeldLight(long ptr, LocalPlayer player) + { + int heldLight = 0; + + for (InteractionHand hand : InteractionHand.values()) + { + Item handItem = player.getItemInHand(hand).getItem(); + if (handItem instanceof BlockItem blockItem) + { + Block block = blockItem.getBlock(); + int blockLight = FlwBackendXplat.INSTANCE + .getLightEmission(block.defaultBlockState(), player.clientLevel, player.blockPosition()); + if (heldLight < blockLight) + { + heldLight = blockLight; + } + } + } + + return writeFloat(ptr, (float) heldLight / 15); + } + + private static long writeEyeIn(long ptr, LocalPlayer player) + { + ClientLevel level = player.clientLevel; + Vec3 eyePos = player.getEyePosition(); + BlockPos blockPos = BlockPos.containing(eyePos); + return writeInFluidAndBlock(ptr, level, blockPos, eyePos); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlShadowPassUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlShadowPassUniforms.java new file mode 100644 index 000000000..6ded85376 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlShadowPassUniforms.java @@ -0,0 +1,347 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import net.irisshaders.iris.compat.flywheel.engine.ShadowCulling; +import net.irisshaders.iris.compat.flywheel.engine.ShadowRenderContext; +import net.irisshaders.iris.compat.flywheel.indirect.ClrwlDepthPyramid; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.api.visualization.VisualizationManager; +import dev.engine_room.flywheel.backend.engine.uniform.UniformBuffer; +import dev.engine_room.flywheel.backend.mixin.LevelRendererAccessor; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shadows.ShadowMatrices; +import net.irisshaders.iris.shadows.frustum.advanced.NeighboringPlaneSet; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.core.Vec3i; +import org.joml.*; +import org.joml.Math; +import org.lwjgl.system.MemoryUtil; + +public final class ClrwlShadowPassUniforms extends UniformWriter +{ + private static final int SIZE = 12 * 16 // Frustum + + 32 // Cull + + 64 * 9 // View + Projection + + 48 // Normal + + 6 * 8; // Remaining + + public static final UniformBuffer BUFFER = new UniformBuffer(ClrwlUniforms.PASS_INDEX, SIZE); + + private static final Vector4f ZERO_V4F = new Vector4f(0.0f); + + private static final Matrix4f VIEW = new Matrix4f(); + private static final Matrix4f VIEW_INVERSE = new Matrix4f(); + private static final Matrix4f VIEW_PREV = new Matrix4f(); + private static final Matrix4f PROJECTION = new Matrix4f(); + private static final Matrix4f PROJECTION_INVERSE = new Matrix4f(); + private static final Matrix4f PROJECTION_PREV = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION_INVERSE = new Matrix4f(); + private static final Matrix4f VIEW_PROJECTION_PREV = new Matrix4f(); + + private static final Matrix3f NORMAL = new Matrix3f(); + + private static boolean firstWrite = true; + + private static boolean frustumPaused = false; + private static boolean frustumCapture = false; + private static Matrix4fc capturedPlayerProjView = null; + + private ClrwlShadowPassUniforms() { + } + + public static void captureFrustum() + { + frustumPaused = true; + frustumCapture = true; + } + + public static void unpauseFrustum() + { + frustumPaused = false; + capturedPlayerProjView = null; + } + + public static void update(ShadowRenderContext context, ShaderPack pack, NamespacedId dimension, ShadowCulling culling) + { + var programSet = pack.getProgramSet(dimension); + var directives = programSet.getPackDirectives(); + var shadowDirectives = directives.getShadowDirectives(); + + long ptr = BUFFER.ptr(); + setPrev(); + + Vec3i renderOrigin = VisualizationManager.getOrThrow(context.level()) + .renderOrigin(); + var camera = context.camera(); + var camX = (context.camX() - renderOrigin.getX()); + var camY = (context.camY() - renderOrigin.getY()); + var camZ = (context.camZ() - renderOrigin.getZ()); + + int resolution = shadowDirectives.getResolution(); + float zNear; + float zFar; + boolean orthographicProj; + + if (shadowDirectives.getFov() != null) + { + zNear = ShadowMatrices.NEAR; + zFar = ShadowMatrices.FAR; + orthographicProj = false; + } + else + { + zNear = shadowDirectives.getNearPlane(); + zFar = shadowDirectives.getFarPlane(); + orthographicProj = true; + } + + VIEW.set(context./*? if >=1.21 {*/ /*modelView() *//*?} else {*/ stack().last().pose() /*?}*/); + VIEW.translate(-camX, -camY, -camZ); + VIEW.invert(VIEW_INVERSE); + PROJECTION.set(context.projection()); + PROJECTION.invert(PROJECTION_INVERSE); + VIEW_PROJECTION.set(context.viewProjection()); + VIEW_PROJECTION.translate(-camX, -camY, -camZ); + VIEW_PROJECTION.invert(VIEW_PROJECTION_INVERSE); + + Matrix4f normal = new Matrix4f(context./*? if >=1.21 {*/ /*modelView() *//*?} else {*/ stack().last().pose() /*?}*/) + .translate(-camX, -camY, -camZ) + .invert() + .transpose(); + normal.get3x3(NORMAL); + + var playerViewProj = context.playerViewProjection() + .translate(-camX, -camY, -camZ, new Matrix4f()); + + if (firstWrite) + { + setPrev(); + } + + if (frustumCapture) + { + capturedPlayerProjView = playerViewProj; + frustumCapture = false; + } + + writeShadowCullData(ptr, culling, !frustumPaused ? playerViewProj : capturedPlayerProjView); + ptr += 12 * 16; + + ptr = writeCullData(ptr, resolution, zNear, zFar, orthographicProj); + + ptr = writeMatrices(ptr); + + var window = Minecraft.getInstance().getWindow(); + ptr = writeVec2(ptr, resolution, resolution); + ptr = writeFloat(ptr, 1.0f); + // default line width: net.minecraft.client.renderer.RenderStateShard.LineStateShard + ptr = writeFloat(ptr, Math.max(2.5F, (float) window.getWidth() / 1920.0F * 2.5F)); + ptr = writeFloat(ptr, zFar); + + ptr = writeTime(ptr, context); + + firstWrite = false; + BUFFER.markDirty(); + } + + private static void setPrev() + { + VIEW_PREV.set(VIEW); + PROJECTION_PREV.set(PROJECTION); + VIEW_PROJECTION_PREV.set(VIEW_PROJECTION); + } + + private static long writeMatrices(long ptr) + { + ptr = writeMat4(ptr, VIEW); + ptr = writeMat4(ptr, VIEW_INVERSE); + ptr = writeMat4(ptr, VIEW_PREV); + ptr = writeMat4(ptr, PROJECTION); + ptr = writeMat4(ptr, PROJECTION_INVERSE); + ptr = writeMat4(ptr, PROJECTION_PREV); + ptr = writeMat4(ptr, VIEW_PROJECTION); + ptr = writeMat4(ptr, VIEW_PROJECTION_INVERSE); + ptr = writeMat4(ptr, VIEW_PROJECTION_PREV); + ptr = writeMat3(ptr, NORMAL); + return ptr; + } + + private static long writeTime(long ptr, RenderContext context) + { + int ticks = ((LevelRendererAccessor) context.renderer()).flywheel$getTicks(); + float partialTick = context.partialTick(); + float renderTicks = ticks + partialTick; + float renderSeconds = renderTicks / 20f; + float systemSeconds = Util.getMillis() / 1000f; + int systemMillis = (int) (Util.getMillis() % Integer.MAX_VALUE); + + ptr = writeInt(ptr, ticks); + ptr = writeFloat(ptr, partialTick); + ptr = writeFloat(ptr, renderTicks); + ptr = writeFloat(ptr, renderSeconds); + ptr = writeFloat(ptr, systemSeconds); + ptr = writeInt(ptr, systemMillis); + return ptr; + } + + private static long writeCullData(long ptr, int resolution, float zNear, float zFar, boolean orthographic) + { + int pyramidRes = ClrwlDepthPyramid.mip0Size(resolution); + int pyramidDepth = ClrwlDepthPyramid.getImageMipLevels(pyramidRes, pyramidRes); + + ptr = writeFloat(ptr, zNear); + ptr = writeFloat(ptr, zFar); + ptr = writeFloat(ptr, PROJECTION.m00()); // P00 + ptr = writeFloat(ptr, PROJECTION.m11()); // P11 + ptr = writeFloat(ptr, pyramidRes); // pyramidWidth + ptr = writeFloat(ptr, pyramidRes); // pyramidHeight + ptr = writeInt(ptr, pyramidDepth - 1); // pyramidLevels + ptr = writeInt(ptr, orthographic ? 1 : 0); // orthographicProjection + + return ptr; + } + + private static Vector3f getPlaneNormal(Vector4f plane) + { + return new Vector3f(plane.x(), plane.y(), plane.z()); + } + + private static Vector4f normalizePlane(Vector4f plane) + { + float scale = Math.invsqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z); + plane.x *= scale; + plane.y *= scale; + plane.z *= scale; + plane.w *= scale; + return plane; + } + + private static Vector4f processNeighborPlane(Vector4f plane, Vector4f backPlane, Vector3f lightFromOrigin) + { + var planeNormal = getPlaneNormal(plane); + var backPlaneNormal = getPlaneNormal(backPlane); + var intersection = backPlaneNormal.cross(planeNormal, new Vector3f()); + var edgePlaneNormal = intersection.cross(lightFromOrigin, new Vector3f()); + + Vector3f point; + { + // "Line of intersection between two planes" + // https://stackoverflow.com/a/32410473 by ideasman42, CC BY-SA 3.0 + // (a modified version of "Intersection of 2-planes" from Graphics Gems 1, page 305 + var ixb = intersection.cross(backPlaneNormal, new Vector3f()); + var fxi = planeNormal.cross(intersection, new Vector3f()); + + ixb.mul(-plane.w()); + fxi.mul(-backPlane.w()); + + ixb.add(fxi); + + point = ixb; + point.mul(1.0F / intersection.lengthSquared()); + } + + float d = edgePlaneNormal.dot(point); + return normalizePlane(new Vector4f(edgePlaneNormal.x(), edgePlaneNormal.y(), edgePlaneNormal.z(), -d)); + } + + // planes MUST have at least 11 entries + public static int computeFrustumPlanes(Vector3f lightFromOrigin, Matrix4fc playerViewProj, Vector4f[] frustumPlanes) + { + Vector4f[] planes = + { + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_NX, new Vector4f())), + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_PX, new Vector4f())), + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_NY, new Vector4f())), + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_PY, new Vector4f())), + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_NZ, new Vector4f())), + normalizePlane(playerViewProj.frustumPlane(Matrix4fc.PLANE_PZ, new Vector4f())), + }; + + boolean[] isBack = new boolean[6]; + boolean[] isBackOrEdge = new boolean[6]; + int frustumPlaneCount = 0; + + for (int i = 0; i < 6; i++) + { + var plane = planes[i]; + var normal = getPlaneNormal(plane); + var dot = lightFromOrigin.dot(normal); + + var isBackPlane = dot > 0.0f; + var isEdgePlane = dot == 0.0f; + + isBack[i] = isBackPlane; + isBackOrEdge[i] = isBackPlane || isEdgePlane; + + if (isBackPlane || isEdgePlane) + { + frustumPlanes[frustumPlaneCount] = plane; + frustumPlaneCount++; + } + } + + for (int i = 0; i < 6; i++) + { + if (!isBack[i]) + { + continue; + } + + var backPlane = planes[i]; + var neighbors = NeighboringPlaneSet.forPlane(i); + + if (!isBackOrEdge[neighbors.plane0()]) + { + frustumPlanes[frustumPlaneCount] = processNeighborPlane(planes[neighbors.plane0()], backPlane, lightFromOrigin); + frustumPlaneCount++; + } + + if (!isBackOrEdge[neighbors.plane1()]) + { + frustumPlanes[frustumPlaneCount] = processNeighborPlane(planes[neighbors.plane1()], backPlane, lightFromOrigin); + frustumPlaneCount++; + } + + if (!isBackOrEdge[neighbors.plane2()]) + { + frustumPlanes[frustumPlaneCount] = processNeighborPlane(planes[neighbors.plane2()], backPlane, lightFromOrigin); + frustumPlaneCount++; + } + + if (!isBackOrEdge[neighbors.plane3()]) + { + frustumPlanes[frustumPlaneCount] = processNeighborPlane(planes[neighbors.plane3()], backPlane, lightFromOrigin); + frustumPlaneCount++; + } + } + + return frustumPlaneCount; + } + + // Derived from Iris' Advanced Shadow Culling Frustum + // https://github.com/IrisShaders/Iris/blob/37c020371845f1426a65d4e8615a078024cc4b02/common/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java + private static void writeShadowCullData(long ptr, ShadowCulling culling, Matrix4fc playerViewProj) + { + Vector4f[] frustumPlanes = new Vector4f[11]; + int frustumPlaneCount = computeFrustumPlanes(culling.getShadowLightVectorFromOrigin(), playerViewProj, frustumPlanes); + + for (int i = 0; i < 11; i++) + { + var plane = i < frustumPlaneCount ? frustumPlanes[i] : ZERO_V4F; + var idx = i / 4; + var subidx = i % 4; + + MemoryUtil.memPutFloat(ptr + idx * 64L + subidx * 4L + 0L, plane.x()); + MemoryUtil.memPutFloat(ptr + idx * 64L + subidx * 4L + 16L, plane.y()); + MemoryUtil.memPutFloat(ptr + idx * 64L + subidx * 4L + 32L, plane.z()); + MemoryUtil.memPutFloat(ptr + idx * 64L + subidx * 4L + 48L, plane.w()); + } + + MemoryUtil.memPutFloat(ptr + 2 * 64L + 3 * 4L + 0L, culling.getReversedCullDist()); + MemoryUtil.memPutFloat(ptr + 2 * 64L + 3 * 4L + 16L, culling.getCullDist()); + MemoryUtil.memPutFloat(ptr + 2 * 64L + 3 * 4L + 32L, 0.0f); + MemoryUtil.memPutFloat(ptr + 2 * 64L + 3 * 4L + 48L, 0.0f); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlUniforms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlUniforms.java new file mode 100644 index 000000000..9722288c1 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/ClrwlUniforms.java @@ -0,0 +1,82 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import net.irisshaders.iris.compat.flywheel.compile.ClrwlProgram; +import dev.engine_room.flywheel.api.backend.RenderContext; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; + +public class ClrwlUniforms +{ + public static final int FRAME_INDEX = 0; + public static final int PASS_INDEX = 1; + public static final int LEVEL_INDEX = 2; + public static final int PLAYER_INDEX = 3; + public static final int FOG_INDEX = 4; + public static final int OPTIONS_INDEX = 5; + + public static final String FRAME_BLOCK_NAME = "_ClrwlFrameUniforms"; + public static final String PASS_BLOCK_NAME = "_ClrwlPassUniforms"; + public static final String LEVEL_BLOCK_NAME = "_ClrwlLevelUniforms"; + public static final String PLAYER_BLOCK_NAME = "_ClrwlPlayerUniforms"; + public static final String FOG_BLOCK_NAME = "_ClrwlFogUniforms"; + public static final String OPTIONS_BLOCK_NAME = "_ClrwlOptionsUniforms"; + + public static void updateFrame(RenderContext context) + { + ClrwlFrameUniforms.update(context); + ClrwlLevelUniforms.update(context); + ClrwlPlayerUniforms.update(context); + ClrwlFogUniforms.update(); + } + + public static void bind(boolean isShadow) + { + if (isShadow) + { + bindShadow(); + } + else + { + bindGbuffers(); + } + } + + public static void bindGbuffers() + { + ClrwlFrameUniforms.BUFFER.bind(); + ClrwlGbuffersPassUniforms.BUFFER.bind(); + ClrwlLevelUniforms.BUFFER.bind(); + ClrwlPlayerUniforms.BUFFER.bind(); + ClrwlFogUniforms.BUFFER.bind(); + ClrwlOptionsUniforms.BUFFER.bind(); + } + + public static void bindShadow() + { + ClrwlFrameUniforms.BUFFER.bind(); + ClrwlShadowPassUniforms.BUFFER.bind(); + ClrwlLevelUniforms.BUFFER.bind(); + ClrwlPlayerUniforms.BUFFER.bind(); + ClrwlFogUniforms.BUFFER.bind(); + ClrwlOptionsUniforms.BUFFER.bind(); + } + + public static void setUniformsBlockBindings(GlProgram program) + { + program.setUniformBlockBinding(FRAME_BLOCK_NAME, FRAME_INDEX); + program.setUniformBlockBinding(PASS_BLOCK_NAME, PASS_INDEX); + program.setUniformBlockBinding(LEVEL_BLOCK_NAME, LEVEL_INDEX); + program.setUniformBlockBinding(PLAYER_BLOCK_NAME, PLAYER_INDEX); + program.setUniformBlockBinding(FOG_BLOCK_NAME, FOG_INDEX); + program.setUniformBlockBinding(OPTIONS_BLOCK_NAME, OPTIONS_INDEX); + } + + public static void setUniformsBlockBindings(ClrwlProgram program) + { + program.setUniformBlockBinding(FRAME_BLOCK_NAME, FRAME_INDEX); + program.setUniformBlockBinding(PASS_BLOCK_NAME, PASS_INDEX); + program.setUniformBlockBinding(LEVEL_BLOCK_NAME, LEVEL_INDEX); + program.setUniformBlockBinding(PLAYER_BLOCK_NAME, PLAYER_INDEX); + program.setUniformBlockBinding(FOG_BLOCK_NAME, FOG_INDEX); + program.setUniformBlockBinding(OPTIONS_BLOCK_NAME, OPTIONS_INDEX); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/DebugMode.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/DebugMode.java new file mode 100644 index 000000000..acecd61a1 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/DebugMode.java @@ -0,0 +1,45 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import com.mojang.serialization.Codec; +import net.minecraft.commands.arguments.StringRepresentableArgument; +import net.minecraft.commands.synchronization.SingletonArgumentInfo; +import net.minecraft.util.StringRepresentable; + +import java.util.Locale; + +public enum DebugMode implements StringRepresentable +{ + OFF, + NORMALS, + TANGENTS, + TANGENTS_HANDEDNESS, + BLOCK_ID, + MIDTEX, + MIDMESH, + EMISSION, + INSTANCE_ID, + LIGHT_LEVEL, + OVERLAY, + OLD_LIGHTING, + MODEL_ID; + + public static final Codec CODEC = StringRepresentable.fromEnum(DebugMode::values); + + private DebugMode() { + } + + public String getSerializedName() { + return this.name().toLowerCase(Locale.ROOT); + } + + public static class CommandArgument extends StringRepresentableArgument + { + public static final CommandArgument INSTANCE = new CommandArgument(); + public static final SingletonArgumentInfo INFO = SingletonArgumentInfo.contextFree(() -> INSTANCE); + + public CommandArgument() + { + super(DebugMode.CODEC, DebugMode::values); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/UniformWriter.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/UniformWriter.java new file mode 100644 index 000000000..a09bcae9d --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/engine/uniform/UniformWriter.java @@ -0,0 +1,117 @@ +package net.irisshaders.iris.compat.flywheel.engine.uniform; + +import dev.engine_room.flywheel.lib.util.ExtraMemoryOps; +import net.minecraft.core.BlockPos; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3fc; +import org.lwjgl.system.MemoryUtil; + +public class UniformWriter +{ + static long writeInt(long ptr, int value) { + MemoryUtil.memPutInt(ptr, value); + return ptr + 4; + } + + static long writeFloat(long ptr, float value) { + MemoryUtil.memPutFloat(ptr, value); + return ptr + 4; + } + + static long writeVec2(long ptr, float x, float y) { + MemoryUtil.memPutFloat(ptr, x); + MemoryUtil.memPutFloat(ptr + 4, y); + return ptr + 8; + } + + static long writeVec3(long ptr, float x, float y, float z) { + MemoryUtil.memPutFloat(ptr, x); + MemoryUtil.memPutFloat(ptr + 4, y); + MemoryUtil.memPutFloat(ptr + 8, z); + MemoryUtil.memPutFloat(ptr + 12, 0f); // empty component of vec4 because we don't trust std140 + return ptr + 16; + } + + static long writeVec3(long ptr, Vector3fc vec) { + return writeVec3(ptr, vec.x(), vec.y(), vec.z()); + } + + static long writeVec4(long ptr, float x, float y, float z, float w) { + MemoryUtil.memPutFloat(ptr, x); + MemoryUtil.memPutFloat(ptr + 4, y); + MemoryUtil.memPutFloat(ptr + 8, z); + MemoryUtil.memPutFloat(ptr + 12, w); + return ptr + 16; + } + + static long writeIVec2(long ptr, int x, int y) { + MemoryUtil.memPutInt(ptr, x); + MemoryUtil.memPutInt(ptr + 4, y); + return ptr + 8; + } + + static long writeIVec3(long ptr, int x, int y, int z) { + MemoryUtil.memPutInt(ptr, x); + MemoryUtil.memPutInt(ptr + 4, y); + MemoryUtil.memPutInt(ptr + 8, z); + MemoryUtil.memPutInt(ptr + 12, 0); // empty component of vec4 because we don't trust std140 + return ptr + 16; + } + + static long writeIVec4(long ptr, int x, int y, int z, int w) { + MemoryUtil.memPutInt(ptr, x); + MemoryUtil.memPutInt(ptr + 4, y); + MemoryUtil.memPutInt(ptr + 8, z); + MemoryUtil.memPutInt(ptr + 12, w); + return ptr + 16; + } + + static long writeMat4(long ptr, Matrix4f mat) { + ExtraMemoryOps.putMatrix4f(ptr, mat); + return ptr + 64; + } + + static long writeMat3(long ptr, Matrix3f mat) { + ExtraMemoryOps.putMatrix3fPadded(ptr, mat); + return ptr + 48; + } + + static long writeInFluidAndBlock(long ptr, Level level, BlockPos blockPos, Vec3 pos) { + FluidState fluidState = level.getFluidState(blockPos); + BlockState blockState = level.getBlockState(blockPos); + float height = fluidState.getHeight(level, blockPos); + + if (fluidState.isEmpty()) { + MemoryUtil.memPutInt(ptr, 0); + } else if (pos.y < blockPos.getY() + height) { + // TODO: handle custom fluids via defines + if (fluidState.is(FluidTags.WATER)) { + MemoryUtil.memPutInt(ptr, 1); + } else if (fluidState.is(FluidTags.LAVA)) { + MemoryUtil.memPutInt(ptr, 2); + } else { + MemoryUtil.memPutInt(ptr, -1); + } + } + + if (blockState.isAir()) { + MemoryUtil.memPutInt(ptr + 4, 0); + } else { + // TODO: handle custom blocks via defines + if (blockState.is(Blocks.POWDER_SNOW)) { + MemoryUtil.memPutInt(ptr + 4, 0); + } else { + MemoryUtil.memPutInt(ptr + 4, -1); + } + } + + return ptr + 8; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlGlShader.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlGlShader.java new file mode 100644 index 000000000..c858d193d --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlGlShader.java @@ -0,0 +1,29 @@ +package net.irisshaders.iris.compat.flywheel.gl; + +import dev.engine_room.flywheel.backend.gl.GlObject; +import org.lwjgl.opengl.GL20; + +public class ClrwlGlShader extends GlObject +{ + public final ClrwlShaderType type; + private final String name; + + public ClrwlGlShader(int handle, ClrwlShaderType type, String name) + { + this.type = type; + this.name = name; + + handle(handle); + } + + @Override + protected void deleteInternal(int handle) { + GL20.glDeleteShader(handle); + } + + @Override + public String toString() { + return "ClrwlGlShader{" + type.name + handle() + " " + name + "}"; + } + +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlShaderType.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlShaderType.java new file mode 100644 index 000000000..3e414b53a --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/gl/ClrwlShaderType.java @@ -0,0 +1,51 @@ +package net.irisshaders.iris.compat.flywheel.gl; + +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL43; + +import java.util.Optional; + +public enum ClrwlShaderType { + VERTEX("vertex", "VERTEX_SHADER", "vert", GL20.GL_VERTEX_SHADER), + FRAGMENT("fragment", "FRAGMENT_SHADER", "frag", GL20.GL_FRAGMENT_SHADER), + GEOMETRY("geometry", "GEOMETRY_SHADER", "geom", GL43.GL_GEOMETRY_SHADER), + COMPUTE("compute", "COMPUTE_SHADER", "glsl", GL43.GL_COMPUTE_SHADER), + ; + + public final String name; + public final String define; + public final String extension; + public final int glEnum; + + ClrwlShaderType(String name, String define, String extension, int glEnum) { + this.name = name; + this.define = define; + this.extension = extension; + this.glEnum = glEnum; + } + + public Optional toFlw() + { + switch (this) + { + case VERTEX -> + { + return Optional.of(dev.engine_room.flywheel.backend.gl.shader.ShaderType.VERTEX); + } + case FRAGMENT -> + { + return Optional.of(dev.engine_room.flywheel.backend.gl.shader.ShaderType.FRAGMENT); + } + case GEOMETRY -> + { + return Optional.empty(); + } + case COMPUTE -> + { + return Optional.of(dev.engine_room.flywheel.backend.gl.shader.ShaderType.COMPUTE); + } + } + + throw new RuntimeException("Unknown ShaderType: " + this); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlBufferBindings.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlBufferBindings.java new file mode 100644 index 000000000..4684b8690 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlBufferBindings.java @@ -0,0 +1,37 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +public final class ClrwlBufferBindings +{ + public static final int TOTAL_BINDING_COUNT = 10; + + public static final int PAGE_FRAME_DESCRIPTOR = 0; + public static final int BOUNDING_SPHERES = 1; + public static final int INSTANCE = 2; + public static final int DRAW_INSTANCE_INDEX = 3; + public static final int MODEL = 4; + public static final int DRAW = 5; + + public static final int VISIBILITY = 6; + + public static final int LIGHT_LUT = 7; + public static final int LIGHT_SECTION = 8; + public static final int MATRICES = 9; + + // Shader packs bind their own SSBOs starting at 0, so ours go above the pack's highest binding. The constants + // above are relative to this; programs see it as _CLRWL_SSBO_BASE. + private static int base = 0; + + private ClrwlBufferBindings() + { + } + + public static int base() + { + return base; + } + + public static void setBase(int base) + { + ClrwlBufferBindings.base = base; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlDepthPyramid.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlDepthPyramid.java new file mode 100644 index 000000000..b4c0518db --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlDepthPyramid.java @@ -0,0 +1,129 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.engine.ProgramGroupDepthInfo; +import com.mojang.blaze3d.platform.GlStateManager; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlIndirectPrograms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import dev.engine_room.flywheel.backend.gl.GlTextureUnit; +import dev.engine_room.flywheel.lib.math.MoreMath; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL46; + +public class ClrwlDepthPyramid +{ + private final ClrwlProgramGroup programGroup; + private final ClrwlIndirectPrograms programs; + private final IrisRenderingPipeline irisPipeline; + + public int pyramidTextureId = -1; + + private int lastWidth = -1; + private int lastHeight = -1; + + public ClrwlDepthPyramid(ClrwlProgramGroup programGroup, ClrwlIndirectPrograms programs, IrisRenderingPipeline irisPipeline) + { + this.programGroup = programGroup; + this.programs = programs; + this.irisPipeline = irisPipeline; + } + + public void generate() + { + var depthInfo = ProgramGroupDepthInfo.of(irisPipeline, programGroup); + int depthBufferId = depthInfo.textureId(); + int width = mip0Size(depthInfo.width()); + int height = mip0Size(depthInfo.height()); + + int mipLevels = getImageMipLevels(width, height); + + createPyramidMips(mipLevels, width, height); + + GL46.glMemoryBarrier(GL46.GL_FRAMEBUFFER_BARRIER_BIT); + + GlTextureUnit.T0.makeActive(); + GlStateManager._bindTexture(depthBufferId); + + var downsampleFirstProgram = programs.getDownsampleFirstProgram(); + downsampleFirstProgram.bind(); + + GL46.glBindImageTexture(1, pyramidTextureId, 0, false, 0, GL32.GL_WRITE_ONLY, GL32.GL_R32F); + GL46.glDispatchCompute(MoreMath.ceilingDiv(width << 1, 64), MoreMath.ceilingDiv(height << 1, 64), 1); + + var downsampleSecondProgram = programs.getDownsampleSecondProgram(); + downsampleSecondProgram.bind(); + downsampleSecondProgram.setUInt("mip_levels", mipLevels); + + for (int baseMipLevel = 0; baseMipLevel + 1 < mipLevels; baseMipLevel += 6) + { + GL46.glMemoryBarrier(GL46.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); + + downsampleSecondProgram.setUInt("base_mip_level", baseMipLevel); + + for (int i = 0; i < Math.min(7, mipLevels - baseMipLevel); i++) + { + GL46.glBindImageTexture(i, pyramidTextureId, baseMipLevel + i, false, 0, GL32.GL_WRITE_ONLY, GL32.GL_R32F); + } + + GL46.glDispatchCompute(MoreMath.ceilingDiv(width >> baseMipLevel, 64), MoreMath.ceilingDiv(height >> baseMipLevel, 64), 1); + } + + GL46.glMemoryBarrier(GL46.GL_TEXTURE_FETCH_BARRIER_BIT); + } + + public void bindForCull() + { + GlTextureUnit.T0.makeActive(); + GlStateManager._bindTexture(pyramidTextureId); + } + + public void delete() + { + if (pyramidTextureId != -1) + { + GL32.glDeleteTextures(pyramidTextureId); + pyramidTextureId = -1; + } + } + + private void createPyramidMips(int mipLevels, int width, int height) + { + if (lastWidth == width && lastHeight == height) + { + return; + } + + lastWidth = width; + lastHeight = height; + + delete(); + + pyramidTextureId = GL46.glCreateTextures(GL46.GL_TEXTURE_2D); + GL46.glTextureStorage2D(pyramidTextureId, mipLevels, GL32.GL_R32F, width, height); + + GL46.glTextureParameteri(pyramidTextureId, GL32.GL_TEXTURE_MIN_FILTER, GL32.GL_NEAREST); + GL46.glTextureParameteri(pyramidTextureId, GL32.GL_TEXTURE_MAG_FILTER, GL32.GL_NEAREST); + GL46.glTextureParameteri(pyramidTextureId, GL32.GL_TEXTURE_COMPARE_MODE, GL32.GL_NONE); + GL46.glTextureParameteri(pyramidTextureId, GL32.GL_TEXTURE_WRAP_S, GL32.GL_CLAMP_TO_EDGE); + GL46.glTextureParameteri(pyramidTextureId, GL32.GL_TEXTURE_WRAP_T, GL32.GL_CLAMP_TO_EDGE); + } + + public static int mip0Size(int screenSize) + { + return Integer.highestOneBit(screenSize); + } + + public static int getImageMipLevels(int width, int height) + { + int result = 1; + + while (width > 1 && height > 1) + { + result++; + width >>= 1; + height >>= 1; + } + + return result; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectBuffers.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectBuffers.java new file mode 100644 index 000000000..3d0656171 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectBuffers.java @@ -0,0 +1,293 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import dev.engine_room.flywheel.backend.engine.indirect.ObjectStorage; +import dev.engine_room.flywheel.backend.engine.indirect.ResizableStorageArray; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import dev.engine_room.flywheel.backend.gl.buffer.GlBufferType; +import dev.engine_room.flywheel.lib.memory.MemoryBlock; +import org.lwjgl.opengl.GL46; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.Pointer; + +import static org.lwjgl.opengl.GL30.glBindBufferBase; +import static org.lwjgl.opengl.GL43.GL_SHADER_STORAGE_BUFFER; +import static org.lwjgl.opengl.GL44.nglBindBuffersRange; + +public class ClrwlIndirectBuffers +{ + // Number of vbos created. + public static final int BUFFER_COUNT = 6; + + public static final long INT_SIZE = Integer.BYTES; + public static final long PTR_SIZE = Pointer.POINTER_SIZE; + public static final long SPHERE_SIZE = Float.BYTES * 4L; + + public static final long MODEL_STRIDE = 28 + 12; + + // Byte size of a draw command, plus our added mesh data. + public static final long DRAW_COMMAND_STRIDE = 36 + 12; + public static final long DRAW_COMMAND_OFFSET = 0; + + // Offsets to the 3 segments + private static final long HANDLE_OFFSET = 0; + private static final long OFFSET_OFFSET = BUFFER_COUNT * INT_SIZE; + private static final long SIZE_OFFSET = OFFSET_OFFSET + BUFFER_COUNT * PTR_SIZE; + // Total size of the buffer. + private static final long BUFFERS_SIZE_BYTES = SIZE_OFFSET + BUFFER_COUNT * PTR_SIZE; + + // Offsets to the vbos + private static final long PAGE_FRAME_DESCRIPTOR_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.PAGE_FRAME_DESCRIPTOR * INT_SIZE; + private static final long BOUNDING_SPHERE_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.BOUNDING_SPHERES * INT_SIZE; + private static final long INSTANCE_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.INSTANCE * INT_SIZE; + private static final long DRAW_INSTANCE_INDEX_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.DRAW_INSTANCE_INDEX * INT_SIZE; + private static final long MODEL_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.MODEL * INT_SIZE; + private static final long DRAW_HANDLE_OFFSET = HANDLE_OFFSET + ClrwlBufferBindings.DRAW * INT_SIZE; + + // Offsets to the sizes + private static final long PAGE_FRAME_DESCRIPTOR_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.PAGE_FRAME_DESCRIPTOR * PTR_SIZE; + private static final long BOUNDING_SPHERE_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.BOUNDING_SPHERES * PTR_SIZE; + private static final long INSTANCE_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.INSTANCE * PTR_SIZE; + private static final long DRAW_INSTANCE_INDEX_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.DRAW_INSTANCE_INDEX * PTR_SIZE; + private static final long MODEL_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.MODEL * PTR_SIZE; + private static final long DRAW_SIZE_OFFSET = SIZE_OFFSET + ClrwlBufferBindings.DRAW * PTR_SIZE; + + + private static final float INSTANCE_GROWTH_FACTOR = 1.25f; + private static final float MODEL_GROWTH_FACTOR = 2f; + private static final float DRAW_GROWTH_FACTOR = 2f; + + /** + * A small block of memory divided into 3 contiguous segments: + *
+ * {@code buffers}: an array of {@link net.irisshaders.iris.compat.flywheel.indirect.ClrwlIndirectBuffers#INT_SIZE} buffer handles. + *
+ * {@code offsets}: an array of {@link net.irisshaders.iris.compat.flywheel.indirect.ClrwlIndirectBuffers#PTR_SIZE} offsets into the buffers, currently just zeroed. + *
+ * {@code sizes}: an array of {@link net.irisshaders.iris.compat.flywheel.indirect.ClrwlIndirectBuffers#PTR_SIZE} byte lengths of the buffers. + *
+ * Each segment stores {@link net.irisshaders.iris.compat.flywheel.indirect.ClrwlIndirectBuffers#BUFFER_COUNT} elements, + * one for the instance buffer, target buffer, model index buffer, model buffer, and draw buffer. + */ + private final MemoryBlock multiBindBlock; + + public final ObjectStorage objectStorage; + public final ResizableStorageArray boundingSpheres; + public final ResizableStorageArray drawInstanceIndex; + public final ResizableStorageArray model; + public final ResizableStorageArray draw; + + public ClrwlIndirectBuffers(long instanceStride) + { + this.multiBindBlock = MemoryBlock.calloc(BUFFERS_SIZE_BYTES, 1); + + objectStorage = new ObjectStorage(instanceStride); + boundingSpheres = new ResizableStorageArray(SPHERE_SIZE, INSTANCE_GROWTH_FACTOR); + drawInstanceIndex = new ResizableStorageArray(INT_SIZE, INSTANCE_GROWTH_FACTOR); + model = new ResizableStorageArray(MODEL_STRIDE, MODEL_GROWTH_FACTOR); + draw = new ResizableStorageArray(DRAW_COMMAND_STRIDE, DRAW_GROWTH_FACTOR); + } + + public void updateCounts(int instanceCount, int modelCount, int drawCount) + { + final long ptr = multiBindBlock.ptr(); + + boundingSpheres.ensureCapacity(getAllocatedInstanceCount()); + drawInstanceIndex.ensureCapacity(instanceCount); + model.ensureCapacity(modelCount); + draw.ensureCapacity(drawCount); + + MemoryUtil.memPutInt(ptr + PAGE_FRAME_DESCRIPTOR_HANDLE_OFFSET, objectStorage.frameDescriptorBuffer.handle()); + MemoryUtil.memPutInt(ptr + BOUNDING_SPHERE_HANDLE_OFFSET, boundingSpheres.handle()); + MemoryUtil.memPutInt(ptr + INSTANCE_HANDLE_OFFSET, objectStorage.objectBuffer.handle()); + MemoryUtil.memPutInt(ptr + DRAW_INSTANCE_INDEX_HANDLE_OFFSET, drawInstanceIndex.handle()); + MemoryUtil.memPutInt(ptr + MODEL_HANDLE_OFFSET, model.handle()); + MemoryUtil.memPutInt(ptr + DRAW_HANDLE_OFFSET, draw.handle()); + + MemoryUtil.memPutAddress(ptr + PAGE_FRAME_DESCRIPTOR_SIZE_OFFSET, objectStorage.frameDescriptorBuffer.capacity()); + MemoryUtil.memPutAddress(ptr + BOUNDING_SPHERE_SIZE_OFFSET, SPHERE_SIZE * boundingSpheres.capacity()); + MemoryUtil.memPutAddress(ptr + INSTANCE_SIZE_OFFSET, objectStorage.objectBuffer.capacity()); + MemoryUtil.memPutAddress(ptr + DRAW_INSTANCE_INDEX_SIZE_OFFSET, INT_SIZE * instanceCount); + MemoryUtil.memPutAddress(ptr + MODEL_SIZE_OFFSET, MODEL_STRIDE * modelCount); + MemoryUtil.memPutAddress(ptr + DRAW_SIZE_OFFSET, DRAW_COMMAND_STRIDE * drawCount); + } + + private long getAllocatedPageCount() + { + return objectStorage.frameDescriptorBuffer.capacity() / 2L / 4L; // 2 * 4 bytes per page + } + + private long getAllocatedInstanceCount() + { + return getAllocatedPageCount() * 32L; // 1 page = 32 instances + } + + public void bindForTransform() + { + multiBind(0, 5); + } + + public void bindForCull() + { + multiBind(0, 5); + } + + public void bindForApply() + { + multiBind(4, 2); + } + + public void bindForModelReset() + { + multiBind(4, 1); + } + + public void bindForDraw() + { + multiBind(2, 4); + GlBufferType.DRAW_INDIRECT_BUFFER.bind(draw.handle()); + } + + public void bindForCrumbling() + { + // All we need is the instance buffer. Crumbling uses its own draw buffer. + multiBind(ClrwlBufferBindings.INSTANCE, 1); + } + + private void multiBind(int base, int count) + { + final long ptr = multiBindBlock.ptr(); + nglBindBuffersRange(GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + base, count, ptr + base * INT_SIZE, ptr + OFFSET_OFFSET + base * PTR_SIZE, ptr + SIZE_OFFSET + base * PTR_SIZE); + } + + public void delete() + { + multiBindBlock.free(); + + objectStorage.delete(); + boundingSpheres.delete(); + drawInstanceIndex.delete(); + model.delete(); + draw.delete(); + } + + public PipelineBuffers makePipelineBuffers() + { + return new PipelineBuffers(); + } + + public DrawSnapshot makeDrawSnapshot() + { + return new DrawSnapshot(); + } + + public class PipelineBuffers + { + public final ResizableStorageArray lastFrameVisibility; + public final ResizableStorageArray shadowLastFrameVisibility; + + public PipelineBuffers() + { + lastFrameVisibility = new ResizableStorageArray(INT_SIZE, INSTANCE_GROWTH_FACTOR); + shadowLastFrameVisibility = new ResizableStorageArray(INT_SIZE, INSTANCE_GROWTH_FACTOR); + } + + public void updateCounts() + { + lastFrameVisibility.ensureCapacity(ClrwlIndirectBuffers.this.getAllocatedPageCount()); + shadowLastFrameVisibility.ensureCapacity(ClrwlIndirectBuffers.this.getAllocatedPageCount()); + } + + public void bindForCull(boolean isShadow) + { + var handle = isShadow ? shadowLastFrameVisibility.handle() : lastFrameVisibility.handle(); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + ClrwlBufferBindings.VISIBILITY, handle); + } + + public void delete() + { + lastFrameVisibility.delete(); + shadowLastFrameVisibility.delete(); + } + } + + public class DrawSnapshot + { + private long drawInstanceIndexCpy; + private final long drawInstanceIndexSize; + + private long modelCpy; + private final long modelSize; + + private long drawCpy; + private final long drawSize; + + private DrawSnapshot() + { + this.drawInstanceIndexSize = drawInstanceIndex.byteCapacity(); + this.modelSize = model.byteCapacity(); + this.drawSize = draw.byteCapacity(); + + this.drawInstanceIndexCpy = saveBuffer(drawInstanceIndex, this.drawInstanceIndexSize); + this.modelCpy = saveBuffer(model, this.modelSize); + this.drawCpy = saveBuffer(draw, this.drawSize); + } + + private static long saveBuffer(ResizableStorageArray buffer, long size) + { + if (size == 0) + { + return 0; + } + + long ptr = MemoryUtil.nmemAlloc(size); + GL46.nglGetNamedBufferSubData(buffer.handle(), 0, size, ptr); + + return ptr; + } + + public void applyAndConsume(StagingBuffer buffer) + { + if (drawInstanceIndexCpy > 0) + { + buffer.enqueueCopy(drawInstanceIndexCpy, drawInstanceIndexSize, drawInstanceIndex.handle(), 0); + MemoryUtil.nmemFree(drawInstanceIndexCpy); + drawInstanceIndexCpy = 0; + } + + if (modelCpy > 0) + { + buffer.enqueueCopy(modelCpy, modelSize, model.handle(), 0); + MemoryUtil.nmemFree(modelCpy); + modelCpy = 0; + } + + if (drawCpy > 0) + { + buffer.enqueueCopy(drawCpy, drawSize, draw.handle(), 0); + MemoryUtil.nmemFree(drawCpy); + drawCpy = 0; + } + } + + public void destroy() + { + if (drawInstanceIndexCpy > 0) + { + MemoryUtil.nmemFree(drawInstanceIndexCpy); + drawInstanceIndexCpy = 0; + } + + if (modelCpy > 0) + { + MemoryUtil.nmemFree(modelCpy); + modelCpy = 0; + } + + if (drawCpy > 0) + { + MemoryUtil.nmemFree(drawCpy); + drawCpy = 0; + } + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectCullingGroup.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectCullingGroup.java new file mode 100644 index 000000000..05ba53ff4 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectCullingGroup.java @@ -0,0 +1,512 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.compile.ClrwlIndirectPrograms; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlProgram; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlShaderKey; +import net.irisshaders.iris.compat.flywheel.engine.*; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.api.material.Material; +import dev.engine_room.flywheel.api.model.Model; +import dev.engine_room.flywheel.backend.compile.ContextShader; +import dev.engine_room.flywheel.backend.engine.MaterialRenderState; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import dev.engine_room.flywheel.backend.gl.GlCompat; +import dev.engine_room.flywheel.backend.gl.shader.GlProgram; +import dev.engine_room.flywheel.lib.math.MoreMath; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import static org.lwjgl.opengl.GL11.GL_TRIANGLES; +import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT; +import static org.lwjgl.opengl.GL43.glDispatchCompute; + +public class ClrwlIndirectCullingGroup +{ + private static final Comparator DRAW_COMPARATOR = Comparator.comparing(ClrwlIndirectDraw::isEmbedded) + .thenComparingInt(ClrwlIndirectDraw::bias) + .thenComparingInt(ClrwlIndirectDraw::indexOfMeshInModel) + .thenComparing(ClrwlIndirectDraw::material, MaterialRenderState.COMPARATOR); + + private final InstanceType instanceType; + private final long instanceStride; + private final ClrwlIndirectBuffers buffers; + private final List> instancers = new ArrayList<>(); + private final List indirectDraws = new ArrayList<>(); + private final List solidDraws = new ArrayList<>(); + private final List translucentDraws = new ArrayList<>(); + private final List oitDraws = new ArrayList<>(); + + private final ProgramSet programSet; + private final GlProgram transformSphereProgram; + + private boolean needsDrawSort; + private int instanceCountThisFrame; + + ClrwlIndirectCullingGroup(InstanceType instanceType, ClrwlIndirectPrograms programs, ProgramSet programSet) + { + this.instanceType = instanceType; + instanceStride = MoreMath.align4(instanceType.layout().byteSize()); + // Compiled first: if it throws, the group is never registered, so buffers allocated before it would leak. + transformSphereProgram = programs.getTransformProgram(instanceType); + buffers = new ClrwlIndirectBuffers(instanceStride); + + this.programSet = programSet; + } + + public boolean flushInstancers() + { + instanceCountThisFrame = 0; + int modelIndex = 0; + for (var iterator = instancers.iterator(); iterator.hasNext();) + { + var instancer = iterator.next(); + var instanceCount = instancer.instanceCount(); + + if (instanceCount == 0) + { + iterator.remove(); + instancer.delete(); + continue; + } + + instancer.update(modelIndex, instanceCountThisFrame); + instanceCountThisFrame += instanceCount; + + modelIndex++; + } + + if (indirectDraws.removeIf(ClrwlIndirectDraw::deleted)) + { + needsDrawSort = true; + } + + var out = indirectDraws.isEmpty(); + + if (out) + { + delete(); + } + + return out; + } + + public void upload(StagingBuffer stagingBuffer) + { + buffers.updateCounts(instanceCountThisFrame, instancers.size(), indirectDraws.size()); + + // Upload only instances that have changed. + uploadInstances(stagingBuffer); + + buffers.objectStorage.uploadDescriptors(stagingBuffer); + + // We need to upload the models every frame to reset the instance count. + uploadModels(stagingBuffer); + + if (needsDrawSort) + { + sortDraws(); + needsDrawSort = false; + } + + uploadDraws(stagingBuffer); + } + + public void dispatchTransform() + { + transformSphereProgram.bind(); + + buffers.bindForTransform(); + glDispatchCompute(buffers.objectStorage.capacity(), 1, 1); + } + + public void dispatchCull() + { + buffers.bindForCull(); + glDispatchCompute(buffers.objectStorage.capacity(), 1, 1); + } + + public void dispatchApply() + { + buffers.bindForApply(); + glDispatchCompute(GlCompat.getComputeGroupCount(indirectDraws.size()), 1, 1); + } + + public void dispatchModelReset() + { + buffers.bindForModelReset(); + glDispatchCompute(GlCompat.getComputeGroupCount(indirectDraws.size()), 1, 1); + } + + public boolean hasSolidDraws() + { + return !solidDraws.isEmpty(); + } + + public boolean hasTranslucentDraws() + { + return !translucentDraws.isEmpty(); + } + + public boolean hasOitDraws() + { + return !oitDraws.isEmpty(); + } + + public int materialFilter() + { + int res = 0; + + if (!solidDraws.isEmpty()) + { + res |= ClrwlIndirectPrograms.Culling.MaterialFilter.SOLID; + } + + if (!translucentDraws.isEmpty() || !oitDraws.isEmpty()) + { + res |= ClrwlIndirectPrograms.Culling.MaterialFilter.TRANSLUCENT; + } + + return res; + } + + private void sortDraws() + { + solidDraws.clear(); + translucentDraws.clear(); + oitDraws.clear(); + // sort by visual type, then material + indirectDraws.sort(DRAW_COMPARATOR); + + for (int start = 0, i = 0; i < indirectDraws.size(); i++) + { + var draw1 = indirectDraws.get(i); + + // if the next draw call has a different VisualType or Material, start a new MultiDraw + if (i == indirectDraws.size() - 1 || incompatibleDraws(draw1, indirectDraws.get(i + 1))) + { + List dst; + switch (draw1.material().transparency()) + { + case TRANSLUCENT -> dst = translucentDraws; + case ORDER_INDEPENDENT -> dst = oitDraws; + default -> dst = solidDraws; + } + + dst.add(new MultiDraw(draw1.material(), draw1.isEmbedded(), start, i + 1)); + start = i + 1; + } + } + } + + private boolean incompatibleDraws(ClrwlIndirectDraw draw1, ClrwlIndirectDraw draw2) + { + if (draw1.isEmbedded() != draw2.isEmbedded()) + { + return true; + } + + return !MaterialRenderState.materialEquals(draw1.material(), draw2.material()); + } + + public void add(ClrwlIndirectInstancer instancer, ClrwlInstancerKey key, ClrwlMeshPool meshPool) + { + instancer.mapping = buffers.objectStorage.createMapping(); + instancer.update(instancers.size(), -1); + + instancers.add(instancer); + + List meshes = key.model() + .meshes(); + for (int i = 0; i < meshes.size(); i++) + { + var entry = meshes.get(i); + + ClrwlMeshPool.PooledMesh mesh = meshPool.alloc(entry.mesh()); + var draw = new ClrwlIndirectDraw(instancer, entry.material(), mesh, key.bias(), i); + indirectDraws.add(draw); + instancer.addDraw(draw); + } + + needsDrawSort = true; + } + + public void submitSolid(ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers, boolean isShadow) + { + if (solidDraws.isEmpty()) + { + return; + } + + buffers.bindForDraw(); + + ClrwlProgram prevProgram = null; + GlFramebuffer prevFramebuffer = null; + + for (var multiDraw : solidDraws) + { + var key = ClrwlShaderKey.fromMaterial(instanceType, + multiDraw.material, + multiDraw.embedded ? ContextShader.EMBEDDED : ContextShader.DEFAULT, + isShadow, + ClrwlPrograms.OitMode.OFF); + + var program = programs.get(key); + + if (program == null) + { + continue; + } + + var programId = ClrwlProgramId.fromTransparency(multiDraw.material.transparency(), isShadow); + var framebuffer = framebuffers.getFramebuffer(programId); + + if (framebuffer == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + var blendOverride = framebuffers.getBlendModeOverride(programId).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(programId); + + program.setClrwlCommonUniforms(multiDraw.material, blendOverride, ClrwlRenderingPhase.SOLID); + ClrwlMaterialRenderState.setup(multiDraw.material, blendOverride, bufferBlendOverrides); + + if (prevFramebuffer != framebuffer) + { + prevFramebuffer = framebuffer; + framebuffer.bind(); + } + + multiDraw.submit(program); + + prevProgram = program; + } + } + + private void drawTranslucent(List draws, ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers, boolean isShadow) + { + if (draws.isEmpty()) + { + return; + } + + var programId = !isShadow + ? ClrwlProgramId.GBUFFERS_TRANSLUCENT + : ClrwlProgramId.SHADOW_TRANSLUCENT; + + var framebuffer = framebuffers.getFramebuffer(programId); + var blendOverride = framebuffers.getBlendModeOverride(programId).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(programId); + + if (framebuffer == null) + { + return; + } + + buffers.bindForDraw(); + + ClrwlProgram prevProgram = null; + GlFramebuffer prevFramebuffer = null; + + for (var multiDraw : draws) + { + var key = ClrwlShaderKey.fromMaterial(instanceType, + multiDraw.material, + multiDraw.embedded ? ContextShader.EMBEDDED : ContextShader.DEFAULT, + isShadow, + ClrwlPrograms.OitMode.OFF); + + var program = programs.get(key); + + if (program == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + program.setClrwlCommonUniforms(multiDraw.material, blendOverride, ClrwlRenderingPhase.TRANSLUCENT); + ClrwlMaterialRenderState.setup(multiDraw.material, blendOverride, bufferBlendOverrides); + + if (prevFramebuffer != framebuffer) + { + prevFramebuffer = framebuffer; + framebuffer.bind(); + } + + multiDraw.submit(program); + + prevProgram = program; + } + } + + public void submitTranslucent(ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers, boolean isShadow) + { + drawTranslucent(translucentDraws, programs, framebuffers, isShadow); + } + + public void submitOitAsTranslucent(ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers, boolean isShadow) + { + drawTranslucent(oitDraws, programs, framebuffers, isShadow); + } + + public void submitOit(ClrwlPrograms.OitMode oit, ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers, boolean isShadow, ClrwlRenderingPhase renderingPhase) + { + if (oitDraws.isEmpty()) + { + return; + } + + var programId = !isShadow + ? ClrwlProgramId.GBUFFERS_TRANSLUCENT + : ClrwlProgramId.SHADOW_TRANSLUCENT; + + var blendOverride = framebuffers.getBlendModeOverride(programId).orElse(null); + + buffers.bindForDraw(); + + ClrwlProgram prevProgram = null; + + for (var multiDraw : oitDraws) + { + var key = ClrwlShaderKey.fromMaterial(instanceType, + multiDraw.material, + multiDraw.embedded ? ContextShader.EMBEDDED : ContextShader.DEFAULT, + isShadow, + oit); + + var program = programs.get(key); + + if (program == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + program.setClrwlCommonUniforms(multiDraw.material, blendOverride, renderingPhase); + ClrwlMaterialRenderState.setupOit(multiDraw.material); + + multiDraw.submit(program); + + prevProgram = program; + } + } + + public boolean bindForCrumbling(Material material, ClrwlIndirectPrograms.PipelinePrograms programs, ClrwlBlendModeOverride blendModeOverride) + { + var key = ClrwlShaderKey.fromMaterial(instanceType, material, ContextShader.CRUMBLING, false, ClrwlPrograms.OitMode.OFF); + var program = programs.get(key); + + if (program == null) + { + return false; + } + + program.bind(); + buffers.bindForCrumbling(); + + program.setClrwlCommonUniforms(material, blendModeOverride, ClrwlRenderingPhase.CRUMBLING); + program.setBaseDrawUniform(0); + + return true; + } + + private void uploadInstances(StagingBuffer stagingBuffer) + { + for (var instancer : instancers) + { + instancer.uploadInstances(stagingBuffer, buffers.objectStorage.objectBuffer.handle()); + } + } + + private void uploadModels(StagingBuffer stagingBuffer) + { + var totalSize = instancers.size() * ClrwlIndirectBuffers.MODEL_STRIDE; + var handle = buffers.model.handle(); + + stagingBuffer.enqueueCopy(totalSize, handle, 0, this::writeModels); + } + + private void uploadDraws(StagingBuffer stagingBuffer) + { + var totalSize = indirectDraws.size() * ClrwlIndirectBuffers.DRAW_COMMAND_STRIDE; + var handle = buffers.draw.handle(); + + stagingBuffer.enqueueCopy(totalSize, handle, 0, this::writeCommands); + } + + private void writeModels(long writePtr) + { + for (var model : instancers) + { + model.writeModel(writePtr); + writePtr += ClrwlIndirectBuffers.MODEL_STRIDE; + } + } + + private void writeCommands(long writePtr) + { + for (var draw : indirectDraws) + { + draw.write(writePtr); + writePtr += ClrwlIndirectBuffers.DRAW_COMMAND_STRIDE; + } + } + + public ClrwlIndirectBuffers.PipelineBuffers makePipelineBuffers() + { + return buffers.makePipelineBuffers(); + } + + public ClrwlIndirectBuffers.DrawSnapshot makeDrawSnapshot() + { + return buffers.makeDrawSnapshot(); + } + + public void delete() + { + buffers.delete(); + } + + private record MultiDraw(Material material, boolean embedded, int start, int end) + { + private void submit(ClrwlProgram drawProgram) + { + GlCompat.safeMultiDrawElementsIndirect(drawProgram, GL_TRIANGLES, GL_UNSIGNED_INT, this.start, this.end, ClrwlIndirectBuffers.DRAW_COMMAND_STRIDE); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDraw.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDraw.java new file mode 100644 index 000000000..0b193157d --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDraw.java @@ -0,0 +1,116 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlMeshPool; +import net.irisshaders.iris.compat.flywheel.engine.embed.EmbeddedEnvironment; +import dev.engine_room.flywheel.api.material.Material; +import dev.engine_room.flywheel.backend.engine.MaterialEncoder; +import org.lwjgl.system.MemoryUtil; + +public class ClrwlIndirectDraw +{ + private final ClrwlIndirectInstancer instancer; + private final Material material; + private final ClrwlMeshPool.PooledMesh mesh; + private final int bias; + private final int indexOfMeshInModel; + + private final int packedFogAndCutout; + private final int packedMaterialProperties; + private boolean deleted; + + public ClrwlIndirectDraw(ClrwlIndirectInstancer instancer, Material material, ClrwlMeshPool.PooledMesh mesh, int bias, int indexOfMeshInModel) + { + this.instancer = instancer; + this.material = material; + this.mesh = mesh; + this.bias = bias; + this.indexOfMeshInModel = indexOfMeshInModel; + + mesh.acquire(); + + this.packedFogAndCutout = MaterialEncoder.packUberShader(material); + this.packedMaterialProperties = MaterialEncoder.packProperties(material); + } + + public boolean deleted() + { + return deleted; + } + + public Material material() + { + return material; + } + + public boolean isEmbedded() + { + return instancer.environment instanceof EmbeddedEnvironment; + } + + public ClrwlMeshPool.PooledMesh mesh() + { + return mesh; + } + + public int bias() + { + return bias; + } + + public int indexOfMeshInModel() + { + return indexOfMeshInModel; + } + + public void write(long ptr) + { + MemoryUtil.memPutInt(ptr, mesh.indexCount()); // count + MemoryUtil.memPutInt(ptr + 4, 0); // instanceCount - to be set by the apply shader + MemoryUtil.memPutInt(ptr + 8, mesh.firstIndex()); // firstIndex + MemoryUtil.memPutInt(ptr + 12, mesh.baseVertex()); // baseVertex + MemoryUtil.memPutInt(ptr + 16, instancer.baseInstance()); // baseInstance + + MemoryUtil.memPutInt(ptr + 20, instancer.modelIndex()); // modelIndex + + MemoryUtil.memPutInt(ptr + 24, instancer.environment.matrixIndex()); // matrixIndex + + MemoryUtil.memPutInt(ptr + 28, packedFogAndCutout); // packedFogAndCutout + MemoryUtil.memPutInt(ptr + 32, packedMaterialProperties); // packedMaterialProperties + + MemoryUtil.memPutFloat(ptr + 36, mesh.meshCenter().x()); + MemoryUtil.memPutFloat(ptr + 40, mesh.meshCenter().y()); + MemoryUtil.memPutFloat(ptr + 44, mesh.meshCenter().z()); + } + + public void writeWithOverrides(long ptr, int instanceIndex, Material materialOverride) + { + MemoryUtil.memPutInt(ptr, mesh.indexCount()); // count + MemoryUtil.memPutInt(ptr + 4, 1); // instanceCount - only drawing one instance + MemoryUtil.memPutInt(ptr + 8, mesh.firstIndex()); // firstIndex + MemoryUtil.memPutInt(ptr + 12, mesh.baseVertex()); // baseVertex + MemoryUtil.memPutInt(ptr + 16, instancer.local2GlobalInstanceIndex(instanceIndex)); // baseInstance + + MemoryUtil.memPutInt(ptr + 20, instancer.modelIndex()); // modelIndex + + MemoryUtil.memPutInt(ptr + 24, instancer.environment.matrixIndex()); // matrixIndex + + MemoryUtil.memPutInt(ptr + 28, MaterialEncoder.packUberShader(materialOverride)); // packedFogAndCutout + MemoryUtil.memPutInt(ptr + 32, MaterialEncoder.packProperties(materialOverride)); // packedMaterialProperties + + MemoryUtil.memPutFloat(ptr + 36, mesh.meshCenter().x()); + MemoryUtil.memPutFloat(ptr + 40, mesh.meshCenter().y()); + MemoryUtil.memPutFloat(ptr + 44, mesh.meshCenter().z()); + } + + public void delete() + { + if (deleted) + { + return; + } + + mesh.release(); + + deleted = true; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDrawManager.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDrawManager.java new file mode 100644 index 000000000..e942b8049 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectDrawManager.java @@ -0,0 +1,837 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.ClrwlBackend; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlIndirectPrograms; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import net.irisshaders.iris.compat.flywheel.engine.*; +import net.irisshaders.iris.compat.flywheel.engine.embed.EnvironmentStorage; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramGroup; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import dev.engine_room.flywheel.api.backend.Engine; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceType; +import dev.engine_room.flywheel.backend.Samplers; +import dev.engine_room.flywheel.backend.engine.CommonCrumbling; +import dev.engine_room.flywheel.backend.engine.GroupKey; +import dev.engine_room.flywheel.backend.engine.LightStorage; +import dev.engine_room.flywheel.backend.engine.TextureBinder; +import dev.engine_room.flywheel.backend.engine.indirect.IndirectBuffers; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import dev.engine_room.flywheel.backend.gl.array.GlVertexArray; +import dev.engine_room.flywheel.backend.gl.buffer.GlBuffer; +import dev.engine_room.flywheel.backend.gl.buffer.GlBufferType; +import dev.engine_room.flywheel.backend.gl.buffer.GlBufferUsage; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.lib.material.SimpleMaterial; +import dev.engine_room.flywheel.lib.memory.MemoryBlock; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.model.ModelBakery; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.lwjgl.opengl.GL11.GL_TRIANGLES; +import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT; +import static org.lwjgl.opengl.GL30.glBindBufferRange; +import static org.lwjgl.opengl.GL40.glDrawElementsIndirect; +import static org.lwjgl.opengl.GL42.GL_COMMAND_BARRIER_BIT; +import static org.lwjgl.opengl.GL42.glMemoryBarrier; +import static org.lwjgl.opengl.GL43.GL_SHADER_STORAGE_BARRIER_BIT; +import static org.lwjgl.opengl.GL43.GL_SHADER_STORAGE_BUFFER; + +public class ClrwlIndirectDrawManager extends ClrwlDrawManager> +{ + public record PipelineData(ClrwlIndirectPrograms.PipelinePrograms programs, + ClrwlFramebuffers framebuffers, + ClrwlDepthPyramid depthPyramid, + ClrwlDepthPyramid shadowDepthPyramid, + Map, ClrwlIndirectBuffers.PipelineBuffers> buffers) + { + public ClrwlIndirectBuffers.PipelineBuffers getBuffers(ClrwlIndirectCullingGroup group) + { + return buffers.computeIfAbsent(group, ClrwlIndirectCullingGroup::makePipelineBuffers); + } + + public ClrwlDepthPyramid depthPyramid(boolean isShadow) + { + return isShadow ? shadowDepthPyramid : depthPyramid; + } + + public void delete() + { + programs.delete(); + framebuffers.delete(); + depthPyramid.delete(); + shadowDepthPyramid.delete(); + + for (var buffer : buffers.values()) + { + buffer.delete(); + } + + buffers.clear(); + } + } + + private final ClrwlIndirectPrograms programs; + private final ClrwlMeshPool meshPool; + private final GlVertexArray vao; + private final Map, ClrwlIndirectCullingGroup> cullingGroups = new HashMap<>(); + private final GlBuffer crumblingDrawBuffer = new GlBuffer(GlBufferUsage.STREAM_DRAW); + private final StagingBuffer stagingBuffer; + private final ClrwlLightBuffers lightBuffers; + private final ClrwlMatrixBuffer matrixBuffer; + + private final Map pipelineData = new HashMap<>(); + private final List shadowSolidDraws = new ArrayList<>(); + private final List shadowTranslucentDraws = new ArrayList<>(); + + private final ShaderPack pack; + private final ProgramSet programSet; + + private boolean areModelInstanceCountsDirty = false; + private boolean hasInflightApply = false; + + public ClrwlIndirectDrawManager(ShaderPack pack, ProgramSet programSet, ClrwlIndirectPrograms programs) + { + this.pack = pack; + this.programSet = programSet; + + this.programs = programs; + this.meshPool = new ClrwlMeshPool(); + this.vao = GlVertexArray.create(); + this.stagingBuffer = new StagingBuffer(programs.getFlwPrograms()); + this.lightBuffers = new ClrwlLightBuffers(); + this.matrixBuffer = new ClrwlMatrixBuffer(); + + this.meshPool.bind(vao); + } + + public static ClrwlIndirectDrawManager build(ShaderSources sources, ShaderPack pack, ProgramSet programSet, boolean isFallback) + { + var programs = ClrwlIndirectPrograms.build(sources, pack, programSet, isFallback); + + if (programs == null) + { + return null; + } + + return new ClrwlIndirectDrawManager(pack, programSet, programs); + } + + @Override + protected ClrwlIndirectInstancer create(ClrwlInstancerKey key) + { + return new ClrwlIndirectInstancer<>(key, new ClrwlAbstractInstancer.Recreate<>(key, this)); + } + + @SuppressWarnings("unchecked") + @Override + protected void initialize(ClrwlInstancerKey key, ClrwlIndirectInstancer instancer) + { + var group = (ClrwlIndirectCullingGroup) cullingGroups.computeIfAbsent(key.type(), t -> new ClrwlIndirectCullingGroup<>(t, programs, programSet)); + group.add((ClrwlIndirectInstancer) instancer, key, meshPool); + } + + @Override + public void prepareFrame(LightStorage lightStorage, EnvironmentStorage environmentStorage) + { + super.prepareFrame(lightStorage, environmentStorage); + + if (!shadowSolidDraws.isEmpty()) + { + for (var snapshot : shadowSolidDraws) + { + snapshot.destroy(); + } + + shadowSolidDraws.clear(); + } + + if (!shadowTranslucentDraws.isEmpty()) + { + for (var snapshot : shadowTranslucentDraws) + { + snapshot.destroy(); + } + + shadowTranslucentDraws.clear(); + } + + // Flush instance counts, page mappings, and prune empty groups. + cullingGroups.values() + .removeIf(ClrwlIndirectCullingGroup::flushInstancers); + + // Instancers may have been emptied in the above call, now remove them here. + instancers.values() + .removeIf(instancer -> instancer.instanceCount() == 0); + + meshPool.flush(); + + setPhase(ClrwlRenderingPhase.STAGING_BUFFER_FLUSH, false); + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + stagingBuffer.reclaim(); + + // Genuinely nothing to do, we can just early out. + // Still process the mesh pool and reclaim fenced staging regions though. + if (cullingGroups.isEmpty()) + { + return; + } + + lightBuffers.flush(stagingBuffer, lightStorage); + matrixBuffer.flush(stagingBuffer, environmentStorage); + + for (var group : cullingGroups.values()) + { + group.upload(stagingBuffer); + } + + stagingBuffer.flush(); + + areModelInstanceCountsDirty = false; + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + setPhase(ClrwlRenderingPhase.INDIRECT_CULL_TRANSFORM, false); + + // Bounding spheres can be computed here because they are in world space + + ClrwlUniforms.bind(false); + + for (var group : cullingGroups.values()) + { + group.dispatchTransform(); + } + } + + public void preparePass(IrisRenderingPipeline pipeline, boolean isShadow) + { + if (cullingGroups.isEmpty()) + { + return; + } + + var pipelineData = getPipelineData(pipeline); + + for (var group : cullingGroups.values()) + { + pipelineData.getBuffers(group).updateCounts(); + } + + resetModelCountIfDirty(true); + + if (!useOcclusionCulling(isShadow)) + { + ClrwlUniforms.bind(isShadow); + computeFullCull(isShadow, ClrwlIndirectPrograms.Culling.MaterialFilter.ALL, false, pipelineData); + } + } + + private void dispatchCull(ClrwlIndirectPrograms.Culling culling, int materialFilter, PipelineData pipelineData) + { + setPhase(ClrwlRenderingPhase.INDIRECT_CULL, culling.programGroup() == ClrwlProgramGroup.SHADOW); + + var program = pipelineData.programs.getCullingProgram(culling); + + program.bind(); + program.setUInt("clrwl_materialFilter", materialFilter); + + for (var group : cullingGroups.values()) + { + if ((group.materialFilter() & materialFilter) == 0) + { + continue; + } + + pipelineData.getBuffers(group).bindForCull(culling.programGroup() == ClrwlProgramGroup.SHADOW); + group.dispatchCull(); + } + + areModelInstanceCountsDirty = true; + } + + private void dispatchApply(boolean isShadow) + { + setPhase(ClrwlRenderingPhase.INDIRECT_CULL_APPLY, isShadow); + + programs.getApplyProgram() + .bind(); + + for (var group : cullingGroups.values()) + { + group.dispatchApply(); + } + + hasInflightApply = true; + } + + private void dispatchModelReset() + { + setPhase(ClrwlRenderingPhase.INDIRECT_CULL_RESET, false); + + programs.getZeroModelsProgram() + .bind(); + + for (var group : cullingGroups.values()) + { + group.dispatchModelReset(); + } + } + + private void generateDepthPyramid(ClrwlDepthPyramid depthPyramid) + { + setPhase(ClrwlRenderingPhase.INDIRECT_DEPTH_PYRAMID, false); + depthPyramid.generate(); + } + + private void saveShadowDraws(List snapshots) + { + snapshots.clear(); + + for (var group : cullingGroups.values()) + { + snapshots.add(group.makeDrawSnapshot()); + } + } + + private void loadShadowDraws(List snapshots) + { + stagingBuffer.reclaim(); + + for (var snapshot : snapshots) + { + snapshot.applyAndConsume(stagingBuffer); + } + + stagingBuffer.flush(); + + snapshots.clear(); + + hasInflightApply = true; + } + + private void computeEarlyCull(boolean isShadow, PipelineData pipelineData) + { + ClrwlIndirectPrograms.Culling cullProgram = isShadow + ? ClrwlIndirectPrograms.Culling.SHADOW_EARLY + : ClrwlIndirectPrograms.Culling.GBUFFERS_EARLY; + + resetModelCountIfDirty(true); + + dispatchCull(cullProgram, ClrwlIndirectPrograms.Culling.MaterialFilter.SOLID, pipelineData); + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + dispatchApply(isShadow); + } + + private void computeLateCull(boolean isShadow, PipelineData pipelineData) + { + ClrwlIndirectPrograms.Culling cullProgram = isShadow + ? ClrwlIndirectPrograms.Culling.SHADOW_LATE + : ClrwlIndirectPrograms.Culling.GBUFFERS_LATE; + + var depthPyramid = pipelineData.depthPyramid(isShadow); + + resetModelCountIfDirty(false); + generateDepthPyramid(depthPyramid); + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + depthPyramid.bindForCull(); + dispatchCull(cullProgram, ClrwlIndirectPrograms.Culling.MaterialFilter.SOLID, pipelineData); + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + dispatchApply(isShadow); + } + + private void computeFullCull(boolean isShadow, int matFilter, boolean useOcclusion, PipelineData pipelineData) + { + ClrwlIndirectPrograms.Culling cullProgram = isShadow + ? ClrwlIndirectPrograms.Culling.SHADOW_FULL + : ClrwlIndirectPrograms.Culling.GBUFFERS_FULL; + + var depthPyramid = pipelineData.depthPyramid(isShadow); + + resetModelCountIfDirty(false); + + if (useOcclusion) + { + generateDepthPyramid(depthPyramid); + } + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + if (useOcclusion) + { + depthPyramid.bindForCull(); + } + + dispatchCull(cullProgram, matFilter, pipelineData); + + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + + dispatchApply(isShadow); + } + + private void resetModelCountIfDirty(boolean needsBarrier) + { + if (areModelInstanceCountsDirty) + { + dispatchModelReset(); + + if (needsBarrier) + { + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + } + + areModelInstanceCountsDirty = false; + } + } + + private void drawBarrierIfNeeded() + { + if (hasInflightApply) + { + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_COMMAND_BARRIER_BIT); + hasInflightApply = false; + } + } + + public void renderSolid(IrisRenderingPipeline irisPipeline, boolean isShadow) + { +top: { + for (var group : cullingGroups.values()) + { + if (group.hasSolidDraws()) + { + break top; + } + } + + return; + } + + var pipelineData = getPipelineData(irisPipeline); + + TextureBinder.bindLightAndOverlay(); + ClrwlUniforms.bind(isShadow); + vao.bindForDraw(); + lightBuffers.bind(); + matrixBuffer.bind(); + + + try + { + if (SHADOW_CULL_DEBUG && !isShadow) + { + loadShadowDraws(shadowSolidDraws); + } + else if (useTwoPassCulling(isShadow)) + { + computeEarlyCull(isShadow, pipelineData); + } + else if (useOcclusionCulling(isShadow)) + { + computeFullCull(isShadow, ClrwlIndirectPrograms.Culling.MaterialFilter.SOLID, true, pipelineData); + } + + dispatchSolidDraws(irisPipeline, isShadow, pipelineData); + + if (SHADOW_CULL_DEBUG && isShadow) + { + saveShadowDraws(shadowSolidDraws); + } + + if (useTwoPassCulling(isShadow) && LATE_CULL_ENABLED && !(SHADOW_CULL_DEBUG && !isShadow)) + { + computeLateCull(isShadow, pipelineData); + dispatchSolidDraws(irisPipeline, isShadow, pipelineData); + } + } + catch (Exception e) + { + Colorwheel.LOGGER.error("Got error while rendering solid instances", e); + } + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + } + + private void dispatchSolidDraws(IrisRenderingPipeline irisPipeline, boolean isShadow, PipelineData pipelineData) + { + var pipelinePrograms = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + + setPhase(ClrwlRenderingPhase.SOLID, isShadow); + + drawBarrierIfNeeded(); + + for (var group : cullingGroups.values()) + { + group.submitSolid(pipelinePrograms, framebuffers, isShadow); + } + } + + public void renderTranslucent(IrisRenderingPipeline irisPipeline, boolean isShadow) + { +top: { + for (var group : cullingGroups.values()) + { + if (group.hasTranslucentDraws() || group.hasOitDraws()) + { + break top; + } + } + + return; + } + + var pipelineData = getPipelineData(irisPipeline); + var pipelinePrograms = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + var program = !isShadow + ? ClrwlProgramId.GBUFFERS_TRANSLUCENT + : ClrwlProgramId.SHADOW_TRANSLUCENT; + + TextureBinder.bindLightAndOverlay(); + ClrwlUniforms.bind(isShadow); + vao.bindForDraw(); + lightBuffers.bind(); + matrixBuffer.bind(); + + + try + { + if (SHADOW_CULL_DEBUG && !isShadow) + { + loadShadowDraws(shadowTranslucentDraws); + } + else if (useOcclusionCulling(isShadow)) + { + computeFullCull(isShadow, ClrwlIndirectPrograms.Culling.MaterialFilter.TRANSLUCENT, true, pipelineData); + } + + if (SHADOW_CULL_DEBUG && isShadow) + { + saveShadowDraws(shadowTranslucentDraws); + } + + setPhase(ClrwlRenderingPhase.TRANSLUCENT, isShadow); + + drawBarrierIfNeeded(); + + boolean hasOit = false; + for (var group : cullingGroups.values()) + { + group.submitTranslucent(pipelinePrograms, framebuffers, isShadow); + + if (group.hasOitDraws()) + { + hasOit = true; + } + } + +top: if (hasOit) + { + var clrwlDirectives = programSet.getClrwlPrograms().getClrwlDirectives(); + var isOitEnabled = clrwlDirectives.getOitConfig(program.group()).enabled(); + + if (isOitEnabled) + { + var maybeSrc = programSet.getClrwlPrograms().getClrwlProgramSource(program); + + if (maybeSrc.isEmpty()) + { + break top; + } + + var framebuffer = framebuffers.getFramebuffer(program); + var directives = maybeSrc.get().getDirectives(); + var oitFramebuffer = framebuffers.getOitFramebuffers(program.group(), programs.getOitPrograms(), programSet, directives); + var blendOverride = framebuffers.getBlendModeOverride(program).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(program); + + if (framebuffer == null || oitFramebuffer == null) + { + break top; + } + + setPhase(ClrwlRenderingPhase.OIT_DEPTH_RANGE, isShadow); + + oitFramebuffer.prepare(); + + oitFramebuffer.prepareDepthRange(); + for (var group : cullingGroups.values()) + { + group.submitOit(ClrwlPrograms.OitMode.DEPTH_RANGE, pipelinePrograms, framebuffers, isShadow, currentRenderPhase); + } + + if (oitFramebuffer.prepareRenderTransmittance()) + { + setPhase(ClrwlRenderingPhase.OIT_COEFFICIENTS, isShadow); + + for (var group : cullingGroups.values()) + { + group.submitOit(ClrwlPrograms.OitMode.GENERATE_COEFFICIENTS, pipelinePrograms, framebuffers, isShadow, currentRenderPhase); + } + } + + // oitFramebuffer.renderDepthFromTransmittance(); + // + // // Need to bind this again because we just drew a full screen quad for OIT. + // vao.bindForDraw(); + + setPhase(ClrwlRenderingPhase.OIT_ACCUMULATE, isShadow); + + oitFramebuffer.prepareAccumulate(); + for (var group : cullingGroups.values()) + { + group.submitOit(ClrwlPrograms.OitMode.EVALUATE, pipelinePrograms, framebuffers, isShadow, currentRenderPhase); + } + + setPhase(ClrwlRenderingPhase.OIT_COMPOSITE, isShadow); + + oitFramebuffer.composite(framebuffer, blendOverride, bufferBlendOverrides, isShadow); + } + else + { + for (var group : cullingGroups.values()) + { + group.submitOitAsTranslucent(pipelinePrograms, framebuffers, isShadow); + } + } + } + } + catch (Exception e) + { + Colorwheel.LOGGER.error("Got error while rendering translucent instances", e); + } + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + } + + public void renderCrumbling(IrisRenderingPipeline irisPipeline, List crumblingBlocks) + { + var byType = doCrumblingSort(crumblingBlocks, ClrwlIndirectInstancer::fromState); + + if (byType.isEmpty()) + { + return; + } + + var pipelineData = getPipelineData(irisPipeline); + var programs = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + + var framebuffer = framebuffers.getFramebuffer(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK); + + if (framebuffer == null) + { + return; + } + + setPhase(ClrwlRenderingPhase.CRUMBLING, false); + + framebuffer.bind(); + + TextureBinder.bindLightAndOverlay(); + ClrwlUniforms.bind(false); + vao.bindForDraw(); + + var blendOverride = framebuffers.getBlendModeOverride(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK); + + + var crumblingMaterial = SimpleMaterial.builder(); + + // Scratch memory for writing draw commands. + var block = MemoryBlock.malloc(IndirectBuffers.DRAW_COMMAND_STRIDE); + + // Set up the crumbling program buffers. Nothing changes here between draws. + GlBufferType.DRAW_INDIRECT_BUFFER.bind(crumblingDrawBuffer.handle()); + glBindBufferRange(GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + ClrwlBufferBindings.DRAW, crumblingDrawBuffer.handle(), 0, ClrwlIndirectBuffers.DRAW_COMMAND_STRIDE); + + for (var groupEntry : byType.entrySet()) + { + var byProgress = groupEntry.getValue(); + + GroupKey groupKey = groupEntry.getKey(); + ClrwlIndirectCullingGroup cullingGroup = cullingGroups.get(groupKey.instanceType()); + + if (cullingGroup == null) + { + continue; + } + + for (var progressEntry : byProgress.int2ObjectEntrySet()) + { + Samplers.CRUMBLING.makeActive(); + TextureBinder.bind(ModelBakery.BREAKING_LOCATIONS.get(progressEntry.getIntKey())); + + for (var instanceHandlePair : progressEntry.getValue()) + { + ClrwlIndirectInstancer instancer = instanceHandlePair.getFirst(); + int instanceIndex = instanceHandlePair.getSecond().index; + + for (ClrwlIndirectDraw draw : instancer.draws()) + { + // Transform the material to be suited for crumbling. + CommonCrumbling.applyCrumblingProperties(crumblingMaterial, draw.material()); + + if (cullingGroup.bindForCrumbling(crumblingMaterial, programs, blendOverride)) + { + ClrwlMaterialRenderState.setup(crumblingMaterial, blendOverride, bufferBlendOverrides); + + // Upload the draw command. + draw.writeWithOverrides(block.ptr(), instanceIndex, crumblingMaterial); + crumblingDrawBuffer.upload(block); + + // Submit! Everything is already bound by here. + glDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, 0); + } + } + } + } + } + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + + block.free(); + } + + private boolean useOcclusionCulling(boolean isShadow) + { + var directives = programSet.getClrwlPrograms().getClrwlDirectives(); + var programGroup = ClrwlProgramGroup.fromShadow(isShadow); + + return directives.getOcclusionCulling(programGroup); + } + + private boolean useTwoPassCulling(boolean isShadow) + { + if (!TWO_PASS_CULL_ENABLED) + { + return false; + } + + var directives = programSet.getClrwlPrograms().getClrwlDirectives(); + var programGroup = ClrwlProgramGroup.fromShadow(isShadow); + + return directives.getOcclusionCulling(programGroup) && directives.getFrustumCulling(programGroup); + } + + private PipelineData getPipelineData(IrisRenderingPipeline pipeline) + { + deleteStalePipelinesData(pipeline); + return pipelineData.computeIfAbsent(pipeline, this::createPipelineData); + } + + private PipelineData createPipelineData(IrisRenderingPipeline irisPipeline) + { + ClrwlIndirectPrograms.PipelinePrograms pipelinePrograms = programs.createPipelinePrograms(irisPipeline); + ClrwlFramebuffers framebuffers = new ClrwlFramebuffers(irisPipeline, programSet); + ClrwlDepthPyramid depthPyramid = new ClrwlDepthPyramid(ClrwlProgramGroup.GBUFFERS, programs, irisPipeline); + ClrwlDepthPyramid shadowDepthPyramid = new ClrwlDepthPyramid(ClrwlProgramGroup.SHADOW, programs, irisPipeline); + + Colorwheel.LOGGER.info("Created pipeline data for {}", irisPipeline); + + return new PipelineData(pipelinePrograms, framebuffers, depthPyramid, shadowDepthPyramid, new HashMap<>()); + } + + // An engine only renders its own dimension, so a different pipeline means the old one was destroyed by a reload. + private void deleteStalePipelinesData(IrisRenderingPipeline current) + { + if (pipelineData.size() == 1 && pipelineData.containsKey(current)) + { + return; + } + + var it = pipelineData.entrySet().iterator(); + + while (it.hasNext()) + { + var entry = it.next(); + + if (entry.getKey() != current) + { + entry.getValue().delete(); + it.remove(); + Colorwheel.LOGGER.info("Deleted pipeline data for {}", entry.getKey()); + } + } + } + + private void deletePipelinesData() + { + for (var entry : pipelineData.entrySet()) + { + entry.getValue().delete(); + Colorwheel.LOGGER.info("Deleted pipeline data for {}", entry.getKey()); + } + + pipelineData.clear(); + } + + @Override + public void delete() + { + super.delete(); + + cullingGroups.values() + .forEach(ClrwlIndirectCullingGroup::delete); + cullingGroups.clear(); + + stagingBuffer.delete(); + + meshPool.delete(); + vao.delete(); + + crumblingDrawBuffer.delete(); + + lightBuffers.delete(); + matrixBuffer.delete(); + + deletePipelinesData(); + programs.delete(); + } + + @Override + public void triggerFallback() + { + ClrwlBackend.disableForCurrentPack(); + Minecraft.getInstance().levelRenderer.allChanged(); + } + + private static boolean TWO_PASS_CULL_ENABLED = true; + private static boolean LATE_CULL_ENABLED = true; + private static boolean SHADOW_CULL_DEBUG = false; + + public static void toggleTwoPassCull(boolean enabled) + { + TWO_PASS_CULL_ENABLED = enabled; + } + + public static void toggleLateCull(boolean enabled) + { + LATE_CULL_ENABLED = enabled; + } + + public static void toggleShadowCullDebug(boolean enabled) + { + SHADOW_CULL_DEBUG = enabled; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectInstancer.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectInstancer.java new file mode 100644 index 000000000..643e61a38 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlIndirectInstancer.java @@ -0,0 +1,685 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.compile.ClrwlIndirectPrograms; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlAbstractInstancer; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstanceHandle; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstancerKey; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceWriter; +import dev.engine_room.flywheel.backend.engine.indirect.ObjectStorage; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import dev.engine_room.flywheel.backend.util.AtomicBitSet; +import dev.engine_room.flywheel.lib.math.MoreMath; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.UnknownNullability; +import org.joml.Vector4fc; +import org.lwjgl.system.MemoryUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public class ClrwlIndirectInstancer extends ClrwlAbstractInstancer +{ + private final long instanceStride; + private final InstanceWriter writer; + private final List associatedDraws = new ArrayList<>(); + private final Vector4fc boundingSphere; + + private final AtomicReference[]> pages = new AtomicReference<>(pageArray(0)); + + private final AtomicInteger instanceCount = new AtomicInteger(0); + + /** + * The set of pages whose count changed and thus need their descriptor re-uploaded. + */ + private final AtomicBitSet validityChanged = new AtomicBitSet(); + /** + * The set of pages whose content changed and thus need their instances re-uploaded. + * Note that we don't re-upload for deletions, as the memory becomes invalid and masked out by the validity bits. + */ + private final AtomicBitSet contentsChanged = new AtomicBitSet(); + /** + * The set of pages that are entirely full. + * We scan the clear bits of this set when trying to add an instance. + */ + private final AtomicBitSet fullPages = new AtomicBitSet(); + /** + * The set of mergable pages. A page is mergeable if it is not empty and has 16 or fewer instances. + * These constraints are set so that we can guarantee that merging two pages leaves one entirely empty, + * but we also don't want to waste work merging into pages that are already empty. + */ + private final AtomicBitSet mergeablePages = new AtomicBitSet(); + + public ObjectStorage.@UnknownNullability Mapping mapping; + + private int modelIndex = -1; + private int baseInstance = -1; + + private final int entityId; + private final int blockEntityId; + private final int packedClrwlData; + + public ClrwlIndirectInstancer(ClrwlInstancerKey key, Recreate recreate) + { + super(key, recreate); + instanceStride = MoreMath.align4(type.layout() + .byteSize()); + writer = this.type.writer(); + boundingSphere = key.model().boundingSphere(); + + boolean hasSolidMesh = false; + boolean hasTranslucentMesh = false; + + for (var mesh : key.model().meshes()) + { + switch (mesh.material().transparency()) + { + case OPAQUE, ADDITIVE, LIGHTNING, GLINT -> hasSolidMesh = true; + case TRANSLUCENT, ORDER_INDEPENDENT -> hasTranslucentMesh = true; + case CRUMBLING -> {} + } + } + + entityId = visual.getEntity(); + blockEntityId = visual.getBlockEntity(); + + int packedClrwlData = visual.lightEmission() & 0b1111; + + if (hasSolidMesh) + { + packedClrwlData |= ClrwlIndirectPrograms.Culling.MaterialFilter.SOLID << 4; + } + + if (hasTranslucentMesh) + { + packedClrwlData |= ClrwlIndirectPrograms.Culling.MaterialFilter.TRANSLUCENT << 4; + } + + this.packedClrwlData = packedClrwlData; + } + + @SuppressWarnings("unchecked") + private static InstancePage[] pageArray(int length) + { + return new InstancePage[length]; + } + + @SuppressWarnings("unchecked") + private static I[] instanceArray() + { + return (I[]) new Instance[ObjectStorage.PAGE_SIZE]; + } + + @SuppressWarnings("unchecked") + private static ClrwlInstanceHandle[] handleArray() + { + return new ClrwlInstanceHandle[ObjectStorage.PAGE_SIZE]; + } + + @Nullable + public static ClrwlIndirectInstancer fromState(ClrwlInstanceHandle.State handle) + { + if (handle instanceof InstancePage instancer) + { + return instancer.parent; + } + return null; + } + + private static final class InstancePage implements ClrwlInstanceHandle.State + { + private final ClrwlIndirectInstancer parent; + private final int pageNo; + private final I[] instances; + // Handles are only read in #takeFrom. It would be nice to avoid tracking these at all. + private final ClrwlInstanceHandle[] handles; + /** + * A bitset describing which indices in the instances/handles arrays contain live instances. + */ + private final AtomicInteger valid; + + private InstancePage(ClrwlIndirectInstancer parent, int pageNo) + { + this.parent = parent; + this.pageNo = pageNo; + this.instances = instanceArray(); + this.handles = handleArray(); + this.valid = new AtomicInteger(0); + } + + /** + * Attempt to add the given instance/handle to this page. + * + * @param instance The instance to add + * @param handle The instance's handle + * @return true if the instance was added, false if the page is full + */ + public boolean add(I instance, ClrwlInstanceHandle handle) + { + // Thread safety: we loop until we either win the race and add the given instance, or we + // run out of space because other threads trying to add at the same time. + while (true) + { + int currentValue = valid.get(); + if (isFull(currentValue)) + { + // The page is full, must search elsewhere + return false; + } + + // determine what the new long value will be after we set the appropriate bit. + int index = Integer.numberOfTrailingZeros(~currentValue); + + int newValue = currentValue | (1 << index); + + // if no other thread has modified the value since we read it, we won the race and we are done. + if (valid.compareAndSet(currentValue, newValue)) + { + instances[index] = instance; + handles[index] = handle; + handle.state = this; + // Handle index is unique amongst all pages of this instancer. + handle.index = local2HandleIndex(index); + + parent.contentsChanged.set(pageNo); + parent.validityChanged.set(pageNo); + if (isFull(newValue)) + { + // The page is now full, mark it so in the bitset. + // This is safe because only one bit position changes at a time. + parent.fullPages.set(pageNo); + } + if (isMergeable(newValue)) + { + parent.mergeablePages.set(pageNo); + } + + parent.instanceCount.incrementAndGet(); + return true; + } + } + } + + private int local2HandleIndex(int index) + { + return (pageNo << ObjectStorage.LOG_2_PAGE_SIZE) + index; + } + + @Override + public ClrwlInstanceHandle.State setChanged(int index) + { + parent.contentsChanged.set(pageNo); + return this; + } + + @Override + public ClrwlInstanceHandle.State setDeleted(int index) + { + int localIndex = index % ObjectStorage.PAGE_SIZE; + + clear(localIndex); + + return ClrwlInstanceHandle.Deleted.instance(); + } + + @Override + public ClrwlInstanceHandle.State setVisible(ClrwlInstanceHandle handle, int index, boolean visible) + { + if (visible) + { + return this; + } + + int localIndex = index % ObjectStorage.PAGE_SIZE; + + var out = instances[localIndex]; + + clear(localIndex); + + return new ClrwlInstanceHandle.Hidden<>(parent.recreate, out); + } + + private void clear(int localIndex) + { + instances[localIndex] = null; + handles[localIndex] = null; + + while (true) + { + int currentValue = valid.get(); + int newValue = currentValue & ~(1 << localIndex); + + if (valid.compareAndSet(currentValue, newValue)) + { + parent.validityChanged.set(pageNo); + if (isMergeable(newValue)) + { + parent.mergeablePages.set(pageNo); + } + // Set full page last so that other threads don't race to set the other bitsets. + parent.fullPages.clear(pageNo); + parent.instanceCount.decrementAndGet(); + break; + } + } + } + + /** + * Only call this on 2 pages that are mergeable. + * + * @param other The page to take instances from. + */ + private void takeFrom(InstancePage other) + { + // Fill the holes in this page with instances from the other page. + + int valid = this.valid.get(); + + if (isFull(valid)) + { + // We got filled after being marked mergeable, nothing to do + parent.mergeablePages.clear(pageNo); + return; + } + + int otherValid = other.valid.get(); + + for (int i = 0; i < ObjectStorage.PAGE_SIZE; i++) + { + int mask = 1 << i; + + // Find set bits in the other page. + if ((otherValid & mask) == 0) + { + continue; + } + + int writePos = Integer.numberOfTrailingZeros(~valid); + + instances[writePos] = other.instances[i]; + handles[writePos] = other.handles[i]; + + handles[writePos].state = this; + handles[writePos].index = local2HandleIndex(writePos); + + // Clear out the other page. + otherValid &= ~mask; + other.handles[i] = null; + other.instances[i] = null; + + // Set the bit in this page so we can find the next write position. + valid |= 1 << writePos; + + // If we're full, we're done. + if (isFull(valid)) + { + break; + } + } + + this.valid.set(valid); + other.valid.set(otherValid); + + // If the other page was quite empty we may still be mergeable. + parent.mergeablePages.set(pageNo, isMergeable(valid)); + + // We definitely changed the contents and validity of this page. + parent.contentsChanged.set(pageNo); + parent.validityChanged.set(pageNo); + + // The other page will end up empty, so the validity changes and it's no longer mergeable. + // Also clear the changed bit so we don't re-upload the instances. + parent.contentsChanged.clear(other.pageNo); + parent.validityChanged.set(other.pageNo); + parent.mergeablePages.clear(other.pageNo); + + if (isFull(valid)) + { + parent.fullPages.set(pageNo); + } + } + } + + public void addDraw(ClrwlIndirectDraw draw) + { + associatedDraws.add(draw); + } + + public List draws() + { + return associatedDraws; + } + + public void update(int modelIndex, int baseInstance) + { + this.baseInstance = baseInstance; + + var sameModelIndex = this.modelIndex == modelIndex; + if (sameModelIndex && validityChanged.isEmpty()) + { + // Nothing to do! + return; + } + + this.modelIndex = modelIndex; + + var pages = this.pages.get(); + mapping.updateCount(pages.length); + + if (sameModelIndex) + { + // Only need to update the changed pages. + for (int page = validityChanged.nextSetBit(0); page >= 0 && page < pages.length; page = validityChanged.nextSetBit(page + 1)) + { + mapping.updatePage(page, modelIndex, pages[page].valid.get()); + } + } else + { + // Need to update all pages since the model index changed. + for (int i = 0; i < pages.length; i++) + { + mapping.updatePage(i, modelIndex, pages[i].valid.get()); + } + } + + validityChanged.clear(); + } + + public void writeModel(long ptr) + { + MemoryUtil.memPutInt(ptr, 0); // instanceCount - to be incremented by the cull shader + MemoryUtil.memPutInt(ptr + 4, baseInstance); // baseInstance + MemoryUtil.memPutInt(ptr + 8, environment.matrixIndex()); // matrixIndex + MemoryUtil.memPutFloat(ptr + 12, boundingSphere.x()); // boundingSphere + MemoryUtil.memPutFloat(ptr + 16, boundingSphere.y()); + MemoryUtil.memPutFloat(ptr + 20, boundingSphere.z()); + MemoryUtil.memPutFloat(ptr + 24, boundingSphere.w()); + + MemoryUtil.memPutInt(ptr + 28, entityId); + MemoryUtil.memPutInt(ptr + 32, blockEntityId); + MemoryUtil.memPutInt(ptr + 36, packedClrwlData); + } + + public void uploadInstances(StagingBuffer stagingBuffer, int instanceVbo) + { + if (contentsChanged.isEmpty()) + { + return; + } + + var pages = this.pages.get(); + for (int page = contentsChanged.nextSetBit(0); page >= 0 && page < pages.length; page = contentsChanged.nextSetBit(page + 1)) + { + var instances = pages[page].instances; + + long baseByte = mapping.page2ByteOffset(page); + + if (baseByte < 0) + { + // This page is not mapped to the VBO. + continue; + } + + long size = ObjectStorage.PAGE_SIZE * instanceStride; + + // Because writes are broken into pages, we end up with significantly more calls into + // StagingBuffer#enqueueCopy and the allocations for the writer got out of hand. Here + // we've inlined the enqueueCopy call and do not allocate the write lambda at all. + // Doing so cut upload times in half. + + // Try to write directly into the staging buffer if there is enough contiguous space. + long direct = stagingBuffer.reserveForCopy(size, instanceVbo, baseByte); + + if (direct != MemoryUtil.NULL) + { + for (I instance : instances) + { + if (instance != null) + { + writer.write(direct, instance); + } + direct += instanceStride; + } + continue; + } + + // Otherwise, write to a scratch buffer and enqueue a copy. + var block = stagingBuffer.getScratch(size); + var ptr = block.ptr(); + for (I instance : instances) + { + if (instance != null) + { + writer.write(ptr, instance); + } + ptr += instanceStride; + } + stagingBuffer.enqueueCopy(block.ptr(), size, instanceVbo, baseByte); + } + + contentsChanged.clear(); + } + + @Override + public void parallelUpdate() + { + var pages = this.pages.get(); + + // Clear the tail so we don't have to worry about out of bounds access. + mergeablePages.clear(pages.length, mergeablePages.currentCapacity()); + + int page = 0; + while (mergeablePages.cardinality() > 1) + { + page = mergeablePages.nextSetBit(page); + if (page < 0) + { + break; + } + + // Find the next mergeable page. + int next = mergeablePages.nextSetBit(page + 1); + if (next < 0) + { + break; + } + + // Try to merge the pages. + pages[page].takeFrom(pages[next]); + } + } + + private static boolean isFull(int valid) + { + return valid == 0xFFFFFFFF; + } + + private static boolean isEmpty(int valid) + { + return valid == 0; + } + + private static boolean isMergeable(int valid) + { + return !isEmpty(valid) && Integer.bitCount(valid) <= 16; + } + + @Override + public void delete() + { + for (ClrwlIndirectDraw draw : draws()) + { + draw.delete(); + } + + mapping.delete(); + } + + public int modelIndex() + { + return modelIndex; + } + + public int baseInstance() + { + return baseInstance; + } + + public int local2GlobalInstanceIndex(int instanceIndex) + { + return mapping.objectIndex2GlobalIndex(instanceIndex); + } + + @Override + public I createInstance() + { + var handle = new ClrwlInstanceHandle(null); + I instance = type.create(handle); + + addInner(instance, handle); + + return instance; + } + + public ClrwlInstanceHandle.State revealInstance(ClrwlInstanceHandle handle, I instance) + { + addInner(instance, handle); + return handle.state; + } + + @Override + public void stealInstance(@Nullable I instance) + { + if (instance == null) + { + return; + } + + var instanceHandle = instance.handle(); + + if (!(instanceHandle instanceof ClrwlInstanceHandle)) + { + // UB: do nothing + return; + } + + // Should InstanceType have an isInstance method? + @SuppressWarnings("unchecked") var handle = (ClrwlInstanceHandle) instanceHandle; + + // Not allowed to steal deleted instances. + if (handle.state instanceof ClrwlInstanceHandle.Deleted) + { + return; + } + // No need to steal if the instance will recreate to us. + if (handle.state instanceof ClrwlInstanceHandle.Hidden hidden && recreate.equals(hidden.recreate())) + { + return; + } + + // FIXME: in theory there could be a race condition here if the instance + // is somehow being stolen by 2 different instancers between threads. + // That seems kinda impossible so I'm fine leaving it as is for now. + + // Add the instance to this instancer. + if (handle.state instanceof InstancePage other) + { + if (other.parent == this) + { + return; + } + + // Remove the instance from its old instancer. + // This won't have any unwanted effect when the old instancer + // is filtering deleted instances later, so is safe. + other.setDeleted(handle.index); + + // Only lock now that we'll be mutating our state. + addInner(instance, handle); + } + else if (handle.state instanceof ClrwlInstanceHandle.Hidden) + { + handle.state = new ClrwlInstanceHandle.Hidden<>(recreate, instance); + } + } + + private void addInner(I instance, ClrwlInstanceHandle handle) + { + // Outer loop: + // - try to find an empty space + // - or grow the page array if we can't + // - add the instance to the new page, or try again + while (true) + { + var pages = this.pages.get(); + + // First, try to find a page with space. + for (int i = fullPages.nextClearBit(0); i < pages.length; i = fullPages.nextClearBit(i + 1)) + { + // It may have been filled in while we were searching, but hopefully not. + if (pages[i].add(instance, handle)) + { + return; + } + } + + // If we're here, all other pages are full + // If we hit this on the second iteration of the outer loop then `pages` is once again full. + var desiredLength = pages.length + 1; + + // Inner loop: grow the page array. This is very similar to the logic in AtomicBitSet. + while (pages.length < desiredLength) + { + // Thread safety: segments contains all pages from the currently visible pages, plus extra. + // all pages in the currently visible pages are canonical and will not change. + // Can't just `new InstancePage[]` because it has a generic parameter. + InstancePage[] newPages = pageArray(desiredLength); + + System.arraycopy(pages, 0, newPages, 0, pages.length); + newPages[pages.length] = new InstancePage<>(this, pages.length); + + // because we are using a compareAndSet, if this thread "wins the race" and successfully sets this variable, then the new page becomes canonical. + if (this.pages.compareAndSet(pages, newPages)) + { + pages = newPages; + } + else + { + // If we "lose the race" and are growing the AtomicBitset segments larger, + // then we will gather the new canonical pages from the update which we missed on the next iteration of this loop. + // The new page will be discarded and never seen again. + pages = this.pages.get(); + } + } + + // Shortcut: try to add the instance to the last page. + // Technically we could just let the outer loop go again, but that + // involves a good bit of work just to likely get back here. + if (pages[pages.length - 1].add(instance, handle)) + { + return; + } + // It may be the case that many other instances were added in the same instant. + // We can still lose this race, though it is very unlikely. + } + } + + public int instanceCount() + { + return instanceCount.get(); + } + + /** + * Clear all instances without freeing resources. + */ + public void clear() + { + this.pages.set(pageArray(0)); + contentsChanged.clear(); + validityChanged.clear(); + fullPages.clear(); + mergeablePages.clear(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlLightBuffers.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlLightBuffers.java new file mode 100644 index 000000000..5b9ac243e --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlLightBuffers.java @@ -0,0 +1,58 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import dev.engine_room.flywheel.backend.engine.LightStorage; +import dev.engine_room.flywheel.backend.engine.indirect.ResizableStorageArray; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import org.lwjgl.opengl.GL46; +import org.lwjgl.system.MemoryUtil; + +public class ClrwlLightBuffers +{ + private final ResizableStorageArray lut = new ResizableStorageArray(4); + private final ResizableStorageArray sections = new ResizableStorageArray(LightStorage.SECTION_SIZE_BYTES); + + public void flush(StagingBuffer staging, LightStorage light) + { + var capacity = light.capacity(); + + if (capacity == 0) + { + return; + } + + sections.ensureCapacity(capacity); + light.uploadChangedSections(staging, sections.handle()); + + if (light.checkNeedsLutRebuildAndClear()) + { + var lut = light.createLut(); + + this.lut.ensureCapacity(lut.size()); + + staging.enqueueCopy((long) lut.size() * Integer.BYTES, this.lut.handle(), 0, ptr -> + { + for (int i = 0; i < lut.size(); i++) + { + MemoryUtil.memPutInt(ptr + (long) i * Integer.BYTES, lut.getInt(i)); + } + }); + } + } + + public void bind() + { + if (sections.capacity() == 0) + { + return; + } + + GL46.glBindBufferRange(GL46.GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + ClrwlBufferBindings.LIGHT_LUT, lut.handle(), 0, lut.byteCapacity()); + GL46.glBindBufferRange(GL46.GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + ClrwlBufferBindings.LIGHT_SECTION, sections.handle(), 0, sections.byteCapacity()); + } + + public void delete() + { + lut.delete(); + sections.delete(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlMatrixBuffer.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlMatrixBuffer.java new file mode 100644 index 000000000..392dbbb68 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/indirect/ClrwlMatrixBuffer.java @@ -0,0 +1,50 @@ +package net.irisshaders.iris.compat.flywheel.indirect; + +import net.irisshaders.iris.compat.flywheel.engine.embed.EnvironmentStorage; +import dev.engine_room.flywheel.backend.engine.indirect.ResizableStorageArray; +import dev.engine_room.flywheel.backend.engine.indirect.StagingBuffer; +import org.lwjgl.opengl.GL46; +import org.lwjgl.system.MemoryUtil; + +public class ClrwlMatrixBuffer +{ + private final ResizableStorageArray matrices; + + public ClrwlMatrixBuffer() + { + this.matrices = new ResizableStorageArray(EnvironmentStorage.MATRIX_SIZE_BYTES); + } + + public void flush(StagingBuffer stagingBuffer, EnvironmentStorage environmentStorage) + { + var arena = environmentStorage.arena; + var capacity = arena.capacity(); + + if (capacity == 0) + { + return; + } + + matrices.ensureCapacity(capacity); + + stagingBuffer.enqueueCopy(arena.byteCapacity(), matrices.handle(), 0, ptr -> + { + MemoryUtil.memCopy(arena.indexToPointer(0), ptr, arena.byteCapacity()); + }); + } + + public void bind() + { + if (matrices.capacity() == 0) + { + return; + } + + GL46.glBindBufferRange(GL46.GL_SHADER_STORAGE_BUFFER, ClrwlBufferBindings.base() + ClrwlBufferBindings.MATRICES, matrices.handle(), 0, matrices.byteCapacity()); + } + + public void delete() + { + matrices.delete(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDraw.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDraw.java new file mode 100644 index 000000000..f311eca6b --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDraw.java @@ -0,0 +1,82 @@ +package net.irisshaders.iris.compat.flywheel.instancing; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstanceVisual; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlMeshPool; +import dev.engine_room.flywheel.api.material.Material; +import dev.engine_room.flywheel.backend.engine.GroupKey; +import dev.engine_room.flywheel.backend.gl.TextureBuffer; + +public class ClrwlInstancedDraw +{ + public final GroupKey groupKey; + private final ClrwlInstancedInstancer instancer; + private final ClrwlMeshPool.PooledMesh mesh; + private final Material material; + private final int bias; + private final int indexOfMeshInModel; + + private boolean deleted; + + public ClrwlInstancedDraw(ClrwlInstancedInstancer instancer, ClrwlMeshPool.PooledMesh mesh, GroupKey groupKey, Material material, int bias, int indexOfMeshInModel) { + this.instancer = instancer; + this.mesh = mesh; + this.groupKey = groupKey; + this.material = material; + this.bias = bias; + this.indexOfMeshInModel = indexOfMeshInModel; + + mesh.acquire(); + } + + public ClrwlInstanceVisual visual() { return instancer.visual; } + + public int bias() { + return bias; + } + + public int indexOfMeshInModel() { + return indexOfMeshInModel; + } + + public Material material() { + return material; + } + + public boolean deleted() { + return deleted; + } + + public ClrwlMeshPool.PooledMesh mesh() { + return mesh; + } + + public void render(TextureBuffer buffer) { + if (mesh.isInvalid()) { + return; + } + + instancer.bind(buffer); + + mesh.draw(instancer.instanceCount()); + } + + public void renderOne(TextureBuffer buffer) { + if (mesh.isInvalid()) { + return; + } + + instancer.bind(buffer); + + mesh.draw(1); + } + + public void delete() { + if (deleted) { + return; + } + + mesh.release(); + + deleted = true; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDrawManager.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDrawManager.java new file mode 100644 index 000000000..c89c3779f --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedDrawManager.java @@ -0,0 +1,608 @@ +package net.irisshaders.iris.compat.flywheel.instancing; + +import net.irisshaders.iris.compat.flywheel.ClrwlBackend; +import net.irisshaders.iris.compat.flywheel.ClrwlSamplers; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlInstancedPrograms; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlProgram; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlPrograms; +import net.irisshaders.iris.compat.flywheel.compile.ClrwlShaderKey; +import net.irisshaders.iris.compat.flywheel.engine.*; +import net.irisshaders.iris.compat.flywheel.engine.embed.EnvironmentStorage; +import net.irisshaders.iris.compat.flywheel.engine.uniform.ClrwlUniforms; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; +import dev.engine_room.flywheel.api.backend.Engine; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.material.Transparency; +import dev.engine_room.flywheel.backend.Samplers; +import dev.engine_room.flywheel.backend.compile.ContextShader; +import dev.engine_room.flywheel.backend.engine.*; +import dev.engine_room.flywheel.backend.engine.instancing.InstancedLight; +import dev.engine_room.flywheel.backend.gl.TextureBuffer; +import dev.engine_room.flywheel.backend.gl.array.GlVertexArray; +import dev.engine_room.flywheel.backend.glsl.ShaderSources; +import dev.engine_room.flywheel.lib.material.SimpleMaterial; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.model.ModelBakery; + +import java.util.*; + +public class ClrwlInstancedDrawManager extends ClrwlDrawManager> +{ + public record PipelineData(ClrwlInstancedPrograms.PipelinePrograms programs, ClrwlFramebuffers framebuffers) + { + public void delete() + { + programs.delete(); + framebuffers.delete(); + } + } + + private static final Comparator DRAW_COMPARATOR = Comparator.comparing(ClrwlInstancedDraw::bias) + .thenComparing(ClrwlInstancedDraw::indexOfMeshInModel) + .thenComparing(ClrwlInstancedDraw::material, MaterialRenderState.COMPARATOR); + + private final List allDraws = new ArrayList<>(); + private boolean needSort = false; + + private final List solidDraws = new ArrayList<>(); + private final List translucentDraws = new ArrayList<>(); + private final List oitDraws = new ArrayList<>(); + + private final Map pipelineData = new HashMap<>(); + + /** + * A map of vertex types to their mesh pools. + */ + private final ClrwlInstancedPrograms programs; + private final ClrwlMeshPool meshPool; + private final GlVertexArray vao; + private final TextureBuffer instanceTexture; + private final InstancedLight light; + + private final ShaderPack pack; + private final ProgramSet programSet; + + public ClrwlInstancedDrawManager(ShaderPack pack, ProgramSet programSet, ClrwlInstancedPrograms programs) + { + this.pack = pack; + this.programSet = programSet; + + this.programs = programs; + this.meshPool = new ClrwlMeshPool(); + this.vao = GlVertexArray.create(); + this.instanceTexture = new TextureBuffer(); + this.light = new InstancedLight(); + + this.meshPool.bind(vao); + } + + public static ClrwlInstancedDrawManager build(ShaderSources sources, ShaderPack pack, ProgramSet programSet, boolean isFallback) + { + var programs = ClrwlInstancedPrograms.build(sources, pack, programSet, isFallback); + return new ClrwlInstancedDrawManager(pack, programSet, programs); + } + + @Override + public void prepareFrame(LightStorage lightStorage, EnvironmentStorage environmentStorage) + { + super.prepareFrame(lightStorage, environmentStorage); + + this.instancers.values() + .removeIf(instancer -> + { + if (instancer.instanceCount() == 0) + { + instancer.delete(); + return true; + } + else + { + instancer.updateBuffer(); + return false; + } + }); + + // Remove the draw calls for any instancers we deleted. + needSort |= allDraws.removeIf(ClrwlInstancedDraw::deleted); + + if (needSort) + { + allDraws.sort(DRAW_COMPARATOR); + + solidDraws.clear(); + translucentDraws.clear(); + oitDraws.clear(); + + for (var draw : allDraws) + { + if (draw.material().transparency() == Transparency.TRANSLUCENT) + { + translucentDraws.add(draw); + } + else if (draw.material().transparency() == Transparency.ORDER_INDEPENDENT) + { + oitDraws.add(draw); + } + else + { + solidDraws.add(draw); + } + } + + needSort = false; + } + + meshPool.flush(); + + light.flush(lightStorage); + } + + public void preparePass(IrisRenderingPipeline pipeline, boolean isShadow) + { + } + + public void renderSolid(IrisRenderingPipeline irisPipeline, boolean isShadow) + { + if (solidDraws.isEmpty()) + { + return; + } + + if (isShadow && programSet.getClrwlPrograms().getClrwlProgramSource(ClrwlProgramId.SHADOW).isEmpty()) + { + // No base shadow shader, skip + return; + } + + var pipelineData = getPipelineData(irisPipeline); + setPhase(ClrwlRenderingPhase.SOLID, isShadow); + + ClrwlUniforms.bind(isShadow); + vao.bindForDraw(); + TextureBinder.bindLightAndOverlay(); + light.bind(); + + submitDraws(solidDraws, pipelineData, isShadow); + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + } + + public void renderTranslucent(IrisRenderingPipeline irisPipeline, boolean isShadow) + { + if (translucentDraws.isEmpty() && oitDraws.isEmpty()) + { + return; + } + + var pipelineData = getPipelineData(irisPipeline); + var framebuffers = pipelineData.framebuffers(); + + setPhase(ClrwlRenderingPhase.TRANSLUCENT, isShadow); + + ClrwlUniforms.bind(isShadow); + vao.bindForDraw(); + TextureBinder.bindLightAndOverlay(); + light.bind(); + + if (!translucentDraws.isEmpty()) + { + submitDraws(translucentDraws, pipelineData, isShadow); + } + +top: if (!oitDraws.isEmpty()) + { + var program = !isShadow + ? ClrwlProgramId.GBUFFERS_TRANSLUCENT + : ClrwlProgramId.SHADOW_TRANSLUCENT; + + var clrwlDirectives = programSet.getClrwlPrograms().getClrwlDirectives(); + var isOitEnabled = clrwlDirectives.getOitConfig(program.group()).enabled(); + + if (isOitEnabled) + { + var maybeSrc = programSet.getClrwlPrograms().getClrwlProgramSource(program); + + if (maybeSrc.isEmpty()) + { + break top; + } + + var directives = maybeSrc.get().getDirectives(); + + var framebuffer = framebuffers.getFramebuffer(program); + var oitFramebuffer = framebuffers.getOitFramebuffers(program.group(), programs.getOitPrograms(), programSet, directives); + var blendOverride = framebuffers.getBlendModeOverride(program).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(program); + + if (framebuffer == null || oitFramebuffer == null) + { + break top; + } + + setPhase(ClrwlRenderingPhase.OIT_DEPTH_RANGE, isShadow); + + oitFramebuffer.prepare(); + + oitFramebuffer.prepareDepthRange(); + submitOitDraws(pipelineData, isShadow, ClrwlPrograms.OitMode.DEPTH_RANGE); + + setPhase(ClrwlRenderingPhase.OIT_COEFFICIENTS, isShadow); + + if (oitFramebuffer.prepareRenderTransmittance()) + { + submitOitDraws(pipelineData, isShadow, ClrwlPrograms.OitMode.GENERATE_COEFFICIENTS); + } + +// oitFramebuffer.renderDepthFromTransmittance(); +// +// // Need to bind this again because we just drew a full screen quad for OIT. +// vao.bindForDraw(); + + setPhase(ClrwlRenderingPhase.OIT_ACCUMULATE, isShadow); + + oitFramebuffer.prepareAccumulate(); + submitOitDraws(pipelineData, isShadow, ClrwlPrograms.OitMode.EVALUATE); + + setPhase(ClrwlRenderingPhase.OIT_COMPOSITE, isShadow); + + oitFramebuffer.composite(framebuffer, blendOverride, bufferBlendOverrides, isShadow); + } + else + { + setPhase(ClrwlRenderingPhase.TRANSLUCENT, isShadow); + submitDraws(oitDraws, pipelineData, isShadow); + } + } + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + } + + private void submitDraws(List draws, PipelineData pipelineData, boolean isShadow) + { + var programs = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + + GlFramebuffer prevFramebuffer = null; + ClrwlProgram prevProgram = null; + + for (var drawCall : draws) + { + var material = drawCall.material(); + var groupKey = drawCall.groupKey; + var environment = groupKey.environment(); + + var key = ClrwlShaderKey.fromMaterial(groupKey.instanceType(), material, environment.contextShader(), isShadow, ClrwlPrograms.OitMode.OFF); + var program = programs.get(key); + + if (program == null) + { + continue; + } + + var programId = ClrwlProgramId.fromTransparency(material.transparency(), isShadow); + var framebuffer = framebuffers.getFramebuffer(programId); + + if (framebuffer == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + var blendOverride = framebuffers.getBlendModeOverride(programId).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(programId); + + program.setClrwlCommonUniforms(material, blendOverride, currentRenderPhase); + program.setInstancingUniforms(drawCall.mesh().baseVertex(), 0, material, drawCall.visual(), drawCall.mesh().meshCenter()); + environment.setupDraw(program); + ClrwlMaterialRenderState.setup(material, blendOverride, bufferBlendOverrides); + + ClrwlSamplers.INSTANCE_BUFFER.makeActive(); + + if (prevFramebuffer != framebuffer) + { + prevFramebuffer = framebuffer; + framebuffer.bind(); + } + + drawCall.render(instanceTexture); + + prevProgram = program; + } + + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + } + + private void submitOitDraws(PipelineData pipelineData, boolean isShadow, ClrwlPrograms.OitMode oit) + { + var programs = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + + var programId = isShadow ? ClrwlProgramId.SHADOW_TRANSLUCENT : ClrwlProgramId.GBUFFERS_TRANSLUCENT; + var blendOverride = framebuffers.getBlendModeOverride(programId).orElse(null); + + ClrwlProgram prevProgram = null; + + for (var drawCall : oitDraws) + { + var material = drawCall.material(); + var groupKey = drawCall.groupKey; + var environment = groupKey.environment(); + + var key = ClrwlShaderKey.fromMaterial(groupKey.instanceType(), material, environment.contextShader(), isShadow, oit); + var program = programs.get(key); + + if (program == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + program.setClrwlCommonUniforms(material, blendOverride, currentRenderPhase); + program.setInstancingUniforms(drawCall.mesh().baseVertex(), 0, material, drawCall.visual(), drawCall.mesh().meshCenter()); + environment.setupDraw(program); + ClrwlMaterialRenderState.setupOit(material); + + Samplers.INSTANCE_BUFFER.makeActive(); + + drawCall.render(instanceTexture); + + prevProgram = program; + } + + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + } + + public void renderCrumbling(IrisRenderingPipeline irisPipeline, List crumblingBlocks) + { + var pipelineData = getPipelineData(irisPipeline); + var programs = pipelineData.programs(); + var framebuffers = pipelineData.framebuffers(); + + var isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); + ClrwlProgram prevProgram = null; + + if (isShadow) + { + return; + } + + // Sort draw calls into buckets, so we don't have to do as many shader binds. + var byType = doCrumblingSort(crumblingBlocks, handle -> + { + // AbstractInstancer directly implement HandleState, so this check is valid. + if (handle instanceof ClrwlInstancedInstancer instancer) + { + return instancer; + } + // This rejects instances that were created by a different engine, + // and also instances that are hidden or deleted. + return null; + }); + + if (byType.isEmpty()) + { + return; + } + + var framebuffer = framebuffers.getFramebuffer(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK); + + if (framebuffer == null) + { + return; + } + + setPhase(ClrwlRenderingPhase.CRUMBLING, false); + + framebuffer.bind(); + + ClrwlUniforms.bind(false); + vao.bindForDraw(); + TextureBinder.bindLightAndOverlay(); + + var blendOverride = framebuffers.getBlendModeOverride(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK).orElse(null); + var bufferBlendOverrides = framebuffers.getBufferBlendModeOverrides(ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK); + + var crumblingMaterial = SimpleMaterial.builder(); + + for (var groupEntry : byType.entrySet()) + { + var byProgress = groupEntry.getValue(); + + GroupKey key = groupEntry.getKey(); + + for (var progressEntry : byProgress.int2ObjectEntrySet()) + { + Samplers.CRUMBLING.makeActive(); + TextureBinder.bind(ModelBakery.BREAKING_LOCATIONS.get(progressEntry.getIntKey())); + + for (var instanceHandlePair : progressEntry.getValue()) + { + ClrwlInstancedInstancer instancer = instanceHandlePair.getFirst(); + var index = instanceHandlePair.getSecond().index; + + for (ClrwlInstancedDraw draw : instancer.draws()) + { + CommonCrumbling.applyCrumblingProperties(crumblingMaterial, draw.material()); + + var shaderKey = ClrwlShaderKey.fromMaterial(key.instanceType(), crumblingMaterial, ContextShader.CRUMBLING, false, ClrwlPrograms.OitMode.OFF); + var program = programs.get(shaderKey); + + if (program == null) + { + continue; + } + + if (prevProgram != program) + { + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + program.bind(); + } + + program.setClrwlCommonUniforms(crumblingMaterial, blendOverride, currentRenderPhase); + program.setInstancingUniforms(0, index, crumblingMaterial, draw.visual(), draw.mesh().meshCenter()); + ClrwlMaterialRenderState.setup(crumblingMaterial, blendOverride, bufferBlendOverrides); + + Samplers.INSTANCE_BUFFER.makeActive(); + + draw.renderOne(instanceTexture); + + prevProgram = program; + } + } + } + } + + if (prevProgram != null) + { + ClrwlProgram.unbind(); + } + + ClrwlMaterialRenderState.reset(); + TextureBinder.resetLightAndOverlay(); + } + + private PipelineData getPipelineData(IrisRenderingPipeline pipeline) + { + deleteStalePipelinesData(pipeline); + return pipelineData.computeIfAbsent(pipeline, this::createPipelineData); + } + + private PipelineData createPipelineData(IrisRenderingPipeline irisPipeline) + { + var pipelinePrograms = programs.createPipelinePrograms(irisPipeline); + var framebuffers = new ClrwlFramebuffers(irisPipeline, programSet); + + Colorwheel.LOGGER.info("Created pipeline data for {}", irisPipeline); + + return new PipelineData(pipelinePrograms, framebuffers); + } + + // An engine only renders its own dimension, so a different pipeline means the old one was destroyed by a reload. + private void deleteStalePipelinesData(IrisRenderingPipeline current) + { + if (pipelineData.size() == 1 && pipelineData.containsKey(current)) + { + return; + } + + var it = pipelineData.entrySet().iterator(); + + while (it.hasNext()) + { + var entry = it.next(); + + if (entry.getKey() != current) + { + entry.getValue().delete(); + it.remove(); + Colorwheel.LOGGER.info("Deleted pipeline data for {}", entry.getKey()); + } + } + } + + private void deletePipelinesData() + { + for (var entry : pipelineData.entrySet()) + { + entry.getValue().delete(); + Colorwheel.LOGGER.info("Deleted pipeline data for {}", entry.getKey()); + } + + pipelineData.clear(); + } + + @Override + public void delete() + { + instancers.values() + .forEach(ClrwlInstancedInstancer::delete); + + solidDraws.clear(); + translucentDraws.clear(); + oitDraws.clear(); + + allDraws.forEach(ClrwlInstancedDraw::delete); + allDraws.clear(); + + meshPool.delete(); + instanceTexture.delete(); + vao.delete(); + + light.delete(); + + deletePipelinesData(); + programs.delete(); + + super.delete(); + } + + @Override + protected ClrwlInstancedInstancer create(ClrwlInstancerKey key) + { + return new ClrwlInstancedInstancer<>(key, new ClrwlAbstractInstancer.Recreate<>(key, this)); + } + + @Override + protected void initialize(ClrwlInstancerKey key, ClrwlInstancedInstancer instancer) + { + instancer.init(); + + var meshes = key.model() + .meshes(); + for (int i = 0; i < meshes.size(); i++) + { + var entry = meshes.get(i); + var mesh = meshPool.alloc(entry.mesh()); + + GroupKey groupKey = new GroupKey<>(key.type(), key.environment()); + ClrwlInstancedDraw instancedDraw = new ClrwlInstancedDraw(instancer, mesh, groupKey, entry.material(), key.bias(), i); + + allDraws.add(instancedDraw); + needSort = true; + instancer.addDrawCall(instancedDraw); + } + } + + @Override + public void triggerFallback() + { + ClrwlBackend.disableForCurrentPack(); + Minecraft.getInstance().levelRenderer.allChanged(); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedInstancer.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedInstancer.java new file mode 100644 index 000000000..ee9661d5d --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/instancing/ClrwlInstancedInstancer.java @@ -0,0 +1,189 @@ +package net.irisshaders.iris.compat.flywheel.instancing; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlBaseInstancer; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlInstancerKey; +import dev.engine_room.flywheel.api.instance.Instance; +import dev.engine_room.flywheel.api.instance.InstanceWriter; +import dev.engine_room.flywheel.backend.gl.TextureBuffer; +import dev.engine_room.flywheel.backend.gl.buffer.GlBuffer; +import dev.engine_room.flywheel.backend.gl.buffer.GlBufferUsage; +import dev.engine_room.flywheel.lib.math.MoreMath; +import dev.engine_room.flywheel.lib.memory.MemoryBlock; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +public class ClrwlInstancedInstancer extends ClrwlBaseInstancer +{ + private final int instanceStride; + + private final InstanceWriter writer; + @Nullable + private GlBuffer vbo; + + private final List draws = new ArrayList<>(); + + public ClrwlInstancedInstancer(ClrwlInstancerKey key, ClrwlBaseInstancer.Recreate recreate) { + super(key, recreate); + var layout = type.layout(); + // Align to one texel in the texture buffer + instanceStride = MoreMath.align16(layout.byteSize()); + writer = type.writer(); + } + + public List draws() { + return draws; + } + + public void init() { + if (vbo != null) { + return; + } + + vbo = new GlBuffer(GlBufferUsage.DYNAMIC_DRAW); + } + + public void updateBuffer() { + if (changed.isEmpty() || vbo == null) { + return; + } + + int byteSize = instanceStride * instances.size(); + if (needsToGrow(byteSize)) { + // TODO: Should this memory block be persistent? + var temp = MemoryBlock.malloc(increaseSize(byteSize)); + + writeAll(temp.ptr()); + + vbo.upload(temp); + + temp.free(); + } else { + writeChanged(); + } + + changed.clear(); + } + + private void writeChanged() { + changed.forEachSetSpan((startInclusive, endInclusive) -> { + // Generally we're good about ensuring we don't have changed bits set out of bounds, but check just in case + if (startInclusive >= instances.size()) { + return; + } + int actualEnd = Math.min(endInclusive, instances.size() - 1); + var temp = MemoryBlock.malloc((long) instanceStride * (actualEnd - startInclusive + 1)); + long ptr = temp.ptr(); + for (int i = startInclusive; i <= actualEnd; i++) { + writer.write(ptr, instances.get(i)); + ptr += instanceStride; + } + + vbo.uploadSpan((long) startInclusive * instanceStride, temp); + + temp.free(); + }); + } + + private void writeAll(long ptr) { + for (I instance : instances) { + writer.write(ptr, instance); + ptr += instanceStride; + } + } + + private long increaseSize(long capacity) { + return Math.max(capacity + (long) instanceStride * 16, (long) (capacity * 1.6)); + } + + public boolean needsToGrow(long capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("Size " + capacity + " < 0"); + } + + if (capacity == 0) { + return false; + } + + return capacity > vbo.size(); + } + + public void parallelUpdate() { + if (deleted.isEmpty()) { + return; + } + + // Figure out which elements are to be removed. + final int oldSize = this.instances.size(); + int removeCount = deleted.cardinality(); + + if (oldSize == removeCount) { + clear(); + return; + } + + final int newSize = oldSize - removeCount; + + // Start from the first deleted index. + int writePos = deleted.nextSetBit(0); + + if (writePos < newSize) { + // Since we'll be shifting everything into this space we can consider it all changed. + changed.set(writePos, newSize); + } + + // We definitely shouldn't consider the deleted instances as changed though, + // else we might try some out of bounds accesses later. + changed.clear(newSize, oldSize); + + // Punch out the deleted instances, shifting over surviving instances to fill their place. + for (int scanPos = writePos; (scanPos < oldSize) && (writePos < newSize); scanPos++, writePos++) { + // Find next non-deleted element. + scanPos = deleted.nextClearBit(scanPos); + + if (scanPos != writePos) { + // Grab the old instance/handle from scanPos... + var handle = handles.get(scanPos); + I instance = instances.get(scanPos); + + // ... and move it to writePos. + handles.set(writePos, handle); + instances.set(writePos, instance); + + // Make sure the handle knows it's been moved + handle.index = writePos; + } + } + + deleted.clear(); + instances.subList(newSize, oldSize) + .clear(); + handles.subList(newSize, oldSize) + .clear(); + } + + public void delete() { + if (vbo == null) { + return; + } + vbo.delete(); + vbo = null; + + for (ClrwlInstancedDraw instancedDraw : draws) { + instancedDraw.delete(); + } + } + + public void addDrawCall(ClrwlInstancedDraw instancedDraw) { + draws.add(instancedDraw); + } + + public void bind(TextureBuffer buffer) { + if (vbo == null) { + return; + } + + buffer.bind(vbo.handle()); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/BlockEntityStorageMixin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/BlockEntityStorageMixin.java new file mode 100644 index 000000000..4ab3cef9a --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/BlockEntityStorageMixin.java @@ -0,0 +1,29 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import com.llamalad7.mixinextras.sugar.Local; +import dev.engine_room.flywheel.api.visualization.VisualizationContext; +import dev.engine_room.flywheel.impl.visualization.storage.BlockEntityStorage; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlEngine; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(value = BlockEntityStorage.class, remap = false) +public abstract class BlockEntityStorageMixin +{ + @ModifyVariable(method = "createRaw", at = @At("HEAD"), argsOnly = true) + private VisualizationContext iris$tagContext(VisualizationContext context, @Local(argsOnly = true) BlockEntity blockEntity) + { + var blockIds = WorldRenderingSettings.INSTANCE.getBlockStateIds(); + + if (context instanceof ClrwlEngine.ClrwlMainVisualizationContext mainCtx && blockIds != null) + { + var state = blockEntity.getBlockState(); + return mainCtx.getBlockEntityVisualCtx(blockIds.getInt(state), state.getLightEmission()); + } + + return context; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/EntityStorageMixin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/EntityStorageMixin.java new file mode 100644 index 000000000..76d4d7bc7 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/EntityStorageMixin.java @@ -0,0 +1,31 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import com.llamalad7.mixinextras.sugar.Local; +import dev.engine_room.flywheel.api.visualization.VisualizationContext; +import dev.engine_room.flywheel.impl.visualization.storage.EntityStorage; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlEngine; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(value = EntityStorage.class, remap = false) +public abstract class EntityStorageMixin +{ + @ModifyVariable(method = "createRaw", at = @At("HEAD"), argsOnly = true) + private VisualizationContext iris$tagContext(VisualizationContext context, @Local(argsOnly = true) Entity entity) + { + var entityIds = WorldRenderingSettings.INSTANCE.getEntityIds(); + + if (context instanceof ClrwlEngine.ClrwlMainVisualizationContext mainCtx && entityIds != null) + { + var entityId = BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()); + return mainCtx.getEntityVisualCtx(entityIds.applyAsInt(new NamespacedId(entityId.getNamespace(), entityId.getPath()))); + } + + return context; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterManagerMixin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterManagerMixin.java new file mode 100644 index 000000000..1fb5c4811 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterManagerMixin.java @@ -0,0 +1,37 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +/** + * On Fabric the manager itself is the consumer handed to the block renderer, so it passes the block on to the + * emitter of every layer. + */ +@Mixin(targets = "dev.engine_room.flywheel.lib.model.baked.MeshEmitterManager", remap = false) +public abstract class MeshEmitterManagerMixin implements BlockSensitiveBufferBuilder +{ + @Shadow + @Final + private Reference2ReferenceMap emitterMap; + + @Override + public void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ) + { + for (Object emitter : emitterMap.values()) + { + ((BlockSensitiveBufferBuilder) emitter).beginBlock(block, renderType, lightEmission, localPosX, localPosY, localPosZ); + } + } + + @Override + public void endBlock() + { + for (Object emitter : emitterMap.values()) + { + ((BlockSensitiveBufferBuilder) emitter).endBlock(); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterMixin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterMixin.java new file mode 100644 index 000000000..5b35ae68e --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/MeshEmitterMixin.java @@ -0,0 +1,113 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.blaze3d.vertex.BufferBuilder; +//? if >=1.21 +//import com.mojang.blaze3d.vertex.MeshData; +import dev.engine_room.flywheel.lib.memory.MemoryBlock; +import dev.engine_room.flywheel.lib.model.SimpleQuadMesh; +import net.irisshaders.iris.compat.flywheel.engine.IrisTerrainVertexView; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import org.lwjgl.system.MemoryUtil; +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; + +/** + * Flywheel builds block models into one buffer per material. This forwards the current block to whichever buffer a + * quad lands in, and keeps the Iris terrain attributes that Flywheel's own mesh conversion drops. + */ +@Mixin(targets = "dev.engine_room.flywheel.lib.model.baked.MeshEmitter", remap = false) +public abstract class MeshEmitterMixin implements BlockSensitiveBufferBuilder +{ + // Only blocks placed in a virtual world get real light emission. Single models use -1, which the backend's + // shaders replace with the mesh center and the owning visual's emission. + @Unique + private boolean iris$isTerrain; + @Unique + private short iris$block = -1; + @Unique + private short iris$renderType = -1; + @Unique + private byte iris$lightEmission; + @Unique + private int iris$localPosX; + @Unique + private int iris$localPosY; + @Unique + private int iris$localPosZ; + + @Inject(method = "prepare", at = @At("HEAD")) + private void iris$beginModel(CallbackInfo ci) + { + iris$isTerrain = false; + } + + @Inject(method = "prepareForBlock", at = @At("HEAD")) + private void iris$beginTerrainBlock(CallbackInfo ci) + { + iris$isTerrain = true; + } + + @Override + public void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ) + { + iris$block = block; + iris$renderType = renderType; + iris$lightEmission = lightEmission; + iris$localPosX = localPosX; + iris$localPosY = localPosY; + iris$localPosZ = localPosZ; + } + + @Override + public void endBlock() + { + beginBlock((short) -1, (short) -1, (byte) 0, 0, 0, 0); + } + + @ModifyReturnValue(method = "getBuffer", at = @At("RETURN")) + private BufferBuilder iris$forwardBlock(BufferBuilder buffer) + { + if (buffer instanceof BlockSensitiveBufferBuilder blockSensitive) + { + blockSensitive.beginBlock(iris$block, iris$renderType, iris$isTerrain ? iris$lightEmission : -1, + iris$localPosX, iris$localPosY, iris$localPosZ); + } + + return buffer; + } + + @WrapOperation(method = "end", at = @At(value = "INVOKE", target = "Ldev/engine_room/flywheel/lib/model/baked/MeshHelper;blockVerticesToMesh(" + + /*? if >=1.21 {*/ /*"Lcom/mojang/blaze3d/vertex/MeshData;" + *//*?} else {*/ "Lcom/mojang/blaze3d/vertex/BufferBuilder$RenderedBuffer;" + /*?}*/ + "Ljava/lang/String;)Ldev/engine_room/flywheel/lib/model/SimpleQuadMesh;", + // The descriptor names Minecraft classes, which Fabric remaps even though Flywheel's own names are not. + remap = true)) + private SimpleQuadMesh iris$keepTerrainAttributes(/*? if >=1.21 {*/ /*MeshData data *//*?} else {*/ BufferBuilder.RenderedBuffer data /*?}*/, + String meshDescriptor, Operation original) + { + var drawState = data.drawState(); + + if (drawState.format() != IrisVertexFormats.TERRAIN) + { + return original.call(data, meshDescriptor); + } + + int vertexCount = drawState.vertexCount(); + IrisTerrainVertexView vertexView = new IrisTerrainVertexView(); + MemoryBlock dst = MemoryBlock.mallocTracked((long) vertexCount * vertexView.stride()); + + MemoryUtil.memCopy(MemoryUtil.memAddress(data.vertexBuffer()), dst.ptr(), (long) drawState.format().getVertexSize() * vertexCount); + + vertexView.ptr(dst.ptr()); + vertexView.vertexCount(vertexCount); + vertexView.nativeMemoryOwner(dst); + + return new SimpleQuadMesh(vertexView, meshDescriptor); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/OculusFlywheelCompatMixinPlugin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/OculusFlywheelCompatMixinPlugin.java new file mode 100644 index 000000000..263967338 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/OculusFlywheelCompatMixinPlugin.java @@ -0,0 +1,46 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Set; + +public class OculusFlywheelCompatMixinPlugin implements IMixinConfigPlugin { + @Override + public void onLoad(String s) { + + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String s, String s1) { + return EarlyLoaderServices.INSTANCE.isModLoaded("flywheel"); + } + + @Override + public void acceptTargets(Set set, Set set1) { + + } + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String s, ClassNode classNode, String s1, IMixinInfo iMixinInfo) { + + } + + @Override + public void postApply(String s, ClassNode classNode, String s1, IMixinInfo iMixinInfo) { + + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/TransformingVertexConsumerMixin.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/TransformingVertexConsumerMixin.java new file mode 100644 index 000000000..ded1edd69 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/mixin/TransformingVertexConsumerMixin.java @@ -0,0 +1,34 @@ +package net.irisshaders.iris.compat.flywheel.mixin; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +/** + * Wraps the buffer that Flywheel's model builder tesselates fluids into. + */ +@Mixin(targets = "dev.engine_room.flywheel.lib.model.baked.TransformingVertexConsumer", remap = false) +public abstract class TransformingVertexConsumerMixin implements BlockSensitiveBufferBuilder +{ + @Shadow + private VertexConsumer delegate; + + @Override + public void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ) + { + if (delegate instanceof BlockSensitiveBufferBuilder blockSensitive) + { + blockSensitive.beginBlock(block, renderType, lightEmission, localPosX, localPosY, localPosZ); + } + } + + @Override + public void endBlock() + { + if (delegate instanceof BlockSensitiveBufferBuilder blockSensitive) + { + blockSensitive.endBlock(); + } + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlOitConfig.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlOitConfig.java new file mode 100644 index 000000000..e95d0c3cd --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlOitConfig.java @@ -0,0 +1,9 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; + +import java.util.List; + +public record ClrwlOitConfig(boolean enabled, int[] coeffRanks, List accumulateOverrides) +{ +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackDirectives.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackDirectives.java new file mode 100644 index 000000000..63ccad1f8 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackDirectives.java @@ -0,0 +1,142 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlBlendModeOverride; +import net.irisshaders.iris.compat.flywheel.engine.ShadowCulling; +import net.irisshaders.iris.gl.blending.BufferBlendInformation; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.properties.ShadowCullState; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class ClrwlPackDirectives +{ + private final Map programBlendOverrides; + private final Map> bufferBlendOverrides; + + private final boolean shadowEnabled; + + private final ClrwlOitConfig gbuffersOit; + private final ClrwlOitConfig shadowOit; + + private final ShadowCullState shadowCullState; + + private final boolean gbuffersOcclusionCulling; + private final boolean gbuffersFrustumCulling; + + private final boolean shadowOcclusionCulling; + private final boolean shadowFrustumCulling; + + public ClrwlPackDirectives(ProgramSet programSet, ClrwlPackPrograms programs, ClrwlShaderProperties clrwlProperties) + { + var directives = programSet.getPackDirectives(); + + programBlendOverrides = clrwlProperties.getBlendModeOverride(); + bufferBlendOverrides = clrwlProperties.getBufferBlendModeOverrides(); + + shadowEnabled = clrwlProperties.shouldRenderShadow(); + + gbuffersOit = new ClrwlOitConfig(clrwlProperties.isOitEnabled(ClrwlProgramGroup.GBUFFERS), + clrwlProperties.getOitCoeffRanks(ClrwlProgramGroup.GBUFFERS), + clrwlProperties.getOitAccumulateOverrides(ClrwlProgramGroup.GBUFFERS)); + + shadowOit = new ClrwlOitConfig(clrwlProperties.isOitEnabled(ClrwlProgramGroup.SHADOW), + clrwlProperties.getOitCoeffRanks(ClrwlProgramGroup.SHADOW), + clrwlProperties.getOitAccumulateOverrides(ClrwlProgramGroup.SHADOW)); + + var shadowCullState = clrwlProperties.getShadowCullState(); + + if (shadowCullState == ShadowCullState.DEFAULT) + { + shadowCullState = directives.getShadowDirectives().getCullingState(); + } + + this.shadowCullState = shadowCullState; + + gbuffersOcclusionCulling = clrwlProperties.getOcclusionCulling().orElse(directives.shouldUseOcclusionCulling()); + gbuffersFrustumCulling = clrwlProperties.getFrustumCulling().orElse(directives.shouldUseFrustumCulling()); + + shadowOcclusionCulling = clrwlProperties.getShadowOcclusionCulling().orElse(false) + && programs.getShadowDistortSource().isPresent(); + shadowFrustumCulling = ShadowCulling.useFrustumCulling(programSet, shadowCullState); + } + + public Optional getBlendModeOverride(ClrwlProgramId programId) + { + return Optional.ofNullable(programBlendOverrides.get(programId)); + } + + public List getBufferBlendModeOverrides(ClrwlProgramId programId) + { + var list = bufferBlendOverrides.get(programId); + + if (list == null) + { + return Collections.emptyList(); + } + + return ImmutableList.copyOf(list); + } + + public boolean shouldRenderShadow() + { + return shadowEnabled; + } + + public ClrwlOitConfig getOitConfig(ClrwlProgramGroup group) + { + switch (group) + { + case GBUFFERS -> + { + return gbuffersOit; + } + case SHADOW -> + { + return shadowOit; + } + } + + throw new RuntimeException("Unknown program group: " + group); + } + + public ShadowCullState getShadowCullState() + { + return shadowCullState; + } + + public boolean getOcclusionCulling(ClrwlProgramGroup programGroup) + { + switch (programGroup) + { + case GBUFFERS -> { + return gbuffersOcclusionCulling; + } + + case SHADOW -> { + return shadowOcclusionCulling; + } + } + + throw new RuntimeException("Unknown program group: " + programGroup); + } + + public boolean getFrustumCulling(ClrwlProgramGroup programGroup) + { + switch (programGroup) + { + case GBUFFERS -> { + return gbuffersFrustumCulling; + } + + case SHADOW -> { + return shadowFrustumCulling; + } + } + + throw new RuntimeException("Unknown program group: " + programGroup); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackPrograms.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackPrograms.java new file mode 100644 index 000000000..a58caa83c --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlPackPrograms.java @@ -0,0 +1,159 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + +/** + * The Flywheel programs of one {@link ProgramSet}. Packs that ship no {@code clrwl_gbuffers} program run in + * fallback mode, where each Flywheel program borrows the closest vanilla gbuffers program. + */ +public class ClrwlPackPrograms +{ + private final ProgramSet programSet; + private final Map programSrcs = new EnumMap<>(ClrwlProgramId.class); + @Nullable + private final ComputeSource shadowDistortSrc; + private final boolean isFallbackMode; + private final ClrwlPackDirectives directives; + + public ClrwlPackPrograms(AbsolutePackPath directory, Function sourceProvider, ProgramSet programSet, + ShaderProperties shaderProperties, ClrwlShaderProperties clrwlProperties) + { + this.programSet = programSet; + + var clrwlGbuffers = ProgramSet.readProgramSource(directory, sourceProvider, ClrwlProgramId.GBUFFERS.programName(), programSet, shaderProperties, false) + .requireValid(); + ComputeSource shadowDistort = null; + + if (clrwlGbuffers.isPresent()) + { + isFallbackMode = false; + programSrcs.put(ClrwlProgramId.GBUFFERS, clrwlGbuffers.get()); + + for (var program : ClrwlProgramId.values()) + { + if (program == ClrwlProgramId.GBUFFERS) + { + continue; + } + + ProgramSet.readProgramSource(directory, sourceProvider, program.programName(), programSet, shaderProperties, false) + .requireValid() + .ifPresent(programSource -> programSrcs.put(program, programSource)); + } + + var shadowTransform = ProgramSet.readComputeSource(directory, sourceProvider, "clrwl_shadow_distort", programSet, shaderProperties); + + if (shadowTransform != null && shadowTransform.isValid()) + { + shadowDistort = shadowTransform; + } + } + else + { + isFallbackMode = true; + + for (var program : ClrwlProgramId.values()) + { + getFallbackProgramSrc(program.fallbackProgram()) + .ifPresent(programSource -> programSrcs.put(program, programSource)); + } + } + + this.shadowDistortSrc = shadowDistort; + this.directives = new ClrwlPackDirectives(programSet, this, clrwlProperties); + } + + private Optional getFallbackProgramSrc(@Nullable ProgramId programId) + { + while (programId != null) + { + var src = programSet.get(programId); + + if (src.isPresent()) + { + return src; + } + + programId = programId.getFallback().orElse(null); + } + + return Optional.empty(); + } + + public ClrwlPackDirectives getClrwlDirectives() + { + return directives; + } + + public Optional getRealClrwlProgram(ClrwlProgramId programId) + { + ClrwlProgramId cur = programId; + + while (cur != null) + { + if (programSrcs.containsKey(cur)) + { + return Optional.of(cur); + } + + cur = cur.base(); + } + + return Optional.empty(); + } + + public Optional getRealFallbackProgram(ClrwlProgramId programId) + { + var clrwlCur = programId; + + while (clrwlCur != null && clrwlCur.fallbackProgram() == null) + { + clrwlCur = clrwlCur.base(); + } + + if (clrwlCur == null) + { + return Optional.empty(); + } + + var cur = Optional.of(clrwlCur.fallbackProgram()); + + while (cur.isPresent()) + { + if (programSet.get(cur.get()).isPresent()) + { + return cur; + } + + cur = cur.get().getFallback(); + } + + return Optional.empty(); + } + + public Optional getClrwlProgramSource(ClrwlProgramId programId) + { + return getRealClrwlProgram(programId).map(programSrcs::get); + } + + public Optional getShadowDistortSource() + { + return Optional.ofNullable(shadowDistortSrc); + } + + public boolean isFallbackMode() + { + return isFallbackMode; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramGroup.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramGroup.java new file mode 100644 index 000000000..b412f3367 --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramGroup.java @@ -0,0 +1,24 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +public enum ClrwlProgramGroup +{ + GBUFFERS("gbuffers"), + SHADOW("shadow"); + + private final String name; + + ClrwlProgramGroup(String name) + { + this.name = name; + } + + public String groupName() + { + return name; + } + + public static ClrwlProgramGroup fromShadow(boolean isShadow) + { + return isShadow ? SHADOW : GBUFFERS; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramId.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramId.java new file mode 100644 index 000000000..a4c6e287a --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlProgramId.java @@ -0,0 +1,166 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +import net.irisshaders.iris.compat.flywheel.engine.ClrwlBlendModeOverride; +import dev.engine_room.flywheel.api.material.Transparency; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import org.jetbrains.annotations.Nullable; + +import java.util.Optional; + +public enum ClrwlProgramId +{ + GBUFFERS(ClrwlProgramGroup.GBUFFERS, "clrwl_gbuffers", ProgramId.Terrain, null, false, null), + GBUFFERS_ADDITIVE(ClrwlProgramGroup.GBUFFERS,"clrwl_gbuffers_additive", null, GBUFFERS, false, null), + GBUFFERS_GLINT(ClrwlProgramGroup.GBUFFERS,"clrwl_gbuffers_glint", ProgramId.ArmorGlint, GBUFFERS, false, null), + GBUFFERS_LIGHTNING(ClrwlProgramGroup.GBUFFERS,"clrwl_gbuffers_lightning", null, GBUFFERS, false, null), + GBUFFERS_TRANSLUCENT(ClrwlProgramGroup.GBUFFERS,"clrwl_gbuffers_translucent", ProgramId.Water, GBUFFERS, true, null), + GBUFFERS_DAMAGEDBLOCK(ClrwlProgramGroup.GBUFFERS,"clrwl_gbuffers_damagedblock", ProgramId.DamagedBlock, GBUFFERS, false, null), + + SHADOW(ClrwlProgramGroup.SHADOW, "clrwl_shadow", ProgramId.Shadow, null, false, ClrwlBlendModeOverride.OFF), + SHADOW_ADDITIVE(ClrwlProgramGroup.SHADOW,"clrwl_shadow_additive", null, SHADOW, false, ClrwlBlendModeOverride.OFF), + SHADOW_GLINT(ClrwlProgramGroup.SHADOW,"clrwl_shadow_glint", null, SHADOW, false, ClrwlBlendModeOverride.OFF), + SHADOW_LIGHTNING(ClrwlProgramGroup.SHADOW,"clrwl_shadow_lightning", null, null, false, ClrwlBlendModeOverride.OFF), + SHADOW_TRANSLUCENT(ClrwlProgramGroup.SHADOW,"clrwl_shadow_translucent", null, SHADOW, true, ClrwlBlendModeOverride.OFF); + + private final ClrwlProgramGroup group; + private final String name; + @Nullable + private final ProgramId fallbackProgram; + @Nullable + private final ClrwlProgramId base; + private final boolean afterTranslucent; + @Nullable + private final ClrwlBlendModeOverride defaultBlendOverride; + + ClrwlProgramId(ClrwlProgramGroup group, String name, @Nullable ProgramId fallbackProgram, @Nullable ClrwlProgramId base, boolean afterTranslucent, @Nullable ClrwlBlendModeOverride defaultBlendOverride) + { + this.group = group; + this.name = name; + this.fallbackProgram = fallbackProgram; + this.base = base; + this.afterTranslucent = afterTranslucent; + this.defaultBlendOverride = defaultBlendOverride; + } + + public ClrwlProgramGroup group() + { + return group; + } + + public String programName() + { + return name; + } + + @Nullable + public ProgramId fallbackProgram() + { + return fallbackProgram; + } + + @Nullable + public ClrwlProgramId base() + { + return base; + } + + public boolean afterTranslucent() + { + return afterTranslucent; + } + + public Optional defaultBlendOverride() + { + return Optional.ofNullable(defaultBlendOverride); + } + + public static ClrwlProgramId[] gbuffers() + { + return new ClrwlProgramId[] { GBUFFERS, GBUFFERS_ADDITIVE, GBUFFERS_GLINT, GBUFFERS_LIGHTNING, GBUFFERS_TRANSLUCENT, GBUFFERS_DAMAGEDBLOCK }; + } + + public static ClrwlProgramId[] shadow() + { + return new ClrwlProgramId[] { SHADOW, SHADOW_ADDITIVE, SHADOW_GLINT, SHADOW_LIGHTNING, SHADOW_TRANSLUCENT }; + } + + public static Optional fromName(String name) + { + for (var program : values()) + { + if (program.name.equals(name)) + { + return Optional.of(program); + } + } + + return Optional.empty(); + } + + public static ClrwlProgramId fromTransparency(Transparency transparency, boolean isShadow) + { + if (!isShadow) + { + switch (transparency) + { + case OPAQUE -> + { + return ClrwlProgramId.GBUFFERS; + } + case ADDITIVE -> + { + return ClrwlProgramId.GBUFFERS_ADDITIVE; + } + case LIGHTNING -> + { + return ClrwlProgramId.GBUFFERS_LIGHTNING; + } + case GLINT -> + { + return ClrwlProgramId.GBUFFERS_GLINT; + } + case CRUMBLING -> + { + return ClrwlProgramId.GBUFFERS_DAMAGEDBLOCK; + } + case TRANSLUCENT, ORDER_INDEPENDENT -> + { + return ClrwlProgramId.GBUFFERS_TRANSLUCENT; + } + } + } + else + { + switch (transparency) + { + case OPAQUE -> + { + return ClrwlProgramId.SHADOW; + } + case ADDITIVE -> + { + return ClrwlProgramId.SHADOW_ADDITIVE; + } + case LIGHTNING -> + { + return ClrwlProgramId.SHADOW_LIGHTNING; + } + case GLINT -> + { + return ClrwlProgramId.SHADOW_GLINT; + } + case TRANSLUCENT, ORDER_INDEPENDENT -> + { + return ClrwlProgramId.SHADOW_TRANSLUCENT; + } + case CRUMBLING -> + { + // Should never happen + return ClrwlProgramId.SHADOW; + } + } + } + + throw new RuntimeException("Unknown transparency: " + transparency); + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlShaderProperties.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlShaderProperties.java new file mode 100644 index 000000000..93ee306bd --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/shaderpack/ClrwlShaderProperties.java @@ -0,0 +1,553 @@ +package net.irisshaders.iris.compat.flywheel.shaderpack; + +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlBlendModeOverride; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlOitAccumulateOverride; +import net.irisshaders.iris.compat.flywheel.util.Utils; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendMode; +import net.irisshaders.iris.gl.blending.BlendModeFunction; +import net.irisshaders.iris.gl.blending.BufferBlendInformation; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.shaderpack.option.OrderBackedProperties; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor; +import net.irisshaders.iris.shaderpack.properties.ShadowCullState; + +import java.io.IOException; +import java.io.StringReader; +import java.util.*; +import java.util.function.Consumer; + +public class ClrwlShaderProperties +{ + private final Map programBlendOverrides = new EnumMap<>(ClrwlProgramId.class); + private final Map> bufferBlendOverrides = new EnumMap<>(ClrwlProgramId.class); + + private OptionalBoolean shadowEnabled = OptionalBoolean.DEFAULT; + + private OptionalBoolean gbuffersOitEnabled = OptionalBoolean.DEFAULT; + private int[] gbuffersOitCoeffRanks = new int[0]; + private final List gbuffersOitAccumulateOverrides = new ArrayList<>(); + + private OptionalBoolean shadowOitEnabled = OptionalBoolean.DEFAULT; + private int[] shadowOitCoeffRanks = new int[0]; + private final List shadowOitAccumulateOverrides = new ArrayList<>(); + + private ShadowCullState shadowCulling = ShadowCullState.DEFAULT; + private OptionalBoolean shadowOcclusionCulling = OptionalBoolean.DEFAULT; + private OptionalBoolean frustumCulling = OptionalBoolean.DEFAULT; + private OptionalBoolean occlusionCulling = OptionalBoolean.DEFAULT; + + public ClrwlShaderProperties() + { + // Empty + } + + public ClrwlShaderProperties(String str, ShaderPackOptions options, Iterable environmentDefines) + { + String preprocessedStr = PropertiesPreprocessor.preprocessSource(str, options, environmentDefines); + Properties properties = new OrderBackedProperties(); + + try + { + properties.load(new StringReader(preprocessedStr)); + } + catch (IOException e) + { + Colorwheel.LOGGER.error("Could not load colorwheel.properties", e); + } + + for (Map.Entry property : properties.entrySet()) + { + String key = (String) property.getKey(); + String value = (String) property.getValue(); + String[] path = key.split("\\."); + + if (path.length == 0) + { + continue; + } + + if (path[0].equals("shadow")) + { + if (path.length == 2) + { + if (path[1].equals("enabled")) + { + parseBoolean(value, bool -> shadowEnabled = bool); + } + else if (path[1].equals("culling")) + { + if ("false".equals(value)) { + shadowCulling = ShadowCullState.DISTANCE; + } else if ("true".equals(value)) { + shadowCulling = ShadowCullState.ADVANCED; + } else if ("reversed".equals(value)) { + shadowCulling = ShadowCullState.REVERSED; + } else { + Colorwheel.LOGGER.error("Unrecognized shadow culling setting: " + value); + continue; + } + } + } + else if (path.length == 3) + { + if (path[1].equals("occlusion") && path[2].equals("culling")) + { + parseBoolean(value, bool -> shadowOcclusionCulling = bool); + } + } + } + else if (path[0].equals("frustum")) + { + if (path.length == 2 && path[1].equals("culling")) + { + parseBoolean(value, bool -> frustumCulling = bool); + } + } + else if (path[0].equals("occlusion")) + { + if (path.length == 2 && path[1].equals("culling")) + { + parseBoolean(value, bool -> occlusionCulling = bool); + } + } + else if (path[0].equals("blend")) + { + if (path.length == 2) + { + var maybeProgramId = ClrwlProgramId.fromName(path[1]); + + if (maybeProgramId.isEmpty()) + { + Colorwheel.LOGGER.warn("Unknown program: {}", path[1]); + continue; + } + + var programId = maybeProgramId.get(); + + if (value.equals("off")) + { + programBlendOverrides.put(programId, new ClrwlBlendModeOverride(null)); + } + else + { + parseBlendMode(value).ifPresent(bm -> programBlendOverrides.put(programId, new ClrwlBlendModeOverride(bm))); + } + } + else if (path.length == 3) + { + if (!IrisRenderSystem.supportsBufferBlending()) + { + throw new RuntimeException("Buffer blending not supported"); + } + + var maybeProgramId = ClrwlProgramId.fromName(path[1]); + + if (maybeProgramId.isEmpty()) + { + Colorwheel.LOGGER.warn("Unknown program: {}", path[1]); + continue; + } + + var programId = maybeProgramId.get(); + String buffer = path[2]; + + int id; + + if (programId.group() == ClrwlProgramGroup.SHADOW) + { + if (!buffer.startsWith("shadowcolor")) + { + Colorwheel.LOGGER.error("Attempt to disable blend on invalid buffer: {}", buffer); + continue; + } + + try + { + id = Integer.parseInt(buffer.substring("shadowcolor".length())); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Attempt to disable blend on invalid buffer: {}", buffer); + continue; + } + } + else + { + if (!buffer.startsWith("colortex")) + { + Colorwheel.LOGGER.error("Attempt to disable blend on invalid buffer: {}", buffer); + continue; + } + + try + { + id = Integer.parseInt(buffer.substring("colortex".length())); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Attempt to disable blend on invalid buffer: {}", buffer); + continue; + } + } + + var list = bufferBlendOverrides.computeIfAbsent(programId, (s) -> new ArrayList<>()); + + if (value.equals("off")) + { + list.add(new BufferBlendInformation(id, null)); + } + else + { + parseBlendMode(value).ifPresent(bm -> list.add(new BufferBlendInformation(id, bm))); + } + } + + continue; + } + else if (path[0].equals("oit")) + { + if (path.length == 1) + { + parseBoolean(value, bool -> + { + gbuffersOitEnabled = bool; + shadowOitEnabled = bool; + }); + continue; + } + + if (path[1].equals("gbuffers")) + { + if (path.length == 2) + { + parseBoolean(value, bool -> gbuffersOitEnabled = bool); + continue; + } + else if (path[2].equals("coefficientRanks") && path.length == 3) + { + parseCoefficientsRanks(value) + .ifPresent(ranks -> gbuffersOitCoeffRanks = ranks); + continue; + } + else if (path[2].startsWith("colortex")) + { + int drawBuffer; + + try + { + drawBuffer = Integer.parseUnsignedInt(path[2].substring(8)); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Invalid attachment: {}", path[2]); + continue; + } + + if (path.length == 3) + { + Optional coefficientId; + + if (value.equals("frontmost")) + { + coefficientId = Optional.empty(); + } + else + { + try + { + coefficientId = Optional.of(Integer.parseUnsignedInt(value)); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Invalid coefficient id: {}", value); + continue; + } + } + + Utils.findFirst(gbuffersOitAccumulateOverrides, t -> t.drawBuffer() == drawBuffer) + .ifPresentOrElse(t -> t.setCoefficientId(coefficientId), + () -> gbuffersOitAccumulateOverrides.add(new ClrwlOitAccumulateOverride(drawBuffer, coefficientId))); + + continue; + } + else if (path.length == 4) + { + if (path[3].equals("format")) + { + try + { + var format = InternalTextureFormat.valueOf(value); + + Utils.findFirst(gbuffersOitAccumulateOverrides, t -> t.drawBuffer() == drawBuffer) + .ifPresentOrElse(t -> t.setFormat(format), + () -> gbuffersOitAccumulateOverrides.add(new ClrwlOitAccumulateOverride(drawBuffer, format))); + } + catch (IllegalArgumentException e) + { + Colorwheel.LOGGER.error("Unknown format: {}", value); + continue; + } + + continue; + } + } + } + + Colorwheel.LOGGER.error("Unknown OIT key: {}", path[2]); + continue; + } + else if (path[1].equals("shadow")) + { + if (path.length == 2) + { + parseBoolean(value, bool -> shadowOitEnabled = bool); + continue; + } + else if (path[2].equals("coefficientRanks") && path.length == 3) + { + parseCoefficientsRanks(value) + .ifPresent(ranks -> shadowOitCoeffRanks = ranks); + continue; + } + else if (path[2].startsWith("shadowcolor")) + { + int drawBuffer; + + try + { + drawBuffer = Integer.parseUnsignedInt(path[2].substring(11)); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Invalid attachment: {}", path[2]); + continue; + } + + if (path.length == 3) + { + Optional coefficientId; + + if (value.equals("frontmost")) + { + coefficientId = Optional.empty(); + } + else + { + try + { + coefficientId = Optional.of(Integer.parseUnsignedInt(value)); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Invalid coefficient id: {}", value); + continue; + } + } + + Utils.findFirst(shadowOitAccumulateOverrides, t -> t.drawBuffer() == drawBuffer) + .ifPresentOrElse(t -> t.setCoefficientId(coefficientId), + () -> shadowOitAccumulateOverrides.add(new ClrwlOitAccumulateOverride(drawBuffer, coefficientId))); + + continue; + } + else if (path.length == 4) + { + if (path[3].equals("format")) + { + try + { + var format = InternalTextureFormat.valueOf(value); + + Utils.findFirst(shadowOitAccumulateOverrides, t -> t.drawBuffer() == drawBuffer) + .ifPresentOrElse(t -> t.setFormat(format), + () -> shadowOitAccumulateOverrides.add(new ClrwlOitAccumulateOverride(drawBuffer, format))); + } + catch (IllegalArgumentException e) + { + Colorwheel.LOGGER.error("Unknown format: {}", value); + continue; + } + + continue; + } + } + } + + Colorwheel.LOGGER.error("Unknown OIT key: {}", path[2]); + continue; + } + else + { + Colorwheel.LOGGER.error("Unknown program groug for OIT: {}", path[1]); + continue; + } + } + } + } + + private void parseBoolean(String value, Consumer block) + { + if (value.equalsIgnoreCase("true")) + { + block.accept(OptionalBoolean.TRUE); + } + else if (value.equalsIgnoreCase("false")) + { + block.accept(OptionalBoolean.FALSE); + } + else + { + Colorwheel.LOGGER.error("Could not parse boolean: {}", value); + } + } + + private Optional parseBlendMode(String value) + { + String[] modeStrs = value.split(" "); + int[] modeFcts = new int[modeStrs.length]; + + if (modeFcts.length != 4) + { + Colorwheel.LOGGER.error("Invalid blend function count: {} (expected 4)", modeFcts.length); + return Optional.empty(); + } + + for (int i = 0; i < modeStrs.length; i++) + { + var maybeFct = BlendModeFunction.fromString(modeStrs[i]); + + if (maybeFct.isEmpty()) + { + Colorwheel.LOGGER.error("Unknown blend function: {}", modeStrs[i]); + continue; + } + + modeFcts[i] = maybeFct.get().getGlId(); + } + + return Optional.of(new BlendMode(modeFcts[0], modeFcts[1], modeFcts[2], modeFcts[3])); + } + + private Optional parseCoefficientsRanks(String value) + { + String[] rankStrs = value.split(","); + int[] ranks = new int[rankStrs.length]; + + for (int i = 0; i < rankStrs.length; i++) + { + String rankStr = rankStrs[i].trim(); + int rank; + + try + { + rank = Integer.parseUnsignedInt(rankStr); + } + catch (NumberFormatException e) + { + Colorwheel.LOGGER.error("Invalid OIT coefficients ranks: {}", value); + return Optional.empty(); + } + + if (rank == 0 || rank > 3) + { + Colorwheel.LOGGER.error("Invalid OIT coefficients ranks: {} (must be >= 1 && <= 3)", value); + return Optional.empty(); + } + + ranks[i] = rank; + } + + return Optional.of(ranks); + } + + public Map getBlendModeOverride() + { + return programBlendOverrides; + } + + public Map> getBufferBlendModeOverrides() + { + return bufferBlendOverrides; + } + + public boolean shouldRenderShadow() + { + return shadowEnabled.orElse(true); + } + + public boolean isOitEnabled(ClrwlProgramGroup group) + { + switch (group) + { + case GBUFFERS -> + { + return gbuffersOitEnabled.orElse(false); + } + case SHADOW -> + { + return shadowOitEnabled.orElse(false); + } + } + + throw new RuntimeException("Unknown program group: " + group); + } + + public int[] getOitCoeffRanks(ClrwlProgramGroup group) + { + switch (group) + { + case GBUFFERS -> + { + return gbuffersOitCoeffRanks; + } + case SHADOW -> + { + return shadowOitCoeffRanks; + } + } + + throw new RuntimeException("Unknown program group: " + group); + } + + public List getOitAccumulateOverrides(ClrwlProgramGroup group) + { + switch (group) + { + case GBUFFERS -> + { + return gbuffersOitAccumulateOverrides; + } + case SHADOW -> + { + return shadowOitAccumulateOverrides; + } + } + + throw new RuntimeException("Unknown program group: " + group); + } + + public ShadowCullState getShadowCullState() + { + return shadowCulling; + } + + public OptionalBoolean getShadowOcclusionCulling() + { + return shadowOcclusionCulling; + } + + public OptionalBoolean getFrustumCulling() + { + return frustumCulling; + } + + public OptionalBoolean getOcclusionCulling() + { + return occlusionCulling; + } +} diff --git a/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/util/Utils.java b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/util/Utils.java new file mode 100644 index 000000000..a64e6998b --- /dev/null +++ b/modern/src/main/flywheel_java/net/irisshaders/iris/compat/flywheel/util/Utils.java @@ -0,0 +1,73 @@ +package net.irisshaders.iris.compat.flywheel.util; + +import dev.engine_room.flywheel.api.material.Transparency; +import net.irisshaders.iris.gl.blending.BlendMode; +import net.irisshaders.iris.gl.blending.BlendModeFunction; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class Utils +{ + public static Map reverse(Map map) + { + return map.entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); + } + + public static Optional findFirst(List list, Predicate predicate) + { + for (T e : list) + { + if (predicate.test(e)) + { + return Optional.of(e); + } + } + + return Optional.empty(); + } + + public static BlendMode transparencyToBlendMode(Transparency transparency) + { + switch (transparency) + { + case OPAQUE -> + { + return new BlendMode(BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId(), + BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId()); + } + case ADDITIVE -> + { + return new BlendMode(BlendModeFunction.ONE.getGlId(), BlendModeFunction.ONE.getGlId(), + BlendModeFunction.ONE.getGlId(), BlendModeFunction.ONE.getGlId()); + } + case LIGHTNING -> + { + return new BlendMode(BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE.getGlId(), + BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE.getGlId()); + } + case GLINT -> + { + return new BlendMode(BlendModeFunction.SRC_COLOR.getGlId(), BlendModeFunction.ONE.getGlId(), + BlendModeFunction.ZERO.getGlId(), BlendModeFunction.ONE.getGlId()); + } + case CRUMBLING -> + { + return new BlendMode(BlendModeFunction.DST_COLOR.getGlId(), BlendModeFunction.SRC_COLOR.getGlId(), + BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId()); + } + case TRANSLUCENT, ORDER_INDEPENDENT -> + { + return new BlendMode(BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE_MINUS_SRC_ALPHA.getGlId(), + BlendModeFunction.ONE.getGlId(), BlendModeFunction.ONE_MINUS_SRC_ALPHA.getGlId()); + } + } + + throw new RuntimeException("Unknown transparency: " + transparency); + } +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.frag new file mode 100644 index 000000000..fad263986 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.frag @@ -0,0 +1,66 @@ +#include "celeritas:internal/material.glsl" +#include "flywheel:internal/api_impl.glsl" +#include "celeritas:internal/uniforms.glsl" + +#ifndef _CLRWL_IS_FALLBACK +in ClrwlVertexData +{ + vec4 flw_vertexPos; + vec4 flw_vertexColor; + vec2 flw_vertexTexCoord; + flat ivec2 flw_vertexOverlay; + vec2 flw_vertexLight; + vec3 flw_vertexNormal; + vec4 clrwl_vertexTangent; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif + +#ifdef _FLW_DEBUG + vec2 clrwl_vertexEntity; + vec2 clrwl_vertexMidTexCoord; + vec4 clrwl_vertexMidMesh; + flat uvec2 clrwl_debugIds; +#endif +}; + +vec4 flw_sampleColor; +float flw_distance; + +bool flw_fragDiffuse; +vec4 flw_fragColor; +ivec2 flw_fragOverlay; +vec2 flw_fragLight; + +vec4 clrwl_overlayColor = vec4(0.0); + +#else // _CLRWL_IS_FALLBACK + +in ClrwlFallbackVertexData +{ + vec4 clrwl_overlayColor; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif +}; +#endif + +#ifndef CLRWL_IS_INDIRECT +int _clrwl_entityId; +int _clrwl_blockEntityId; +#endif + +FlwMaterial flw_material; + +uniform sampler2D flw_diffuseTex; +uniform sampler2D flw_overlayTex; + +#ifdef _FLW_CRUMBLING +uniform sampler2D _flw_crumblingTex; +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.vert new file mode 100644 index 000000000..2e4bc4257 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl.vert @@ -0,0 +1,80 @@ +#include "celeritas:internal/material.glsl" +#include "flywheel:internal/api_impl.glsl" +#include "celeritas:internal/uniforms.glsl" + +#ifndef _CLRWL_IS_FALLBACK +out ClrwlVertexData +{ + vec4 flw_vertexPos; + vec4 flw_vertexColor; + vec2 flw_vertexTexCoord; + flat ivec2 flw_vertexOverlay; + vec2 flw_vertexLight; + vec3 flw_vertexNormal; + vec4 clrwl_vertexTangent; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif + +#ifdef _FLW_DEBUG + vec2 clrwl_vertexEntity; + vec2 clrwl_vertexMidTexCoord; + vec4 clrwl_vertexMidMesh; + flat uvec2 clrwl_debugIds; +#endif +}; + +#ifndef _FLW_DEBUG +vec2 clrwl_vertexEntity; +vec2 clrwl_vertexMidTexCoord; +vec4 clrwl_vertexMidMesh; +uvec2 clrwl_debugIds; +#endif + +vec4 clrwl_overlayColor = vec4(0.0); + +#else // _CLRWL_IS_FALLBACK + +vec4 flw_vertexPos; +vec4 flw_vertexColor; +vec2 flw_vertexTexCoord; +ivec2 flw_vertexOverlay; +vec2 flw_vertexLight; +vec3 flw_vertexNormal; +vec4 clrwl_vertexTangent; + +vec2 clrwl_vertexEntity; +vec2 clrwl_vertexMidTexCoord; +vec4 clrwl_vertexMidMesh; +uvec2 clrwl_debugIds; + +out ClrwlFallbackVertexData +{ + vec4 clrwl_overlayColor; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif +}; +#endif + +#ifndef CLRWL_IS_INDIRECT +int _clrwl_entityId; +int _clrwl_blockEntityId; +#endif + +FlwMaterial flw_material; + +uint flw_vertexId; + +uniform sampler2D flw_diffuseTex; +uniform sampler2D flw_overlayTex; + +#ifdef _FLW_CRUMBLING +uniform sampler2D _flw_crumblingTex; +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl_geom.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl_geom.glsl new file mode 100644 index 000000000..08ac6da8c --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/api_impl_geom.glsl @@ -0,0 +1,87 @@ +#include "celeritas:internal/material.glsl" +#include "celeritas:internal/uniforms.glsl" + +#ifndef _CLRWL_IS_FALLBACK +in ClrwlVertexData +{ + vec4 flw_vertexPos; + vec4 flw_vertexColor; + vec2 flw_vertexTexCoord; + flat ivec2 flw_vertexOverlay; + vec2 flw_vertexLight; + vec3 flw_vertexNormal; + vec4 clrwl_vertexTangent; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif + +#ifdef _FLW_DEBUG + vec2 clrwl_vertexEntity; + vec2 clrwl_vertexMidTexCoord; + vec4 clrwl_vertexMidMesh; + flat uvec2 clrwl_debugIds; +#endif +} clrwl_in[3]; + +out ClrwlVertexData +{ + vec4 flw_vertexPos; + vec4 flw_vertexColor; + vec2 flw_vertexTexCoord; + flat ivec2 flw_vertexOverlay; + vec2 flw_vertexLight; + vec3 flw_vertexNormal; + vec4 clrwl_vertexTangent; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif + +#ifdef _FLW_DEBUG + vec2 clrwl_vertexEntity; + vec2 clrwl_vertexMidTexCoord; + vec4 clrwl_vertexMidMesh; + flat uvec2 clrwl_debugIds; +#endif +} clrwl_out; + +#else // _CLRWL_IS_FALLBACK + +in ClrwlFallbackVertexData +{ + vec4 clrwl_overlayColor; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif +} clrwl_in[3]; + +out ClrwlFallbackVertexData +{ + vec4 clrwl_overlayColor; + +#ifdef CLRWL_IS_INDIRECT + flat uint _clrwl_packedMaterial; + flat int _clrwl_entityId; + flat int _clrwl_blockEntityId; +#endif +} clrwl_out; +#endif + +int _clrwl_entityId; +int _clrwl_blockEntityId; +vec4 clrwl_overlayColor = vec4(0.0); + +uniform sampler2D flw_diffuseTex; +uniform sampler2D flw_overlayTex; + +#ifdef _FLW_CRUMBLING +uniform sampler2D _flw_crumblingTex; +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/colorizer.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/colorizer.glsl new file mode 100644 index 000000000..9fb367cef --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/colorizer.glsl @@ -0,0 +1,22 @@ +// https://github.com/Engine-Room/Flywheel/blob/dc5bc8e64976c69b38abb6965d5cd9033e5a8808/common/src/backend/resources/assets/flywheel/flywheel/internal/colorizer.glsl + +// https://stackoverflow.com/a/17479300 +uint _flw_hash(in uint x) { + x += (x << 10u); + x ^= (x >> 6u); + x += (x << 3u); + x ^= (x >> 11u); + x += (x << 15u); + return x; +} + +vec4 _flw_id2Color(in uint id) { + uint x = _flw_hash(id); + + return vec4( + float(x & 0xFFu) / 255.0, + float((x >> 8u) & 0xFFu) / 255.0, + float((x >> 16u) & 0xFFu) / 255.0, + 1. + ); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.frag new file mode 100644 index 000000000..eefe8df64 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.frag @@ -0,0 +1,49 @@ +#include "celeritas:internal/packed_material.glsl" +#include "celeritas:internal/fog_distance.glsl" + +#ifdef CLRWL_OIT +uniform sampler2D _flw_depthRange; +uniform sampler2D _flw_blueNoise; + +float _clrwl_tented_blue_noise(float normalizedDepth) +{ + float tentIn = abs(normalizedDepth * 2. - 1); + float tentIn2 = tentIn * tentIn; + float tentIn4 = tentIn2 * tentIn2; + float tent = 1 - (tentIn2 * tentIn4); + + float b = texture(_flw_blueNoise, gl_FragCoord.xy / vec2(64)).r; + + return b * tent; +} + +float _clrwl_linear_depth() +{ + return _clrwl_linearize_depth(gl_FragCoord.z, _flw_cullData.znear, _flw_cullData.zfar); +} + +#ifdef CLRWL_EVALUATE +float _clrwl_frontmost_transmittance_from_depth(float linear, vec2 range) +{ + return linear <= -range.x + 2e-5 ? 1.0 : 0.0; +} +#endif +#endif + +void _clrwl_post_shader(); + +void _clrwl_main() +{ + #ifndef _CLRWL_IS_FALLBACK + vec3 screenPos = vec3(gl_FragCoord.xy / flw_viewportSize, gl_FragCoord.z); + vec3 ndc = screenPos * 2.0 - 1.0; + vec4 viewPos = flw_projectionInverse * vec4(ndc, 1.0); + viewPos /= viewPos.w; + vec4 flwPos = flw_viewInverse * viewPos; + + flw_distance = _clrwl_fogDistance(flwPos.xyz, flw_cameraPos, flw_fogShape); + #endif + + _clrwl_shader_main(); + _clrwl_post_shader(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.vert new file mode 100644 index 000000000..5b82ad999 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common.vert @@ -0,0 +1,208 @@ +#include "celeritas:internal/packed_material.glsl" +#include "celeritas:internal/diffuse.glsl" + +#ifdef _FLW_CRUMBLING +const int _CLRWL_DOWN = 0; +const int _CLRWL_UP = 1; +const int _CLRWL_NORTH = 2; +const int _CLRWL_SOUTH = 3; +const int _CLRWL_WEST = 4; +const int _CLRWL_EAST = 5; + +// based on net.minecraftforge.client.ForgeHooksClient.getNearestStable +int _clrwl_getNearestFacing(vec3 normal) +{ + float maxAlignment = -2; + int face = 2; + + // Calculate the alignment of the normal vector with each axis. + // Note that `-dot(normal, axis) == dot(normal, -axis)`. + vec3 alignment = vec3( + dot(normal, vec3(1., 0., 0.)), + dot(normal, vec3(0., 1., 0.)), + dot(normal, vec3(0., 0., 1.)) + ); + + if (-alignment.y > maxAlignment) + { + maxAlignment = -alignment.y; + face = _CLRWL_DOWN; + } + if (alignment.y > maxAlignment) + { + maxAlignment = alignment.y; + face = _CLRWL_UP; + } + if (-alignment.z > maxAlignment) + { + maxAlignment = -alignment.z; + face = _CLRWL_NORTH; + } + if (alignment.z > maxAlignment) + { + maxAlignment = alignment.z; + face = _CLRWL_SOUTH; + } + if (-alignment.x > maxAlignment) + { + maxAlignment = -alignment.x; + face = _CLRWL_WEST; + } + if (alignment.x > maxAlignment) + { + maxAlignment = alignment.x; + face = _CLRWL_EAST; + } + + return face; +} + +vec2 _clrwl_getCrumblingTexCoord() +{ + switch (_clrwl_getNearestFacing(flw_vertexNormal)) + { + case _CLRWL_DOWN: return vec2(flw_vertexPos.x, -flw_vertexPos.z); + case _CLRWL_UP: return vec2(flw_vertexPos.x, flw_vertexPos.z); + case _CLRWL_NORTH: return vec2(-flw_vertexPos.x, -flw_vertexPos.y); + case _CLRWL_SOUTH: return vec2(flw_vertexPos.x, -flw_vertexPos.y); + case _CLRWL_WEST: return vec2(-flw_vertexPos.z, -flw_vertexPos.y); + case _CLRWL_EAST: return vec2(flw_vertexPos.z, -flw_vertexPos.y); + } + + // default to north + return vec2(-flw_vertexPos.x, -flw_vertexPos.y); +} +#endif + +float _clrwl_diffuseFactor() +{ + if (flw_material.cardinalLightingMode == 2u) + { + return clrwl_diffuseFromLightDirections(flw_vertexNormal); + } + else if (flw_material.cardinalLightingMode == 1u) + { + if (flw_constantAmbientLight == 1u) + { + return clrwl_diffuseNether(flw_vertexNormal); + } + else + { + return clrwl_diffuse(flw_vertexNormal); + } + } + else + { + return 1.; + } +} + +#ifdef FLW_EMBEDDED +mat4 _flw_modelMatrix; +mat3 _flw_normalMatrix; +#endif + +vec4 _clrwl_meshCenter; + +void _clrwl_main(FlwInstance instance, uint stableInstanceID, uint baseVertex) +{ + flw_vertexId = gl_VertexID - baseVertex; + + _clrwl_layoutVertex(); + + // --- Compute mesh center, vertex tangent and midtexcoord + + vec4 flw_vertexPos_bkp = flw_vertexPos; + vec4 flw_vertexColor_bkp = flw_vertexColor; + vec2 flw_vertexTexCoord_bkp = flw_vertexTexCoord; + ivec2 flw_vertexOverlay_bkp = flw_vertexOverlay; + vec2 flw_vertexLight_bkp = flw_vertexLight; + vec3 flw_vertexNormal_bkp = flw_vertexNormal; + + vec3 midMesh = clrwl_vertexMidMesh.w == -1 + ? _clrwl_meshCenter.xyz + : flw_vertexPos.xyz + clrwl_vertexMidMesh.xyz / 64.0; + + flw_vertexPos = vec4(midMesh.xyz, 1.0); + flw_vertexNormal = clrwl_vertexTangent.xyz; + flw_vertexTexCoord = clrwl_vertexMidTexCoord; + + flw_instanceVertex(instance); + flw_materialVertex(); + + vec4 transformedMeshCenter = flw_vertexPos; + clrwl_vertexTangent.xyz = flw_vertexNormal; + clrwl_vertexMidTexCoord = flw_vertexTexCoord; + + flw_vertexPos = flw_vertexPos_bkp; + flw_vertexColor = flw_vertexColor_bkp; + flw_vertexTexCoord = flw_vertexTexCoord_bkp; + flw_vertexOverlay = flw_vertexOverlay_bkp; + flw_vertexLight = flw_vertexLight_bkp; + flw_vertexNormal = flw_vertexNormal_bkp; + + // --- + + flw_instanceVertex(instance); + flw_materialVertex(); + + #ifdef _FLW_CRUMBLING + flw_vertexTexCoord = _clrwl_getCrumblingTexCoord(); + #endif + + #ifdef FLW_EMBEDDED + flw_vertexPos = _flw_modelMatrix * flw_vertexPos; + transformedMeshCenter = _flw_modelMatrix * transformedMeshCenter; + flw_vertexNormal = _flw_normalMatrix * flw_vertexNormal; + clrwl_vertexTangent.xyz = _flw_normalMatrix * clrwl_vertexTangent.xyz; + #endif + + clrwl_vertexMidMesh = vec4((transformedMeshCenter.xyz - flw_vertexPos.xyz) * 64.0, + clrwl_vertexMidMesh.w == -1 ? _clrwl_meshCenter.w : clrwl_vertexMidMesh.w); + + flw_vertexNormal = normalize(flw_vertexNormal); + + #ifdef _CLRWL_IS_FALLBACK + FlwLightAo light; + if (flw_light(flw_vertexPos.xyz, flw_vertexNormal, light)) + { + if (!flw_material.ambientOcclusion) + { + light.ao = 1.0; + } + + #ifdef _CLRWL_SEPARATE_AO + flw_vertexLight = max(flw_vertexLight, light.light); + flw_vertexColor.a = light.ao; + #else + flw_vertexLight = max(flw_vertexLight, light.light); + flw_vertexColor.rgb *= light.ao; + #endif + } + + #if CLRWL_OLD_LIGHTING + flw_vertexColor.rgb *= _clrwl_diffuseFactor(); + #endif + #endif + + #ifdef _FLW_DEBUG + clrwl_debugIds = uvec2(stableInstanceID, baseVertex); + + if (_flw_debugMode == 6u) // midMesh + { + flw_vertexPos.xyz += (clrwl_vertexMidMesh.xyz / 64.0) * (sin(flw_renderSeconds * 3.14159) * 0.5 + 0.5); + } + #endif + + if (flw_material.useOverlay) + { + clrwl_overlayColor = texelFetch(flw_overlayTex, flw_vertexOverlay, 0); + clrwl_overlayColor.a = 1.0 - clrwl_overlayColor.a; + } + else + { + clrwl_overlayColor = vec4(0.0); + } + + _clrwl_shader_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common_geom.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common_geom.glsl new file mode 100644 index 000000000..e470179d2 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/common_geom.glsl @@ -0,0 +1,18 @@ +FlwMaterial flw_material; + +void _clrwl_main() +{ + #ifndef _CLRWL_IS_FALLBACK + if (flw_material.useOverlay) + { + clrwl_overlayColor = texelFetch(flw_overlayTex, clrwl_in[0].flw_vertexOverlay, 0); + clrwl_overlayColor.a = 1.0 - clrwl_overlayColor.a; + } + #else + // Do the average as a best effort attempt + clrwl_overlayColor = (clrwl_in[0].clrwl_overlayColor + clrwl_in[1].clrwl_overlayColor + clrwl_in[2].clrwl_overlayColor) / 3; + clrwl_out.clrwl_overlayColor = clrwl_overlayColor; + #endif + + _clrwl_shader_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/depth.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/depth.glsl new file mode 100644 index 000000000..e92343d78 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/depth.glsl @@ -0,0 +1,13 @@ +// https://github.com/Engine-Room/Flywheel/blob/dc5bc8e64976c69b38abb6965d5cd9033e5a8808/common/src/backend/resources/assets/flywheel/flywheel/internal/depth.glsl + +float _clrwl_linearize_depth(float d, float zNear, float zFar) +{ + float z_n = 2.0 * d - 1.0; + return 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear)); +} + +float _clrwl_delinearize_depth(float linearDepth, float zNear, float zFar) +{ + float z_n = (2.0 * zNear * zFar / linearDepth) - (zFar + zNear); + return 0.5 * (z_n / (zNear - zFar) + 1.0); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/diffuse.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/diffuse.glsl new file mode 100644 index 000000000..896973384 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/diffuse.glsl @@ -0,0 +1,18 @@ +// https://github.com/Engine-Room/Flywheel/blob/dc5bc8e64976c69b38abb6965d5cd9033e5a8808/common/src/backend/resources/assets/flywheel/flywheel/internal/diffuse.glsl + +float clrwl_diffuse(vec3 normal) { + vec3 n2 = normal * normal * vec3(.6, .25, .8); + return min(n2.x + n2.y * (3. + normal.y) + n2.z, 1.); +} + +float clrwl_diffuseNether(vec3 normal) { + vec3 n2 = normal * normal * vec3(.6, .9, .8); + return min(n2.x + n2.y + n2.z, 1.); +} + +float clrwl_diffuseFromLightDirections(vec3 normal) { + // We assume the directions are normalized before upload. + float light0 = max(0.0, dot(flw_light0Direction, normal)); + float light1 = max(0.0, dot(flw_light1Direction, normal)); + return min(1.0, (light0 + light1) * 0.6 + 0.4); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/fog_distance.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/fog_distance.glsl new file mode 100644 index 000000000..922b2baf8 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/fog_distance.glsl @@ -0,0 +1,23 @@ +// https://github.com/Engine-Room/Flywheel/blob/dc5bc8e64976c69b38abb6965d5cd9033e5a8808/common/src/backend/resources/assets/flywheel/flywheel/internal/fog_distance.glsl + +float _clrwl_sphericalDistance(vec3 relativePos) { + return length(relativePos); +} + +float _clrwl_cylindricalDistance(vec3 relativePos) { + float distXZ = length(relativePos.xz); + float distY = abs(relativePos.y); + return max(distXZ, distY); +} + +float _clrwl_fogDistance(vec3 relativePos, int fogShape) { + if (fogShape == 0) { + return _clrwl_sphericalDistance(relativePos); + } else { + return _clrwl_cylindricalDistance(relativePos); + } +} + +float _clrwl_fogDistance(vec3 worldPos, vec3 cameraPos, int fogShape) { + return _clrwl_fogDistance(worldPos - cameraPos, fogShape); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/apply.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/apply.glsl new file mode 100644 index 000000000..ac280960f --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/apply.glsl @@ -0,0 +1,25 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/draw_command.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" + +layout(local_size_x = _FLW_SUBGROUP_SIZE) in; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict readonly buffer ModelBuffer { + FlwModelDescriptor models[]; +}; + +layout(std430, binding = _FLW_DRAW_BUFFER_BINDING) restrict buffer DrawBuffer { + FlwMeshDrawCommand drawCommands[]; +}; + +// Apply the results of culling to the draw commands. +void main() { + uint drawIndex = gl_GlobalInvocationID.x; + + if (drawIndex >= drawCommands.length()) { + return; + } + + uint modelIndex = drawCommands[drawIndex].modelIndex; + drawCommands[drawIndex].instanceCount = models[modelIndex].instanceCount; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/buffer_bindings.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/buffer_bindings.glsl new file mode 100644 index 000000000..0892bfc6a --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/buffer_bindings.glsl @@ -0,0 +1,15 @@ +// Per culling group +#define _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING (_CLRWL_SSBO_BASE + 0)// transform, cull +#define _FLW_BOUNDING_SPHERE_BUFFER_BINDING (_CLRWL_SSBO_BASE + 1)// transform, cull +#define _FLW_INSTANCE_BUFFER_BINDING (_CLRWL_SSBO_BASE + 2)// transform, draw +#define _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING (_CLRWL_SSBO_BASE + 3)// transform, cull, draw +#define _FLW_MODEL_BUFFER_BINDING (_CLRWL_SSBO_BASE + 4)// transform, cull, zero, apply, draw +#define _FLW_DRAW_BUFFER_BINDING (_CLRWL_SSBO_BASE + 5)// apply, draw + +#define _FLW_INSTANCE_VISIBILITY_BUFFER_BINDING (_CLRWL_SSBO_BASE + 6) + +// Global to the engine +#define _FLW_LIGHT_LUT_BUFFER_BINDING (_CLRWL_SSBO_BASE + 7) +#define _FLW_LIGHT_SECTIONS_BUFFER_BINDING (_CLRWL_SSBO_BASE + 8) + +#define _FLW_MATRIX_BUFFER_BINDING (_CLRWL_SSBO_BASE + 9) diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/api_impl.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/api_impl.glsl new file mode 100644 index 000000000..1b87198df --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/api_impl.glsl @@ -0,0 +1,3 @@ +// Cull shaders may not need all uniforms, but it is +// more consistent if we just provide all uniforms anyways. +#include "celeritas:internal/uniforms.glsl" diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_common.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_common.glsl new file mode 100644 index 000000000..ac8573b3d --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_common.glsl @@ -0,0 +1,99 @@ +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" + +#ifdef _CLRWL_FRUSTUM_CULLING +// Disgustingly vectorized sphere frustum intersection taking advantage of ahead of time packing. +// Only uses 6 fmas and some boolean ops. +// See also: +// flywheel:uniform/flywheel.glsl +// dev.engine_room.flywheel.lib.math.MatrixMath.writePackedFrustumPlanes +// org.joml.FrustumIntersection.testSphere +bool _flw_testSphere(vec3 center, float radius) +{ + bvec4 xyInside = greaterThanEqual(fma(flw_frustumPlanes.xyX, center.xxxx, fma(flw_frustumPlanes.xyY, center.yyyy, fma(flw_frustumPlanes.xyZ, center.zzzz, flw_frustumPlanes.xyW))), -radius.xxxx); + bvec2 zInside = greaterThanEqual(fma(flw_frustumPlanes.zX, center.xx, fma(flw_frustumPlanes.zY, center.yy, fma(flw_frustumPlanes.zZ, center.zz, flw_frustumPlanes.zW))), -radius.xx); + + return all(xyInside) && all(zInside); +} +#endif + +#ifdef _CLRWL_OCCLUSION_CULLING +bool _clrwl_projectSphere(vec3 c, float r, float znear, float P00, float P11, out vec4 aabb) +{ + // Closest point on the sphere is between the camera and the near plane, don't even attempt to cull. + if (c.z + r > -znear) + { + return false; + } + + vec3 cr = c * r; + float czr2 = c.z * c.z - r * r; + + float vx = sqrt(c.x * c.x + czr2); + float minx = (vx * c.x - cr.z) / (vx * c.z + cr.x); + float maxx = (vx * c.x + cr.z) / (vx * c.z - cr.x); + + float vy = sqrt(c.y * c.y + czr2); + float miny = (vy * c.y + cr.z) / (vy * c.z - cr.y); + float maxy = (vy * c.y - cr.z) / (vy * c.z + cr.y); + + aabb = -vec4(minx, miny, maxx, maxy) * vec4(P00, P11, P00, P11); + + return true; +} + +vec2 _clrwl_clipToUV(vec2 p) +{ + return p * vec2(0.5f) + vec2(0.5f); // clip space -> uv space +} + +vec4 _clrwl_clipToUV(vec4 bounds) +{ + return bounds * vec4(0.5f) + vec4(0.5f); // clip space -> uv space +} + +float _clrwl_computeSphereMinDepth(vec3 c, float r, mat4 p) +{ + float z = c.z + r; + float clip_z = fma(z, p[2][2], p[3][2]); + float clip_w = fma(z, p[2][3], p[3][3]); + + return (clip_z / clip_w) / 2.0 + 0.5; +} + +bool _clrwl_testOcclusionCull(vec3 center, float radius, sampler2D _flw_depthPyramid) +{ + vec4 aabb; + if (!_clrwl_projectSphere(center, radius, _flw_cullData.znear, _flw_cullData.P00, _flw_cullData.P11, aabb)) + { + return true; + } + + aabb = _clrwl_clipToUV(aabb); + + float width = (aabb.z - aabb.x) * _flw_cullData.pyramidWidth; + float height = (aabb.w - aabb.y) * _flw_cullData.pyramidHeight; + + int level = clamp(int(ceil(log2(max(width, height)))), 0, _flw_cullData.pyramidLevels); + + ivec2 levelSize = textureSize(_flw_depthPyramid, level); + + ivec4 levelSizePair = ivec4(levelSize, levelSize); + + ivec4 bounds = ivec4(aabb * vec4(levelSizePair)); + + // Clamp to the texture bounds. + // Since we're not going through a sampler out of bounds texel fetches will return 0. + bounds = clamp(bounds, ivec4(0), levelSizePair - ivec4(1)); + + float depth01 = texelFetch(_flw_depthPyramid, bounds.xw, level).r; + float depth11 = texelFetch(_flw_depthPyramid, bounds.zw, level).r; + float depth10 = texelFetch(_flw_depthPyramid, bounds.zy, level).r; + float depth00 = texelFetch(_flw_depthPyramid, bounds.xy, level).r; + + float depth = max(max(depth00, depth01), max(depth10, depth11)); + float depthSphere = _clrwl_computeSphereMinDepth(center, radius, flw_projection); + + return depthSphere <= depth; +} +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_early.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_early.glsl new file mode 100644 index 000000000..602c34080 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_early.glsl @@ -0,0 +1,87 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/gbuffers_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_INSTANCE_VISIBILITY_BUFFER_BINDING) restrict readonly buffer VisibiliyBuffer { + uint _flw_visibility[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +bool _flw_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + + #ifdef _CLRWL_FRUSTUM_CULLING + isVisible = isVisible && _flw_testSphere(center, radius); + #endif + + return isVisible; +} + +uniform uint clrwl_materialFilter; + +void main() +{ + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint materialBitset = _clrwl_unpackMaterialBitset(_flw_models[modelIndex]); + + if ((materialBitset & clrwl_materialFilter) == 0) + { + return; + } + + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + + if (!_flw_isVisible(instanceIndex, modelIndex)) + { + return; + } + + bool wasVisibleLastFrame = (_flw_visibility[gl_WorkGroupID.x] & localInvocationMask) != 0; + + if (wasVisibleLastFrame) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_full.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_full.glsl new file mode 100644 index 000000000..7c21575ae --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_full.glsl @@ -0,0 +1,88 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/gbuffers_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +#ifdef _CLRWL_OCCLUSION_CULLING +layout(binding = 0) uniform sampler2D _flw_depthPyramid; +#endif + +bool _flw_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + +#ifdef _CLRWL_FRUSTUM_CULLING + isVisible = isVisible && _flw_testSphere(center, radius); +#endif + +#ifdef _CLRWL_OCCLUSION_CULLING + if (isVisible) + { + transformBoundingSphere(flw_view, center, radius); + isVisible = isVisible && _clrwl_testOcclusionCull(center, radius, _flw_depthPyramid); + } +#endif + + return isVisible; +} + +uniform uint clrwl_materialFilter; + +void main() +{ + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint materialBitset = _clrwl_unpackMaterialBitset(_flw_models[modelIndex]); + + if ((materialBitset & clrwl_materialFilter) == 0) + { + return; + } + + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + + if (_flw_isVisible(instanceIndex, modelIndex)) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_late.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_late.glsl new file mode 100644 index 000000000..0b39371b1 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/gbuffers_late.glsl @@ -0,0 +1,119 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/gbuffers_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_INSTANCE_VISIBILITY_BUFFER_BINDING) restrict buffer VisibiliyBuffer { + uint _flw_visibility[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +#ifdef _CLRWL_OCCLUSION_CULLING +layout(binding = 0) uniform sampler2D _flw_depthPyramid; +#endif + +bool _flw_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + + #ifdef _CLRWL_FRUSTUM_CULLING + isVisible = isVisible && _flw_testSphere(center, radius); + #endif + + #ifdef _CLRWL_OCCLUSION_CULLING + if (isVisible) + { + transformBoundingSphere(flw_view, center, radius); + isVisible = isVisible && _clrwl_testOcclusionCull(center, radius, _flw_depthPyramid); + } + #endif + + return isVisible; +} + +#if !_CLRWL_FORCE_DISABLE_SUBGROUP_BALLOT && (defined GL_KHR_shader_subgroup_basic && defined GL_KHR_shader_subgroup_ballot) + #define _CLRWL_USE_SUBGROUP_BALLOT +#endif + +uniform uint clrwl_materialFilter; + +void main() +{ +#ifndef _CLRWL_USE_SUBGROUP_BALLOT + if (gl_LocalInvocationID.x == 0) + { + _flw_visibility[gl_WorkGroupID.x] = 0; + } +#endif + + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint materialBitset = _clrwl_unpackMaterialBitset(_flw_models[modelIndex]); + + if ((materialBitset & clrwl_materialFilter) == 0) + { + return; + } + + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + bool isVisible = _flw_isVisible(instanceIndex, modelIndex); + bool wasVisibleLastFrame = (_flw_visibility[gl_WorkGroupID.x] & localInvocationMask) != 0; + + if (isVisible && !wasVisibleLastFrame) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } + +#ifdef _CLRWL_USE_SUBGROUP_BALLOT + uvec4 visibility = subgroupBallot(isVisible); + + if (subgroupElect()) + { + _flw_visibility[gl_WorkGroupID.x] = visibility.x; + } +#else + if (isVisible) + { + atomicOr(_flw_visibility[gl_WorkGroupID.x], localInvocationMask); + } +#endif +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_common.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_common.glsl new file mode 100644 index 000000000..0b781b931 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_common.glsl @@ -0,0 +1,124 @@ +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" + +bool _clrwl_isSphereInCube(vec3 center, float radius, vec3 origin, float halfLength) +{ + vec3 v = abs(center - origin); + float maxD = max(v.x, max(v.y, v.z)); + return maxD <= halfLength - radius; +} + +bool _clrwl_testSphereDistance(vec3 center, float radius, out bool isVisible) +{ + float reversedCullDist = clrwl_shadowFrustumPlanes.groups[2].X.w; + float cullDist = clrwl_shadowFrustumPlanes.groups[2].Y.w; + + if (_clrwl_isSphereInCube(center, radius, flw_cameraPos, reversedCullDist)) + { + isVisible = true; + return true; + } + + if (!_clrwl_isSphereInCube(center, radius, flw_cameraPos, cullDist)) + { + isVisible = false; + return true; + } + + isVisible = true; + return false; +} + +#ifdef _CLRWL_FRUSTUM_CULLING +bool _clrwl_testSphereOn4Planes(vec3 center, float radius, _ClrwlShadowFrustumPlanesGroup planes) +{ + return all(greaterThanEqual(fma(planes.X, center.xxxx, fma(planes.Y, center.yyyy, fma(planes.Z, center.zzzz, planes.W))), -radius.xxxx)); +} + +bool _clrwl_testSphereOn3Planes(vec3 center, float radius, _ClrwlShadowFrustumPlanesGroup planes) +{ + return all(greaterThanEqual(fma(planes.X.xyz, center.xxx, fma(planes.Y.xyz, center.yyy, fma(planes.Z.xyz, center.zzz, planes.W.xyz))), -radius.xxx)); +} +#endif + +#ifdef _CLRWL_OCCLUSION_CULLING +bool _clrwl_projectSphere(vec3 c, float r, float znear, float P00, float P11, out vec4 aabb) +{ + // Closest point on the sphere is between the camera and the near plane, don't even attempt to cull. + if (c.z + r > -znear) + { + return false; + } + + aabb = vec4(c.x - r, c.y - r, c.x + r, c.y + r) * vec4(P00, P11, P00, P11); + + return true; +} + +vec2 _clrwl_clipToUV(vec2 p) +{ + return p * vec2(0.5f) + vec2(0.5f); // clip space -> uv space +} + +vec4 _clrwl_clipToUV(vec4 bounds) +{ + return bounds * vec4(0.5f) + vec4(0.5f); // clip space -> uv space +} + +float _clrwl_computeSphereMinDepth(vec3 c, float r, mat4 p) +{ + float z = c.z + r; + float clip_z = fma(z, p[2][2], p[3][2]); + float clip_w = fma(z, p[2][3], p[3][3]); + + clip_z = clrwl_distortShadowClipZ(clip_z); + + return (clip_z / clip_w) / 2.0 + 0.5; +} + +bool _clrwl_testOcclusionCull(vec3 center, float radius, sampler2D _flw_depthPyramid) +{ + vec4 aabb; + if (!_clrwl_projectSphere(center, radius, _flw_cullData.znear, _flw_cullData.P00, _flw_cullData.P11, aabb)) + { + return true; + } + + vec2 p01 = _clrwl_clipToUV(clrwl_distortShadowClipXY(aabb.xw)); + vec2 p11 = _clrwl_clipToUV(clrwl_distortShadowClipXY(aabb.zw)); + vec2 p10 = _clrwl_clipToUV(clrwl_distortShadowClipXY(aabb.zy)); + vec2 p00 = _clrwl_clipToUV(clrwl_distortShadowClipXY(aabb.xy)); + + vec2 pMin = min(min(p00, p01), min(p10, p11)); + vec2 pMax = max(max(p00, p01), max(p10, p11)); + + float width = (pMax.x - pMin.x) * _flw_cullData.pyramidWidth; + float height = (pMax.y - pMin.y) * _flw_cullData.pyramidHeight; + + int level = clamp(int(floor(log2(max(width, height)))), 0, _flw_cullData.pyramidLevels); + + ivec2 levelSize = textureSize(_flw_depthPyramid, level); + + ivec2 ip00 = ivec2(pMin * levelSize); + ivec2 ip11 = ivec2(pMax * levelSize); + ivec2 ip01 = ivec2(ip11.x, ip00.y); + ivec2 ip10 = ivec2(ip00.x, ip11.y); + + // Clamp to the texture bounds. + // Since we're not going through a sampler out of bounds texel fetches will return 0. + ip01 = clamp(ip01, ivec2(0), levelSize - ivec2(1)); + ip11 = clamp(ip11, ivec2(0), levelSize - ivec2(1)); + ip10 = clamp(ip10, ivec2(0), levelSize - ivec2(1)); + ip00 = clamp(ip00, ivec2(0), levelSize - ivec2(1)); + + float depth01 = texelFetch(_flw_depthPyramid, ip01, level).r; + float depth11 = texelFetch(_flw_depthPyramid, ip11, level).r; + float depth10 = texelFetch(_flw_depthPyramid, ip10, level).r; + float depth00 = texelFetch(_flw_depthPyramid, ip00, level).r; + + float depth = max(max(depth00, depth01), max(depth10, depth11)); + float depthSphere = _clrwl_computeSphereMinDepth(center, radius, flw_projection); + + return depthSphere <= depth; +} +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_early.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_early.glsl new file mode 100644 index 000000000..6f9f172fd --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_early.glsl @@ -0,0 +1,90 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/shadow_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_INSTANCE_VISIBILITY_BUFFER_BINDING) restrict readonly buffer VisibiliyBuffer { + uint _flw_visibility[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +bool _clrwl_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + + if (_clrwl_testSphereDistance(center, radius, isVisible)) + { + return isVisible; + } + + #ifdef _CLRWL_FRUSTUM_CULLING + if (isVisible) + { + bool inFrustum = _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[0]) + && _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[1]) + && _clrwl_testSphereOn3Planes(center, radius, clrwl_shadowFrustumPlanes.groups[2]); + + isVisible = isVisible && inFrustum; + } + #endif + + return isVisible; +} + +void main() +{ + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + + if (!_clrwl_isVisible(instanceIndex, modelIndex)) + { + return; + } + + bool wasVisibleLastFrame = (_flw_visibility[gl_WorkGroupID.x] & localInvocationMask) != 0; + + if (wasVisibleLastFrame) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_full.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_full.glsl new file mode 100644 index 000000000..16599daa1 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_full.glsl @@ -0,0 +1,91 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/shadow_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +#ifdef _CLRWL_OCCLUSION_CULLING +layout(binding = 0) uniform sampler2D _flw_depthPyramid; +#endif + +bool _clrwl_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + + if (_clrwl_testSphereDistance(center, radius, isVisible)) + { + return isVisible; + } + + #ifdef _CLRWL_FRUSTUM_CULLING + if (isVisible) + { + bool inFrustum = _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[0]) + && _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[1]) + && _clrwl_testSphereOn3Planes(center, radius, clrwl_shadowFrustumPlanes.groups[2]); + + isVisible = isVisible && inFrustum; + } + #endif + + #ifdef _CLRWL_OCCLUSION_CULLING + if (isVisible) + { + transformBoundingSphere(flw_view, center, radius); + isVisible = isVisible && _clrwl_testOcclusionCull(center, radius, _flw_depthPyramid); + } + #endif + + return isVisible; +} + +void main() +{ + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + + if (_clrwl_isVisible(instanceIndex, modelIndex)) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_late.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_late.glsl new file mode 100644 index 000000000..cca53a427 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/cull/shadow_late.glsl @@ -0,0 +1,121 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" +#include "celeritas:internal/indirect/cull/shadow_common.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict writeonly buffer TargetBuffer { + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_INSTANCE_VISIBILITY_BUFFER_BINDING) restrict buffer VisibiliyBuffer { + uint _flw_visibility[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict readonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +#ifdef _CLRWL_OCCLUSION_CULLING +layout(binding = 0) uniform sampler2D _flw_depthPyramid; +#endif + +bool _clrwl_isVisible(uint instanceIndex, uint modelIndex) +{ + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_boundingSpheres[instanceIndex], center, radius); + + bool isVisible = true; + + if (_clrwl_testSphereDistance(center, radius, isVisible)) + { + return isVisible; + } + #ifdef _CLRWL_FRUSTUM_CULLING + if (isVisible) + { + bool inFrustum = _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[0]) + && _clrwl_testSphereOn4Planes(center, radius, clrwl_shadowFrustumPlanes.groups[1]) + && _clrwl_testSphereOn3Planes(center, radius, clrwl_shadowFrustumPlanes.groups[2]); + + isVisible = isVisible && inFrustum; + } + #endif + + #ifdef _CLRWL_OCCLUSION_CULLING + if (isVisible) + { + transformBoundingSphere(flw_view, center, radius); + isVisible = isVisible && _clrwl_testOcclusionCull(center, radius, _flw_depthPyramid); + } + #endif + + return isVisible; +} + +#if !_CLRWL_FORCE_DISABLE_SUBGROUP_BALLOT && (defined GL_KHR_shader_subgroup_basic && defined GL_KHR_shader_subgroup_ballot) + #define _CLRWL_USE_SUBGROUP_BALLOT +#endif + +void main() +{ +#ifndef _CLRWL_USE_SUBGROUP_BALLOT + if (gl_LocalInvocationID.x == 0) + { + _flw_visibility[gl_WorkGroupID.x] = 0; + } +#endif + + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + bool isVisible = _clrwl_isVisible(instanceIndex, modelIndex); + bool wasVisibleLastFrame = (_flw_visibility[gl_WorkGroupID.x] & localInvocationMask) != 0; + + if (isVisible && !wasVisibleLastFrame) + { + uint localIndex = atomicAdd(_flw_models[modelIndex].instanceCount, 1); + uint targetIndex = _flw_models[modelIndex].baseInstance + localIndex; + _flw_instanceIndices[targetIndex] = instanceIndex; + } + +#ifdef _CLRWL_USE_SUBGROUP_BALLOT + uvec4 visibility = subgroupBallot(isVisible); + + if (subgroupElect()) + { + _flw_visibility[gl_WorkGroupID.x] = visibility.x; + } +#else + if (isVisible) + { + atomicOr(_flw_visibility[gl_WorkGroupID.x], localInvocationMask); + } +#endif +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample.glsl new file mode 100644 index 000000000..7ef7b3d06 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample.glsl @@ -0,0 +1,36 @@ +layout(local_size_x = 256) in; + +/// Generates a hierarchical depth buffer. +/// Based on FidelityFX SPD v2.1 https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/blob/d7531ae47d8b36a5d4025663e731a47a38be882f/sdk/include/FidelityFX/gpu/spd/ffx_spd.h#L528 +/// Based on Bevy's more readable implementation https://github.com/JMS55/bevy/blob/ca2c8e63b9562f88c8cd7e1d88a17a4eea20aaf4/crates/bevy_pbr/src/meshlet/downsample_depth.wgsl + +// These are builtins in wgsl but we can trivially emulate them. +uint extractBits(uint e, uint offset, uint count) { + return (e >> offset) & ((1u << count) - 1u); +} + +uint insertBits(uint e, uint newbits, uint offset, uint count) { + uint countMask = ((1u << count) - 1u); + // zero out the bits we're going to replace first + return (e & ~(countMask << offset)) | ((newbits & countMask) << offset); +} + +// I do not understand how this works but it seems cool. +uvec2 remap_for_wave_reduction(uint a) { + return uvec2( + insertBits(extractBits(a, 2u, 3u), a, 0u, 1u), + insertBits(extractBits(a, 3u, 3u), extractBits(a, 1u, 2u), 0u, 2u) + ); +} + +uvec2 get_xy() { + uvec2 sub_xy = remap_for_wave_reduction(gl_LocalInvocationIndex % 64u); + uint x = sub_xy.x + 8u * ((gl_LocalInvocationIndex >> 6u) % 2u); + uint y = sub_xy.y + 8u * (gl_LocalInvocationIndex >> 7u); + return uvec2(x, y); +} + +float reduce_4(vec4 v) { + return max(max(v.x, v.y), max(v.z, v.w)); +} + diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_first.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_first.glsl new file mode 100644 index 000000000..eccce35b4 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_first.glsl @@ -0,0 +1,42 @@ +#include "celeritas:internal/indirect/downsample.glsl" + +layout(binding = 0) uniform sampler2D depth_tex; +layout(binding = 1, r32f) uniform restrict writeonly image2D mip_0; + +float reduce_load_depth_tex(ivec2 tex) { + // NOTE: depth_tex is the actual depth buffer, and mip_0 is the "base" of our depth pyramid and has the next + // smallest Po2 dimensions to depth_tex's dimensions. We dispatch enough invocations to cover the entire mip_0 + // and will very likely oversample depth_tex, but that's okay because we need to ensure conservative coverage. + // All following mip levels are proper halvings of their parents and will not waste any work. + vec2 uv = (vec2(tex) + 0.5) / vec2(imageSize(mip_0)) * 0.5; + return reduce_4(textureGather(depth_tex, uv)); +} + +void downsample_depth_tex(uint x, uint y, ivec2 workgroup_id) { + vec4 v; + + ivec2 tex = workgroup_id * 64 + ivec2(x * 2u, y * 2u); + ivec2 pix = workgroup_id * 32 + ivec2(x, y); + v[0] = reduce_load_depth_tex(tex); + imageStore(mip_0, pix, vec4(v[0])); + + tex = workgroup_id * 64 + ivec2(x * 2u + 32u, y * 2u); + pix = workgroup_id * 32 + ivec2(x + 16u, y); + v[1] = reduce_load_depth_tex(tex); + imageStore(mip_0, pix, vec4(v[1])); + + tex = workgroup_id * 64 + ivec2(x * 2u, y * 2u + 32u); + pix = workgroup_id * 32 + ivec2(x, y + 16u); + v[2] = reduce_load_depth_tex(tex); + imageStore(mip_0, pix, vec4(v[2])); + + tex = workgroup_id * 64 + ivec2(x * 2u + 32u, y * 2u + 32u); + pix = workgroup_id * 32 + ivec2(x + 16u, y + 16u); + v[3] = reduce_load_depth_tex(tex); + imageStore(mip_0, pix, vec4(v[3])); +} + +void main() { + uvec2 xy = get_xy(); + downsample_depth_tex(xy.x, xy.y, ivec2(gl_WorkGroupID.xy)); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_second.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_second.glsl new file mode 100644 index 000000000..e648650ee --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/downsample_second.glsl @@ -0,0 +1,133 @@ +#include "celeritas:internal/indirect/downsample.glsl" + +uniform uint mip_levels; +uniform uint base_mip_level; + +layout(binding = 0, r32f) uniform restrict readonly image2D mip_0; +layout(binding = 1, r32f) uniform restrict writeonly image2D mip_1; +layout(binding = 2, r32f) uniform restrict writeonly image2D mip_2; +layout(binding = 3, r32f) uniform restrict writeonly image2D mip_3; +layout(binding = 4, r32f) uniform restrict writeonly image2D mip_4; +layout(binding = 5, r32f) uniform restrict writeonly image2D mip_5; +layout(binding = 6, r32f) uniform restrict writeonly image2D mip_6; + +shared float[16][16] intermediate_memory; + +float reduce_load_mip_0(ivec2 tex) { + // NOTE: We could bind mip_0 as a sampler2D and use textureGather, + // but it's already written to as an image in a previous pass so I think this is fine. + return reduce_4(vec4( + imageLoad(mip_0, tex + ivec2(0u, 0u)).r, + imageLoad(mip_0, tex + ivec2(0u, 1u)).r, + imageLoad(mip_0, tex + ivec2(1u, 0u)).r, + imageLoad(mip_0, tex + ivec2(1u, 1u)).r + )); +} + +void downsample_mips_0_and_1(uint x, uint y, ivec2 workgroup_id) { + vec4 v; + + ivec2 tex = workgroup_id * 64 + ivec2(x * 4u + 0u, y * 4u + 0u); + ivec2 pix = workgroup_id * 32 + ivec2(x * 2u + 0u, y * 2u + 0u); + v[0] = reduce_load_mip_0(tex); + imageStore(mip_1, pix, vec4(v[0])); + + tex = workgroup_id * 64 + ivec2(x * 4u + 2u, y * 4u + 0u); + pix = workgroup_id * 32 + ivec2(x * 2u + 1u, y * 2u + 0u); + v[1] = reduce_load_mip_0(tex); + imageStore(mip_1, pix, vec4(v[1])); + + tex = workgroup_id * 64 + ivec2(x * 4u + 0u, y * 4u + 2u); + pix = workgroup_id * 32 + ivec2(x * 2u + 0u, y * 2u + 1u); + v[2] = reduce_load_mip_0(tex); + imageStore(mip_1, pix, vec4(v[2])); + + tex = workgroup_id * 64 + ivec2(x * 4u + 2u, y * 4u + 2u); + pix = workgroup_id * 32 + ivec2(x * 2u + 1u, y * 2u + 1u); + v[3] = reduce_load_mip_0(tex); + imageStore(mip_1, pix, vec4(v[3])); + + if (mip_levels <= base_mip_level + 2u) { return; } + + float vr = reduce_4(v); + imageStore(mip_2, workgroup_id * 16 + ivec2(x, y), vec4(vr)); + intermediate_memory[x][y] = vr; +} + +void downsample_mip_2(uint x, uint y, ivec2 workgroup_id, uint local_invocation_index) { + if (local_invocation_index < 64u) { + float v = reduce_4(vec4( + intermediate_memory[x * 2u + 0u][y * 2u + 0u], + intermediate_memory[x * 2u + 1u][y * 2u + 0u], + intermediate_memory[x * 2u + 0u][y * 2u + 1u], + intermediate_memory[x * 2u + 1u][y * 2u + 1u] + )); + imageStore(mip_3, (workgroup_id * 8) + ivec2(x, y), vec4(v)); + intermediate_memory[x * 2u + y % 2u][y * 2u] = v; + } +} + +void downsample_mip_3(uint x, uint y, ivec2 workgroup_id, uint local_invocation_index) { + if (local_invocation_index < 16u) { + float v = reduce_4(vec4( + intermediate_memory[x * 4u + 0u + 0u][y * 4u + 0u], + intermediate_memory[x * 4u + 2u + 0u][y * 4u + 0u], + intermediate_memory[x * 4u + 0u + 1u][y * 4u + 2u], + intermediate_memory[x * 4u + 2u + 1u][y * 4u + 2u] + )); + imageStore(mip_4, (workgroup_id * 4) + ivec2(x, y), vec4(v)); + intermediate_memory[x * 4u + y][y * 4u] = v; + } +} + +void downsample_mip_4(uint x, uint y, ivec2 workgroup_id, uint local_invocation_index) { + if (local_invocation_index < 4u) { + float v = reduce_4(vec4( + intermediate_memory[x * 8u + 0u + 0u + y * 2u][y * 8u + 0u], + intermediate_memory[x * 8u + 4u + 0u + y * 2u][y * 8u + 0u], + intermediate_memory[x * 8u + 0u + 1u + y * 2u][y * 8u + 4u], + intermediate_memory[x * 8u + 4u + 1u + y * 2u][y * 8u + 4u] + )); + imageStore(mip_5, (workgroup_id * 2) + ivec2(x, y), vec4(v)); + intermediate_memory[x + y * 2u][0u] = v; + } +} + +void downsample_mip_5(ivec2 workgroup_id, uint local_invocation_index) { + if (local_invocation_index < 1u) { + float v = reduce_4(vec4( + intermediate_memory[0u][0u], + intermediate_memory[1u][0u], + intermediate_memory[2u][0u], + intermediate_memory[3u][0u] + )); + imageStore(mip_6, workgroup_id, vec4(v)); + } +} + +void downsample_mips_2_to_5(uint x, uint y, ivec2 workgroup_id, uint local_invocation_index) { + if (mip_levels <= base_mip_level + 3u) { return; } + barrier(); + downsample_mip_2(x, y, workgroup_id, local_invocation_index); + + if (mip_levels <= base_mip_level + 4u) { return; } + barrier(); + downsample_mip_3(x, y, workgroup_id, local_invocation_index); + + if (mip_levels <= base_mip_level + 5u) { return; } + barrier(); + downsample_mip_4(x, y, workgroup_id, local_invocation_index); + + if (mip_levels <= base_mip_level + 6u) { return; } + barrier(); + downsample_mip_5(workgroup_id, local_invocation_index); +} + +void main() { + uvec2 xy = get_xy(); + uint x = xy.x; + uint y = xy.y; + + downsample_mips_0_and_1(x, y, ivec2(gl_WorkGroupID.xy)); + downsample_mips_2_to_5(x, y, ivec2(gl_WorkGroupID.xy), gl_LocalInvocationIndex); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/draw_command.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/draw_command.glsl new file mode 100644 index 000000000..9f54d8bdc --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/draw_command.glsl @@ -0,0 +1,23 @@ +struct ClrwlMeshCenter +{ + float x; + float y; + float z; +}; + +struct FlwMeshDrawCommand +{ + uint indexCount; + uint instanceCount; + uint firstIndex; + uint vertexOffset; + uint baseInstance; + + uint modelIndex; + uint matrixIndex; + + uint packedFogAndCutout; + uint packedMaterialProperties; + + ClrwlMeshCenter meshCenter; +}; diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/light.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/light.glsl new file mode 100644 index 000000000..7717ba1e2 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/light.glsl @@ -0,0 +1,21 @@ +#include "flywheel:internal/light_lut.glsl" + +layout(std430, binding = _FLW_LIGHT_LUT_BUFFER_BINDING) restrict readonly buffer FlwLightLut +{ + uint _flw_lightLut[]; +}; + +layout(std430, binding = _FLW_LIGHT_SECTIONS_BUFFER_BINDING) restrict readonly buffer FlwLightSections +{ + uint _flw_lightSections[]; +}; + +uint _flw_indexLut(uint index) +{ + return _flw_lightLut[index]; +} + +uint _flw_indexLight(uint index) +{ + return _flw_lightSections[index]; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.frag new file mode 100644 index 000000000..9651fcac4 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.frag @@ -0,0 +1,9 @@ +#include "celeritas:internal/common.frag" +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/light.glsl" + +void main() +{ + _flw_unpackMaterialProperties(_clrwl_packedMaterial, flw_material); + _clrwl_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.vert new file mode 100644 index 000000000..c7fc3f0f2 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main.vert @@ -0,0 +1,68 @@ +#include "celeritas:internal/common.vert" +#include "celeritas:internal/packed_material.glsl" +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/draw_command.glsl" +#include "celeritas:internal/indirect/light.glsl" +#include "celeritas:internal/indirect/matrices.glsl" + +layout(std430, binding = _FLW_DRAW_INSTANCE_INDEX_BUFFER_BINDING) restrict readonly buffer TargetBuffer +{ + uint _flw_instanceIndices[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict buffer ModelBuffer +{ + FlwModelDescriptor _flw_models[]; +}; + +layout(std430, binding = _FLW_DRAW_BUFFER_BINDING) restrict readonly buffer DrawBuffer +{ + FlwMeshDrawCommand _flw_drawCommands[]; +}; + +#ifdef FLW_EMBEDDED +layout(std430, binding = _FLW_MATRIX_BUFFER_BINDING) restrict buffer MatrixBuffer +{ + FlwMatrices _flw_matrices[]; +}; +#endif + +uniform uint _flw_baseDraw; + +#if __VERSION__ < 460 +#define flw_baseInstance gl_BaseInstanceARB +#define flw_drawId gl_DrawIDARB +#else +#define flw_baseInstance gl_BaseInstance +#define flw_drawId gl_DrawID +#endif + +void main() +{ + uint drawIndex = flw_drawId + _flw_baseDraw; + FlwMeshDrawCommand draw = _flw_drawCommands[drawIndex]; + FlwModelDescriptor model = _flw_models[draw.modelIndex]; + + uint packedMaterialProperties = draw.packedMaterialProperties; + _flw_unpackMaterialProperties(packedMaterialProperties, flw_material); + _clrwl_packedMaterial = packedMaterialProperties; + + #ifdef FLW_EMBEDDED + _flw_unpackMatrices(_flw_matrices[draw.matrixIndex], _flw_modelMatrix, _flw_normalMatrix); + #endif + + int lightEmission; + _clrwl_unpackData(model, _clrwl_entityId, _clrwl_blockEntityId, lightEmission); + _clrwl_meshCenter = vec4(draw.meshCenter.x, draw.meshCenter.y, draw.meshCenter.z, float(lightEmission)); + + #ifdef _FLW_CRUMBLING + uint instanceIndex = flw_baseInstance; + #else + uint instanceIndex = _flw_instanceIndices[flw_baseInstance + gl_InstanceID]; + #endif + + FlwInstance instance = _flw_unpackInstance(instanceIndex); + + _clrwl_main(instance, instanceIndex, draw.vertexOffset); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main_geom.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main_geom.glsl new file mode 100644 index 000000000..87578d179 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/main_geom.glsl @@ -0,0 +1,18 @@ +#include "celeritas:internal/common_geom.glsl" +#include "celeritas:internal/packed_material.glsl" + +void main() +{ + #ifndef _CLRWL_IS_FALLBACK + _flw_unpackMaterialProperties(clrwl_in[0]._clrwl_packedMaterial, flw_material); + #else + clrwl_out._clrwl_packedMaterial = clrwl_in[0]._clrwl_packedMaterial; + clrwl_out._clrwl_entityId = clrwl_in[0]._clrwl_entityId; + clrwl_out._clrwl_blockEntityId = clrwl_in[0]._clrwl_blockEntityId; + #endif + + _clrwl_entityId = clrwl_in[0]._clrwl_entityId; + _clrwl_blockEntityId = clrwl_in[0]._clrwl_blockEntityId; + + _clrwl_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/matrices.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/matrices.glsl new file mode 100644 index 000000000..70ae45d41 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/matrices.glsl @@ -0,0 +1,13 @@ +struct FlwMatrices +{ + mat4 pose; + vec4 normalA; + vec4 normalB; + vec4 normalC; +}; + +void _flw_unpackMatrices(in FlwMatrices mats, out mat4 pose, out mat3 normal) +{ + pose = mats.pose; + normal = mat3(mats.normalA.xyz, mats.normalB.xyz, mats.normalC.xyz); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/model_descriptor.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/model_descriptor.glsl new file mode 100644 index 000000000..75d9b2f1e --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/model_descriptor.glsl @@ -0,0 +1,41 @@ +struct FlwBoundingSphere +{ + float x; + float y; + float z; + float radius; +}; + +struct FlwModelDescriptor +{ + uint instanceCount; + uint baseInstance; + uint matrixIndex; + FlwBoundingSphere boundingSphere; + int entityId; + int blockEntityId; + uint clrwlData; // unused: 26 bits | material: 2 bits | light emission: 4 bits +}; + +void _flw_unpackBoundingSphere(in FlwBoundingSphere sphere, out vec3 center, out float radius) +{ + center = vec3(sphere.x, sphere.y, sphere.z); + radius = sphere.radius; +} + +FlwBoundingSphere _flw_packBoundingSphere(vec3 center, float radius) +{ + return FlwBoundingSphere(center.x, center.y, center.z, radius); +} + +void _clrwl_unpackData(in FlwModelDescriptor desc, out int entityId, out int blockEntityId, out int lightEmission) +{ + entityId = desc.entityId; + blockEntityId = desc.blockEntityId; + lightEmission = int((desc.clrwlData & 0x00000008u) >> 0); +} + +uint _clrwl_unpackMaterialBitset(in FlwModelDescriptor desc) +{ + return (desc.clrwlData & 0x00000030u) >> 4; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/transform.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/transform.glsl new file mode 100644 index 000000000..6cdee3238 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/transform.glsl @@ -0,0 +1,59 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" +#include "celeritas:internal/indirect/matrices.glsl" +#include "celeritas:internal/uniforms.glsl" +#include "flywheel:util/matrix.glsl" + +layout(local_size_x = 32) in; + +layout(std430, binding = _FLW_PAGE_FRAME_DESCRIPTOR_BUFFER_BINDING) restrict readonly buffer PageFrameDescriptorBuffer { + uint _flw_pageFrameDescriptors[]; +}; + +layout(std430, binding = _FLW_BOUNDING_SPHERE_BUFFER_BINDING) restrict writeonly buffer BoundingSphereBuffer { + FlwBoundingSphere _flw_boundingSpheres[]; +}; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict readonly buffer ModelBuffer { + FlwModelDescriptor _flw_models[]; +}; + +layout(std430, binding = _FLW_MATRIX_BUFFER_BINDING) restrict readonly buffer MatrixBuffer { + FlwMatrices _flw_matrices[]; +}; + +void main() +{ + uint pageIndex = gl_WorkGroupID.x << 1u; + + if (pageIndex >= _flw_pageFrameDescriptors.length()) + { + return; + } + + uint modelIndex = _flw_pageFrameDescriptors[pageIndex]; + uint pageValidity = _flw_pageFrameDescriptors[pageIndex + 1]; + uint localInvocationMask = 1u << gl_LocalInvocationID.x; + + if ((localInvocationMask & pageValidity) == 0) + { + return; + } + + uint instanceIndex = gl_GlobalInvocationID.x; + uint matrixIndex = _flw_models[modelIndex].matrixIndex; + + vec3 center; + float radius; + _flw_unpackBoundingSphere(_flw_models[modelIndex].boundingSphere, center, radius); + + FlwInstance instance = _flw_unpackInstance(instanceIndex); + flw_transformBoundingSphere(instance, center, radius); + + if (matrixIndex > 0) + { + transformBoundingSphere(_flw_matrices[matrixIndex].pose, center, radius); + } + + _flw_boundingSpheres[instanceIndex] = _flw_packBoundingSphere(center, radius); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/zero_models.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/zero_models.glsl new file mode 100644 index 000000000..a92a70914 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/indirect/zero_models.glsl @@ -0,0 +1,20 @@ +#include "celeritas:internal/indirect/buffer_bindings.glsl" +#include "celeritas:internal/indirect/model_descriptor.glsl" + +layout(local_size_x = _FLW_SUBGROUP_SIZE) in; + +layout(std430, binding = _FLW_MODEL_BUFFER_BINDING) restrict writeonly buffer ModelBuffer { + FlwModelDescriptor models[]; +}; + +void main() +{ + uint modelIndex = gl_GlobalInvocationID.x; + + if (modelIndex >= models.length()) + { + return; + } + + models[modelIndex].instanceCount = 0; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/light.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/light.glsl new file mode 100644 index 000000000..2c162966e --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/light.glsl @@ -0,0 +1,14 @@ +#include "flywheel:internal/light_lut.glsl" + +uniform usamplerBuffer _flw_lightLut; +uniform usamplerBuffer _flw_lightSections; + +uint _flw_indexLut(uint index) +{ + return texelFetch(_flw_lightLut, int(index)).r; +} + +uint _flw_indexLight(uint index) +{ + return texelFetch(_flw_lightSections, int(index)).r; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.frag new file mode 100644 index 000000000..1a375e4b0 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.frag @@ -0,0 +1,14 @@ +#include "celeritas:internal/common.frag" +#include "flywheel:internal/instancing/light.glsl" + +uniform uint _clrwl_packedMaterialUniform; +uniform int _clrwl_entityIdUniform; +uniform int _clrwl_blockEntityIdUniform; + +void main() +{ + _flw_unpackMaterialProperties(_clrwl_packedMaterialUniform, flw_material); + _clrwl_entityId = _clrwl_entityIdUniform; + _clrwl_blockEntityId = _clrwl_blockEntityIdUniform; + _clrwl_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.vert new file mode 100644 index 000000000..f0219fe8d --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main.vert @@ -0,0 +1,35 @@ +#include "celeritas:internal/common.vert" +#include "celeritas:internal/packed_material.glsl" +#include "celeritas:internal/instancing/light.glsl" + +uniform uint _clrwl_packedMaterialUniform; +uniform int _flw_baseInstance = 0; + +#ifdef FLW_EMBEDDED +uniform mat4 _flw_modelMatrixUniform; +uniform mat3 _flw_normalMatrixUniform; +#endif + +uniform uint _flw_baseVertex; + +uniform int _clrwl_entityIdUniform; +uniform int _clrwl_blockEntityIdUniform; +uniform vec4 _clrwl_meshCenterUniform; + +void main() +{ + _flw_unpackMaterialProperties(_clrwl_packedMaterialUniform, flw_material); + + FlwInstance instance = _flw_unpackInstance(_flw_baseInstance + gl_InstanceID); + + #ifdef FLW_EMBEDDED + _flw_modelMatrix = _flw_modelMatrixUniform; + _flw_normalMatrix = _flw_normalMatrixUniform; + #endif + + _clrwl_entityId = _clrwl_entityIdUniform; + _clrwl_blockEntityId = _clrwl_blockEntityIdUniform; + _clrwl_meshCenter = _clrwl_meshCenterUniform; + + _clrwl_main(instance, gl_InstanceID, _flw_baseVertex); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main_geom.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main_geom.glsl new file mode 100644 index 000000000..a81050274 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/instancing/main_geom.glsl @@ -0,0 +1,17 @@ +#include "celeritas:internal/common_geom.glsl" +#include "celeritas:internal/packed_material.glsl" + +uniform uint _clrwl_packedMaterialUniform; +uniform int _clrwl_entityIdUniform; +uniform int _clrwl_blockEntityIdUniform; + +void main() +{ + #ifndef _CLRWL_IS_FALLBACK + _flw_unpackMaterialProperties(_clrwl_packedMaterialUniform, flw_material); + #endif + + _clrwl_entityId = _clrwl_entityIdUniform; + _clrwl_blockEntityId = _clrwl_blockEntityIdUniform; + _clrwl_main(); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.frag new file mode 100644 index 000000000..3bfad4a6a --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.frag @@ -0,0 +1,135 @@ +#include "celeritas:internal/depth.glsl" +#include "celeritas:internal/diffuse.glsl" +#include "celeritas:internal/oit/wavelet.glsl" +#include "celeritas:internal/colorizer.glsl" + +void clrwl_computeDiscard(vec4 color) +{ + #ifdef _FLW_USE_DISCARD + if (flw_discardPredicate(color)) + { + discard; + } + #endif +} + +#ifndef _CLRWL_IS_FALLBACK +float _clrwl_diffuseFactor() +{ + if (flw_material.cardinalLightingMode == 2u) + { + return clrwl_diffuseFromLightDirections(flw_vertexNormal); + } + else if (flw_material.cardinalLightingMode == 1u) + { + if (flw_constantAmbientLight == 1u) + { + return clrwl_diffuseNether(flw_vertexNormal); + } + else + { + return clrwl_diffuse(flw_vertexNormal); + } + } + else + { + return 1.; + } +} + +void _clrwl_materialFragment_hook() +{ + flw_materialFragment(); + + if (flw_material.useOverlay) + { + clrwl_overlayColor = texelFetch(flw_overlayTex, flw_fragOverlay, 0); + clrwl_overlayColor.a = 1.0 - clrwl_overlayColor.a; + } +} + +void _clrwl_shaderLight_hook() +{ + flw_shaderLight(); + + #ifdef CLRWL_OLD_LIGHTING + flw_fragColor.rgb *= _clrwl_diffuseFactor(); + #endif +} + +void clrwl_getDebugColor(inout vec4 color) +{ + #ifdef _FLW_DEBUG + switch (_flw_debugMode) + { + case 1u: + color = vec4(flw_vertexNormal * .5 + .5, 1.); + break; + case 2u: + color = vec4(clrwl_vertexTangent.xyz * .5 + .5, 1.); + break; + case 3u: + color = mix(vec4(1.0, 0.0, 0.0, 1.0), vec4(0.0, 0.0, 1.0, 0.0), clrwl_vertexTangent.w * .5 + .5); + break; + case 4u: + color = _flw_id2Color(uint(abs(clrwl_vertexEntity.x))); + break; + case 5u: + color = vec4(sign(flw_vertexTexCoord.x - clrwl_vertexMidTexCoord.x), sign(flw_vertexTexCoord.y - clrwl_vertexMidTexCoord.y), 0.0, 1.); + break; + case 6u: + color = vec4(clrwl_vertexMidMesh.xyz / 64.0 * .5 + .5, 1.); + break; + case 7u: + color = vec4(clrwl_vertexMidMesh.w / 5.0, 0.0, 0.0, 1.); + break; + case 8u: + color = _flw_id2Color(clrwl_debugIds.x); + break; + case 9u: + color = vec4(vec2((flw_fragLight * 15.0 + 0.5) / 16.), 0., 1.); + break; + case 10u: + color = vec4(flw_fragOverlay / 16., 0., 1.); + break; + case 11u: + color = vec4(vec3(_clrwl_diffuseFactor()), 1.); + break; + case 12u: + color = _flw_id2Color(clrwl_debugIds.y); + break; + } + #endif +} + +void clrwl_computeFragment(vec4 sampleColor, out vec4 fragColor, out vec2 fragLight, out float ao, out vec4 fragOverlay) +{ + flw_sampleColor = sampleColor; + flw_fragColor = flw_sampleColor * flw_vertexColor; + flw_fragLight = flw_vertexLight; + flw_fragOverlay = flw_vertexOverlay; + + _clrwl_materialFragment_hook(); + + vec4 fragColorBfLight = flw_fragColor; + + _clrwl_shaderLight_hook(); + + if (flw_material.ambientOcclusion) + { + vec3 fragColorLightRatio = flw_fragColor.rgb / fragColorBfLight.rgb; + ao = clamp(max(max(fragColorLightRatio.r, fragColorLightRatio.g), fragColorLightRatio.b), 0.0, 1.0); + } + else + { + ao = 1.0; + } + + clrwl_computeDiscard(flw_fragColor); + clrwl_getDebugColor(flw_fragColor); + + fragColor = flw_fragColor; + fragLight = flw_fragLight + 1.0 / 32.0; + fragOverlay = clrwl_overlayColor; +} +#endif diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.vert new file mode 100644 index 000000000..3b3ab007c --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat.vert @@ -0,0 +1,4 @@ +vec4 ftransform() +{ + return flw_viewProjection * flw_vertexPos; +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat_geom.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat_geom.glsl new file mode 100644 index 000000000..e8e644ac8 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/iris_compat_geom.glsl @@ -0,0 +1,25 @@ +#ifndef _CLRWL_IS_FALLBACK +void clrwl_setVertexOut(int i) +{ + clrwl_out.flw_vertexPos = clrwl_in[i].flw_vertexPos; + clrwl_out.flw_vertexColor = clrwl_in[i].flw_vertexColor; + clrwl_out.flw_vertexTexCoord = clrwl_in[i].flw_vertexTexCoord; + clrwl_out.flw_vertexOverlay = clrwl_in[i].flw_vertexOverlay; + clrwl_out.flw_vertexLight = clrwl_in[i].flw_vertexLight; + clrwl_out.flw_vertexNormal = clrwl_in[i].flw_vertexNormal; + clrwl_out.clrwl_vertexTangent = clrwl_in[i].clrwl_vertexTangent; + +#ifdef CLRWL_IS_INDIRECT + clrwl_out._clrwl_packedMaterial = clrwl_in[i]._clrwl_packedMaterial; + clrwl_out._clrwl_entityId = clrwl_in[i]._clrwl_entityId; + clrwl_out._clrwl_blockEntityId = clrwl_in[i]._clrwl_blockEntityId; +#endif + +#ifdef _FLW_DEBUG + clrwl_out.clrwl_vertexEntity = clrwl_in[i].clrwl_vertexEntity; + clrwl_out.clrwl_vertexMidTexCoord = clrwl_in[i].clrwl_vertexMidTexCoord; + clrwl_out.clrwl_vertexMidMesh = clrwl_in[i].clrwl_vertexMidMesh; + clrwl_out.clrwl_debugIds = clrwl_in[i].clrwl_debugIds; +#endif +} +#endif \ No newline at end of file diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/material.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/material.glsl new file mode 100644 index 000000000..24fab70c9 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/material.glsl @@ -0,0 +1,40 @@ +// https://github.com/Engine-Room/Flywheel/blob/ea9226a8928f5ee085192a1a8763236957cf8c75/common/src/backend/resources/assets/flywheel/flywheel/internal/material.glsl + +const uint FLW_MAT_DEPTH_TEST_OFF = 0u; +const uint FLW_MAT_DEPTH_TEST_NEVER = 1u; +const uint FLW_MAT_DEPTH_TEST_LESS = 2u; +const uint FLW_MAT_DEPTH_TEST_EQUAL = 3u; +const uint FLW_MAT_DEPTH_TEST_LEQUAL = 4u; +const uint FLW_MAT_DEPTH_TEST_GREATER = 5u; +const uint FLW_MAT_DEPTH_TEST_NOTEQUAL = 6u; +const uint FLW_MAT_DEPTH_TEST_GEQUAL = 7u; +const uint FLW_MAT_DEPTH_TEST_ALWAYS = 8u; + +const uint FLW_MAT_TRANSPARENCY_OPAQUE = 0u; +const uint FLW_MAT_TRANSPARENCY_ADDITIVE = 1u; +const uint FLW_MAT_TRANSPARENCY_LIGHTNING = 2u; +const uint FLW_MAT_TRANSPARENCY_GLINT = 3u; +const uint FLW_MAT_TRANSPARENCY_CRUMBLING = 4u; +const uint FLW_MAT_TRANSPARENCY_TRANSLUCENT = 5u; + +const uint FLW_MAT_WRITE_MASK_COLOR_DEPTH = 0u; +const uint FLW_MAT_WRITE_MASK_COLOR = 1u; +const uint FLW_MAT_WRITE_MASK_DEPTH = 2u; + +const uint FLW_MAT_CARDINAL_LIGHTING_MODE_OFF = 0u; +const uint FLW_MAT_CARDINAL_LIGHTING_MODE_CHUNK = 1u; +const uint FLW_MAT_CARDINAL_LIGHTING_MODE_ENTITY = 2u; + +struct FlwMaterial { + bool blur; + bool mipmap; + bool backfaceCulling; + bool polygonOffset; + uint depthTest; + uint transparency; + uint writeMask; + bool useOverlay; + bool useLight; + uint cardinalLightingMode; + bool ambientOcclusion; +}; diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth.frag new file mode 100644 index 000000000..00c190e67 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth.frag @@ -0,0 +1,58 @@ +#include "celeritas:internal/uniform/frame.glsl" +#include "celeritas:internal/oit/wavelet.glsl" +#include "celeritas:internal/depth.glsl" + +uniform sampler2D _flw_depthRange; + +uniform sampler2DArray clrwl_coefficients0; + +float eye_depth_from_normalized_transparency_depth(float tDepth) +{ + vec2 depthRange = texelFetch(_flw_depthRange, ivec2(gl_FragCoord.xy), 0).rg; + + float delta = depthRange.x + depthRange.y; + + return tDepth * delta - depthRange.x; +} + +void main() +{ + float threshold = 0.0001; + + // + // If transmittance an infinite depth is above the threshold, it doesn't ever become + // zero, so we can bail out. + // + float transmittance_at_far_depth = _clrwl_total_transmittance(clrwl_coefficients0, 3); + if (transmittance_at_far_depth > threshold) { + discard; + } + + float normalized_depth_at_zero_transmittance = 1.0; + float sample_depth = 0.5; + float delta = 0.25; + + // + // Quick & Dirty way to binary search through the transmittance function + // looking for a value that's below the threshold. + // + int steps = 6; + for (int i = 0; i < steps; ++i) { + float transmittance = _clrwl_transmittance(clrwl_coefficients0, sample_depth, 3); + if (transmittance <= threshold) { + normalized_depth_at_zero_transmittance = sample_depth; + sample_depth -= delta; + } else { + sample_depth += delta; + } + delta *= 0.5; + } + + // + // Searching inside the transparency depth bounds, so have to transform that to + // a world-space linear-depth and that into a device depth we can output into + // the currently bound depth buffer. + // + float eyeDepth = eye_depth_from_normalized_transparency_depth(normalized_depth_at_zero_transmittance); + gl_FragDepth = _clrwl_delinearize_depth(eyeDepth, _flw_cullData.znear, _flw_cullData.zfar); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth_range.frag b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth_range.frag new file mode 100644 index 000000000..86d0e573c --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/depth_range.frag @@ -0,0 +1,12 @@ +out vec2 _flw_depthRange_out; + +void _clrwl_post_shader() +{ + float linearDepth = _clrwl_linear_depth(); + + // Pad the depth by some unbalanced epsilons because minecraft has a lot of single-quad tranparency. + // The unbalance means our fragment will be considered closer to the screen in the normalization, + // which helps prevent unnecessary noise as it'll be closer to the edge of our tent function. + + _flw_depthRange_out = vec2(-linearDepth + 1e-5, linearDepth + 1e-2); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/wavelet.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/wavelet.glsl new file mode 100644 index 000000000..7d445e081 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/oit/wavelet.glsl @@ -0,0 +1,202 @@ +// ------------------------------------------------------------------------- +// WRITING +// ------------------------------------------------------------------------- + +void _clrwl_add_to_index(inout vec4[4] coefficients, int index, float addend) +{ + coefficients[index >> 2][index & 3] = addend; +} + +void _clrwl_add_absorbance(inout vec4[4] coefficients, float signal, float depth, int rank) +{ + int count = 1 << (rank + 1); + + depth *= float(count-1) / count; + + int index = clamp(int(floor(depth * count)), 0, count - 1); + index += count - 1; + + for (int i = 0; i < (rank+1); ++i) { + int power = rank - i; + float power_f = float(power); + + int new_index = (index - 1) >> 1; + float k = float((new_index + 1) & ((1 << power) - 1)); + + float wavelet_sign = float(((index & 1) << 1) - 1); + float wavelet_phase = float((index + 1) & 1) * exp2(-power_f); + float addend = fma(fma(-exp2(-power_f), k, depth), wavelet_sign, wavelet_phase) * exp2(power_f * 0.5) * signal; + _clrwl_add_to_index(coefficients, new_index, addend); + + index = new_index; + } + + float addend = fma(signal, -depth, signal); + _clrwl_add_to_index(coefficients, count - 1, addend); +} + +void _clrwl_add_transmittance(inout vec4[4] coefficients, float transmittance, float depth, int rank) +{ + float absorbance = -log(max(transmittance, 0.00001));// transforming the signal from multiplicative transmittance to additive absorbance + _clrwl_add_absorbance(coefficients, absorbance, depth, rank); +} + +// ------------------------------------------------------------------------- +// READING +// ------------------------------------------------------------------------- + +// TODO: maybe we could reduce the number of texel fetches below? +float _clrwl_get_coefficients(in sampler2DArray coefficients, int index) { + return texelFetch(coefficients, ivec3(gl_FragCoord.xy, index >> 2), 0)[index & 3]; +} + +/// Compute the total absorbance, as if at infinite depth. +float _clrwl_total_absorbance(in sampler2DArray coefficients, int rank) +{ + int count = 1 << (rank + 1); + + float scale_coefficient = _clrwl_get_coefficients(coefficients, count - 1); + if (scale_coefficient == 0) { + return 0; + } + + int index_b = count - 1; + + index_b += count - 1; + + float b = scale_coefficient; + + for (int i = 0; i < (rank+1); ++i) { + int power = rank - i; + + int new_index_b = (index_b - 1) >> 1; + int wavelet_sign_b = ((index_b & 1) << 1) - 1; + float coeff_b = _clrwl_get_coefficients(coefficients, new_index_b); + b -= exp2(float(power) * 0.5) * coeff_b * wavelet_sign_b; + index_b = new_index_b; + } + + return b; +} + +/// Compute the absorbance at a given normalized depth. +float _clrwl_absorbance(in sampler2DArray coefficients, float depth, int rank) +{ + int count = 1 << (rank + 1); + + float scale_coefficient = _clrwl_get_coefficients(coefficients, count - 1); + if (scale_coefficient == 0) { + return 0; + } + + depth *= float(count-1) / count; + + float coefficient_depth = depth * count; + int index_b = clamp(int(floor(coefficient_depth)), 0, count - 1); + bool sample_a = index_b >= 1; + int index_a = sample_a ? (index_b - 1) : index_b; + + index_b += count - 1; + index_a += count - 1; + + float b = scale_coefficient; + float a = sample_a ? scale_coefficient : 0; + + for (int i = 0; i < (rank+1); ++i) { + int power = rank - i; + + int new_index_b = (index_b - 1) >> 1; + int wavelet_sign_b = ((index_b & 1) << 1) - 1; + float coeff_b = _clrwl_get_coefficients(coefficients, new_index_b); + b -= exp2(float(power) * 0.5) * coeff_b * wavelet_sign_b; + index_b = new_index_b; + + if (sample_a) { + int new_index_a = (index_a - 1) >> 1; + int wavelet_sign_a = ((index_a & 1) << 1) - 1; + float coeff_a = (new_index_a == new_index_b) ? coeff_b : _clrwl_get_coefficients(coefficients, new_index_a); + a -= exp2(float(power) * 0.5) * coeff_a * wavelet_sign_a; + index_a = new_index_a; + } + } + + float t = coefficient_depth >= count ? 1.0 : fract(coefficient_depth); + + return mix(a, b, t); +} + +/// Compute the absorbance at a given normalized depth, +/// correcting for self-occlusion by undoing the previously recorded absorbance event. +float _clrwl_signal_corrected_absorbance(in sampler2DArray coefficients, float depth, float signal, int rank) +{ + int count = 1 << (rank + 1); + + float scale_coefficient = _clrwl_get_coefficients(coefficients, count - 1); + if (scale_coefficient == 0) { + return 0; + } + + depth *= float(count-1) / count; + + float scale_coefficient_addend = fma(signal, -depth, signal); + scale_coefficient -= scale_coefficient_addend; + + float coefficient_depth = depth * count; + int index_b = clamp(int(floor(coefficient_depth)), 0, count - 1); + bool sample_a = index_b >= 1; + int index_a = sample_a ? (index_b - 1) : index_b; + + index_b += count - 1; + index_a += count - 1; + + float b = scale_coefficient; + float a = sample_a ? scale_coefficient : 0; + + for (int i = 0; i < (rank+1); ++i) { + int power = rank - i; + float power_f = float(power); + + int new_index_b = (index_b - 1) >> 1; + int wavelet_sign_b = ((index_b & 1) << 1) - 1; + float coeff_b = _clrwl_get_coefficients(coefficients, new_index_b); + + float wavelet_phase_b = ((index_b + 1) & 1) * exp2(-power_f); + float k = float((new_index_b + 1) & ((1 << power) - 1)); + float addend = fma(fma(-exp2(-power_f), k, depth), wavelet_sign_b, wavelet_phase_b) * exp2(power_f * 0.5) * signal; + coeff_b -= addend; + + b -= exp2(power_f * 0.5) * coeff_b * wavelet_sign_b; + index_b = new_index_b; + + if (sample_a) { + int new_index_a = (index_a - 1) >> 1; + int wavelet_sign_a = ((index_a & 1) << 1) - 1; + float coeff_a = (new_index_a == new_index_b) ? coeff_b : _clrwl_get_coefficients(coefficients, new_index_a);// No addend here on purpose, the original signal didn't contribute to this coefficient + a -= exp2(power_f * 0.5) * coeff_a * wavelet_sign_a; + index_a = new_index_a; + } + } + + float t = coefficient_depth >= count ? 1.0 : fract(coefficient_depth); + + return mix(a, b, t); +} + +// Helpers below to deal directly in transmittance. + +#define _CRLWL_ABSORBANCE_TO_TRANSMITTANCE(a) clamp(exp(-(a)), 0., 1.) + +float _clrwl_total_transmittance(in sampler2DArray coefficients, int rank) +{ + return _CRLWL_ABSORBANCE_TO_TRANSMITTANCE(_clrwl_total_absorbance(coefficients, rank)); +} + +float _clrwl_transmittance(in sampler2DArray coefficients, float depth, int rank) +{ + return _CRLWL_ABSORBANCE_TO_TRANSMITTANCE(_clrwl_absorbance(coefficients, depth, rank)); +} + +float _clrwl_signal_corrected_transmittance(in sampler2DArray coefficients, float depth, float signal, int rank) +{ + return _CRLWL_ABSORBANCE_TO_TRANSMITTANCE(_clrwl_signal_corrected_absorbance(coefficients, depth, signal, rank)); +} diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/packed_material.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/packed_material.glsl new file mode 100644 index 000000000..fd4baaefa --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/packed_material.glsl @@ -0,0 +1,61 @@ +// https://github.com/Engine-Room/Flywheel/blob/ea9226a8928f5ee085192a1a8763236957cf8c75/common/src/backend/resources/assets/flywheel/flywheel/internal/packed_material.glsl + +// The number of bits each property takes up +const uint _FLW_BLUR_LENGTH = 1u; +const uint _FLW_MIPMAP_LENGTH = 1u; +const uint _FLW_BACKFACE_CULLING_LENGTH = 1u; +const uint _FLW_POLYGON_OFFSET_LENGTH = 1u; +const uint _FLW_DEPTH_TEST_LENGTH = 4u; +const uint _FLW_TRANSPARENCY_LENGTH = 3u; +const uint _FLW_WRITE_MASK_LENGTH = 2u; +const uint _FLW_USE_OVERLAY_LENGTH = 1u; +const uint _FLW_USE_LIGHT_LENGTH = 1u; +const uint _FLW_CARDINAL_LIGHTING_MODE_LENGTH = 2u; +const uint _FLW_AMBIENT_OCCLUSION_LENGTH = 1u; + +// The bit offset of each property +const uint _FLW_BLUR_OFFSET = 0u; +const uint _FLW_MIPMAP_OFFSET = _FLW_BLUR_OFFSET + _FLW_BLUR_LENGTH; +const uint _FLW_BACKFACE_CULLING_OFFSET = _FLW_MIPMAP_OFFSET + _FLW_MIPMAP_LENGTH; +const uint _FLW_POLYGON_OFFSET_OFFSET = _FLW_BACKFACE_CULLING_OFFSET + _FLW_BACKFACE_CULLING_LENGTH; +const uint _FLW_DEPTH_TEST_OFFSET = _FLW_POLYGON_OFFSET_OFFSET + _FLW_POLYGON_OFFSET_LENGTH; +const uint _FLW_TRANSPARENCY_OFFSET = _FLW_DEPTH_TEST_OFFSET + _FLW_DEPTH_TEST_LENGTH; +const uint _FLW_WRITE_MASK_OFFSET = _FLW_TRANSPARENCY_OFFSET + _FLW_TRANSPARENCY_LENGTH; +const uint _FLW_USE_OVERLAY_OFFSET = _FLW_WRITE_MASK_OFFSET + _FLW_WRITE_MASK_LENGTH; +const uint _FLW_USE_LIGHT_OFFSET = _FLW_USE_OVERLAY_OFFSET + _FLW_USE_OVERLAY_LENGTH; +const uint _FLW_CARDINAL_LIGHTING_MODE_OFFSET = _FLW_USE_LIGHT_OFFSET + _FLW_USE_LIGHT_LENGTH; +const uint _FLW_AMBIENT_OCCLUSION_OFFSET = _FLW_CARDINAL_LIGHTING_MODE_OFFSET + _FLW_CARDINAL_LIGHTING_MODE_LENGTH; + +// The bit mask for each property +const uint _FLW_BLUR_MASK = ((1u << _FLW_BLUR_LENGTH) - 1u) << _FLW_BLUR_OFFSET; +const uint _FLW_MIPMAP_MASK = ((1u << _FLW_MIPMAP_LENGTH) - 1u) << _FLW_MIPMAP_OFFSET; +const uint _FLW_BACKFACE_CULLING_MASK = ((1u << _FLW_BACKFACE_CULLING_LENGTH) - 1u) << _FLW_BACKFACE_CULLING_OFFSET; +const uint _FLW_POLYGON_OFFSET_MASK = ((1u << _FLW_POLYGON_OFFSET_LENGTH) - 1u) << _FLW_POLYGON_OFFSET_OFFSET; +const uint _FLW_DEPTH_TEST_MASK = ((1u << _FLW_DEPTH_TEST_LENGTH) - 1u) << _FLW_DEPTH_TEST_OFFSET; +const uint _FLW_TRANSPARENCY_MASK = ((1u << _FLW_TRANSPARENCY_LENGTH) - 1u) << _FLW_TRANSPARENCY_OFFSET; +const uint _FLW_WRITE_MASK_MASK = ((1u << _FLW_WRITE_MASK_LENGTH) - 1u) << _FLW_WRITE_MASK_OFFSET; +const uint _FLW_USE_OVERLAY_MASK = ((1u << _FLW_USE_OVERLAY_LENGTH) - 1u) << _FLW_USE_OVERLAY_OFFSET; +const uint _FLW_USE_LIGHT_MASK = ((1u << _FLW_USE_LIGHT_LENGTH) - 1u) << _FLW_USE_LIGHT_OFFSET; +const uint _FLW_CARDINAL_LIGHTING_MODE_MASK = ((1u << _FLW_CARDINAL_LIGHTING_MODE_LENGTH) - 1u) << _FLW_CARDINAL_LIGHTING_MODE_OFFSET; +const uint _FLW_AMBIENT_OCCLUSION_MASK = ((1u << _FLW_AMBIENT_OCCLUSION_LENGTH) - 1u) << _FLW_AMBIENT_OCCLUSION_OFFSET; + +// Packed format: +// ambientOcclusion[1] | cardinalLightingMode[2] | useLight[1] | useOverlay[1] | writeMask[2] | transparency[3] | depthTest[4] | polygonOffset[1] | backfaceCulling[1] | mipmap[1] | blur[1] +void _flw_unpackMaterialProperties(uint p, out FlwMaterial m) { + m.blur = (p & _FLW_BLUR_MASK) != 0u; + m.mipmap = (p & _FLW_MIPMAP_MASK) != 0u; + m.backfaceCulling = (p & _FLW_BACKFACE_CULLING_MASK) != 0u; + m.polygonOffset = (p & _FLW_POLYGON_OFFSET_MASK) != 0u; + m.depthTest = (p & _FLW_DEPTH_TEST_MASK) >> _FLW_DEPTH_TEST_OFFSET; + m.transparency = (p & _FLW_TRANSPARENCY_MASK) >> _FLW_TRANSPARENCY_OFFSET; + m.writeMask = (p & _FLW_WRITE_MASK_MASK) >> _FLW_WRITE_MASK_OFFSET; + m.useOverlay = (p & _FLW_USE_OVERLAY_MASK) != 0u; + m.useLight = (p & _FLW_USE_LIGHT_MASK) != 0u; + m.cardinalLightingMode = (p & _FLW_CARDINAL_LIGHTING_MODE_MASK) >> _FLW_CARDINAL_LIGHTING_MODE_OFFSET; + m.ambientOcclusion = (p & _FLW_AMBIENT_OCCLUSION_MASK) != 0; +} + +void _flw_unpackUint2x16(uint s, out uint hi, out uint lo) { + hi = (s >> 16) & 0xFFFFu; + lo = s & 0xFFFFu; +} \ No newline at end of file diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/fog.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/fog.glsl new file mode 100644 index 000000000..27c9ab3a7 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/fog.glsl @@ -0,0 +1,7 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/fog.glsl + +layout(std140) uniform _ClrwlFogUniforms { + vec4 flw_fogColor; + vec2 flw_fogRange; + int flw_fogShape; +}; diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/frame.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/frame.glsl new file mode 100644 index 000000000..fa11bc8dc --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/frame.glsl @@ -0,0 +1,35 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl + +layout(std140) uniform _ClrwlFrameUniforms +{ + ivec4 _flw_renderOrigin; + + vec4 _flw_cameraPos; + vec4 _flw_cameraPosPrev; + vec4 _flw_cameraLook; + vec4 _flw_cameraLookPrev; + vec2 flw_cameraRot; + vec2 flw_cameraRotPrev; + +/** 0 means no fluid. Use FLW_CAMERA_IN_FLUID_* defines to detect fluid type. */ + uint flw_cameraInFluid; +/** 0 means no block. Use FLW_CAMERA_IN_BLOCK_* defines to detect block type. */ + uint flw_cameraInBlock; + + uint _flw_debugMode; + + float _flw_oitNoise; +}; + +#define flw_renderOrigin (_flw_renderOrigin.xyz) +#define flw_cameraPos (_flw_cameraPos.xyz) +#define flw_cameraLook (_flw_cameraLook.xyz) +#define flw_cameraPosPrev (_flw_cameraPosPrev.xyz) +#define flw_cameraLookPrev (_flw_cameraLookPrev.xyz) + +#define FLW_CAMERA_IN_FLUID_WATER 1 +#define FLW_CAMERA_IN_FLUID_LAVA 2 +#define FLW_CAMERA_IN_FLUID_UNKNOWN 0xFFFFFFFFu + +#define FLW_CAMERA_IN_BLOCK_POWDER_SNOW 1 +#define FLW_CAMERA_IN_BLOCK_UNKNOWN 0xFFFFFFFFu diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/level.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/level.glsl new file mode 100644 index 000000000..391d6aa15 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/level.glsl @@ -0,0 +1,42 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/level.glsl + +layout(std140) uniform _ClrwlLevelUniforms { + vec4 flw_skyColor; + vec4 flw_cloudColor; + + vec4 _flw_light0Direction; + vec4 _flw_light1Direction; + +/** The current day number of the level. */ + uint flw_levelDay; +/** The current fraction of the current day that has elapsed. */ + float flw_timeOfDay; + + uint flw_levelHasSkyLight; + + float flw_sunAngle; + + float flw_moonBrightness; +/** There are normally only 8 moon phases. */ + uint flw_moonPhase; + + uint flw_isRaining; + float flw_rainLevel; + uint flw_isThundering; + float flw_thunderLevel; + + float flw_skyDarken; + + uint flw_constantAmbientLight; + +/** Use FLW_DIMENSION_* ids to determine the dimension. May eventually be implemented for custom dimensions. */ + uint flw_dimension; +}; + +#define flw_light0Direction (_flw_light0Direction.xyz) +#define flw_light1Direction (_flw_light1Direction.xyz) + +#define FLW_DIMENSION_OVERWORLD 0 +#define FLW_DIMENSION_NETHER 1 +#define FLW_DIMENSION_END 2 +#define FLW_DIMENSION_UNKNOWN 0xFFFFFFFFu diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/options.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/options.glsl new file mode 100644 index 000000000..b3666aef1 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/options.glsl @@ -0,0 +1,20 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/options.glsl +// options.glsl - Houses uniforms for many of the game's settings, focusing on video and accessibility settings. + +layout(std140) uniform _ClrwlOptionsUniforms { + float flw_brightnessOption; + uint flw_fovOption; + float flw_distortionOption; + float flw_glintSpeedOption; + float flw_glintStrengthOption; + uint flw_biomeBlendOption; + uint flw_smoothLightingOption; + uint flw_viewBobbingOption; + + uint flw_highContrastOption; + float flw_textBackgroundOpacityOption; + uint flw_textBackgroundForChatOnlyOption; + float flw_darknessPulsingOption; + float flw_damageTiltOption; + uint flw_hideLightningFlashesOption; +}; diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/pass.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/pass.glsl new file mode 100644 index 000000000..632342fc2 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/pass.glsl @@ -0,0 +1,79 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl + +struct _FlwFrustumPlanes +{ + vec4 xyX; // + vec4 xyY; // + vec4 xyZ; // + vec4 xyW; // + vec2 zX; // + vec2 zY; // + vec2 zZ; // + vec2 zW; // +}; + +struct _FlwCullData +{ + float znear; + float zfar; + float P00; + float P11; + float pyramidWidth; + float pyramidHeight; + int pyramidLevels; + uint orthographic; +}; + +struct _ClrwlShadowFrustumPlanesGroup +{ + vec4 X; // + vec4 Y; // + vec4 Z; // + vec4 W; // +}; + +struct _ClrwlShadowFrustumPlanes +{ + // Up to 11 planes can be sent, but we're declaring enough floats for 12 planes. + // To keep data compact and packed for efficient computation, group[2] D plane is assigned to metadata: + // * groups[2].X.w = reversed cull distance + // * groups[2].Y.w = cull distance + // * groups[2].Z.w = - + // * groups[2].W.w = - + _ClrwlShadowFrustumPlanesGroup[3] groups; +}; + +layout(std140) uniform _ClrwlPassUniforms +{ +#if defined _CLRWL_IS_GBUFFERS_PASS + _FlwFrustumPlanes flw_frustumPlanes; +#elif defined _CLRWL_IS_SHADOW_PASS + _ClrwlShadowFrustumPlanes clrwl_shadowFrustumPlanes; +#endif + + _FlwCullData _flw_cullData; + + mat4 flw_view; + mat4 flw_viewInverse; + mat4 flw_viewPrev; + mat4 flw_projection; + mat4 flw_projectionInverse; + mat4 flw_projectionPrev; + mat4 flw_viewProjection; + mat4 flw_viewProjectionInverse; + mat4 flw_viewProjectionPrev; + + mat3 clrwl_normal; + + vec2 flw_viewportSize; + float flw_aspectRatio; + float flw_defaultLineWidth; + float flw_viewDistance; + + uint flw_ticks; + float flw_partialTick; + float flw_renderTicks; + float flw_renderSeconds; + float flw_systemSeconds; + uint flw_systemMillis; +}; diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/player.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/player.glsl new file mode 100644 index 000000000..49d168304 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniform/player.glsl @@ -0,0 +1,38 @@ +// https://github.com/Engine-Room/Flywheel/blob/610b1683f3ed0fef5cd387a126bd2c530a9c2ead/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/player.glsl +// player.glsl - Holds uniforms for player state. + +layout (std140) uniform _ClrwlPlayerUniforms { + vec4 _flw_eyePos; + + /** Alpha is 1 if any team color is present, 0 otherwise. */ + vec4 flw_teamColor; + + /** The brightness at the player's eye position. */ + vec2 flw_eyeBrightness; + + /** Brightness of the brightest light that the player is holding, 0-1. */ + float flw_heldLight; + /** 0 means no fluid. Use FLW_PLAYER_EYE_IN_FLUID_* defines to detect fluid type. */ + uint flw_playerEyeInFluid; + /** 0 means no block. Use FLW_PLAYER_EYE_IN_BLOCK_* defines to detect block type. */ + uint flw_playerEyeInBlock; + + uint flw_playerCrouching; + uint flw_playerSleeping; + uint flw_playerSwimming; + uint flw_playerFallFlying; + + uint flw_shiftKeyDown; + + /** 0 = survival, 1 = creative, 2 = adventure, 3 = spectator. */ + uint flw_gameMode; +}; + +#define flw_eyePos _flw_eyePos.xyz + +#define FLW_PLAYER_EYE_IN_FLUID_WATER 1 +#define FLW_PLAYER_EYE_IN_FLUID_LAVA 2 +#define FLW_PLAYER_EYE_IN_FLUID_UNKNOWN 0xFFFFFFFFu + +#define FLW_PLAYER_EYE_IN_BLOCK_POWDER_SNOW 1 +#define FLW_PLAYER_EYE_IN_BLOCK_UNKNOWN 0xFFFFFFFFu diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniforms.glsl b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniforms.glsl new file mode 100644 index 000000000..d534a51f2 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/uniforms.glsl @@ -0,0 +1,6 @@ +#include "celeritas:internal/uniform/frame.glsl" +#include "celeritas:internal/uniform/pass.glsl" +#include "celeritas:internal/uniform/level.glsl" +#include "celeritas:internal/uniform/player.glsl" +#include "celeritas:internal/uniform/fog.glsl" +#include "celeritas:internal/uniform/options.glsl" diff --git a/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/vertex_input.vert b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/vertex_input.vert new file mode 100644 index 000000000..98f5fcc37 --- /dev/null +++ b/modern/src/main/flywheel_resources/assets/celeritas/flywheel/internal/vertex_input.vert @@ -0,0 +1,25 @@ +in vec3 _flw_aPos; +in vec4 _flw_aColor; +in vec2 _flw_aTexCoord; +in vec2 _flw_aLight; +in vec4 _flw_aNormal; +in vec2 _clrwl_aEntity; +in vec2 _clrwl_aMidTexCoord; +in vec4 _clrwl_aTangent; +in vec4 _clrwl_aMidBlock; +in vec2 _flw_aOverlay; + +void _clrwl_layoutVertex() { + flw_vertexPos = vec4(_flw_aPos, 1.0); + flw_vertexColor = _flw_aColor; + flw_vertexTexCoord = _flw_aTexCoord; + // Integer vertex attributes explode on some drivers for some draw calls, so get the driver + // to cast the int to a float so we can cast it back to an int and reliably get a sane value. + flw_vertexOverlay = ivec2(_flw_aOverlay); + flw_vertexLight = _flw_aLight / 256.0; + flw_vertexNormal = _flw_aNormal.xyz; // w is garbage + clrwl_vertexEntity = _clrwl_aEntity; + clrwl_vertexMidTexCoord = _clrwl_aMidTexCoord; + clrwl_vertexTangent = _clrwl_aTangent; + clrwl_vertexMidMesh = _clrwl_aMidBlock; // at_midBlock.w does not exists on 1.20.1 +} diff --git a/modern/src/main/flywheel_resources/mixins.oculus.compat.flywheel.json b/modern/src/main/flywheel_resources/mixins.oculus.compat.flywheel.json new file mode 100644 index 000000000..5d9ee5ffb --- /dev/null +++ b/modern/src/main/flywheel_resources/mixins.oculus.compat.flywheel.json @@ -0,0 +1,18 @@ +{ + "required": true, + "minVersion": "0.8", + "plugin": "net.irisshaders.iris.compat.flywheel.mixin.OculusFlywheelCompatMixinPlugin", + "package": "net.irisshaders.iris.compat.flywheel.mixin", + "compatibilityLevel": "JAVA_17", + "client": [ + "BlockEntityStorageMixin", + "EntityStorageMixin", + "MeshEmitterManagerMixin", + "MeshEmitterMixin", + "TransformingVertexConsumerMixin" + ], + "injectors": { + "defaultRequire": 1 + }, + "mixins": [] +} diff --git a/modern/src/main/modern_java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java b/modern/src/main/modern_java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java index db3215819..5fce4223d 100644 --- a/modern/src/main/modern_java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java +++ b/modern/src/main/modern_java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java @@ -46,6 +46,10 @@ public class WorldRenderingSettings { return reloadRequired; } + public void requireReload() { + reloadRequired = true; + } + public void clearReloadRequired() { reloadRequired = false; } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/Iris.java b/modern/src/main/shaders_java/net/irisshaders/iris/Iris.java index 059cae975..d21f8dbea 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/Iris.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/Iris.java @@ -6,6 +6,9 @@ import com.mojang.blaze3d.platform.InputConstants; //? if fabric //import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.compat.flywheel.ClrwlBackend; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.config.IrisConfig; import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.irisshaders.iris.gl.shader.StandardMacros; @@ -563,6 +566,11 @@ public class Iris { // Very important - we need to re-create the pipeline straight away. // https://github.com/IrisShaders/Iris/issues/1330 if (Minecraft.getInstance().level != null) { + // Flywheel engines are built against the previous pack's programs; the level renderer reload resets them. + if (Colorwheel.isFlywheelLoaded()) { + WorldRenderingSettings.INSTANCE.requireReload(); + } + Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimension()); } } @@ -799,6 +807,11 @@ public class Iris { CeleritasShaders.logger().error("", e); } + // Options load before Flywheel freezes its backend registry at the first resource reload. + if (Colorwheel.isFlywheelLoaded()) { + ClrwlBackend.init(); + } + initialized = true; } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/config/IrisConfig.java b/modern/src/main/shaders_java/net/irisshaders/iris/config/IrisConfig.java index 818d9d494..7d1cee457 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/config/IrisConfig.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/config/IrisConfig.java @@ -51,6 +51,13 @@ public class IrisConfig { @Getter @Setter private boolean enableTextureMaterialFallback; + /** + * Whether Flywheel content renders through a pack's regular gbuffers programs when the pack has no Flywheel + * programs of its own. + */ + @Getter + @Setter + private boolean flywheelFallbackMode; public IrisConfig(Path propertiesPath) { shaderPackName = null; @@ -152,6 +159,7 @@ public class IrisConfig { disableUpdateMessage = "true".equals(properties.getProperty("disableUpdateMessage")); blockUnknownShaders = "true".equals(properties.getProperty("blockUnknownShaders")); enableTextureMaterialFallback = !"false".equals(properties.getProperty("enableTextureMaterialFallback")); + flywheelFallbackMode = "true".equals(properties.getProperty("flywheelFallbackMode")); try { IrisVideoSettings.shadowDistance = Integer.parseInt(properties.getProperty("maxShadowRenderDistance", "32")); IrisVideoSettings.colorSpace = ColorSpace.valueOf(properties.getProperty("colorSpace", "SRGB")); @@ -194,6 +202,7 @@ public class IrisConfig { properties.setProperty("disableUpdateMessage", disableUpdateMessage ? "true" : "false"); properties.setProperty("blockUnknownShaders", blockUnknownShaders ? "true" : "false"); properties.setProperty("enableTextureMaterialFallback", enableTextureMaterialFallback ? "true" : "false"); + properties.setProperty("flywheelFallbackMode", flywheelFallbackMode ? "true" : "false"); properties.setProperty("maxShadowRenderDistance", String.valueOf(IrisVideoSettings.shadowDistance)); properties.setProperty("colorSpace", IrisVideoSettings.colorSpace.name()); properties.setProperty("renderScale", IrisVideoSettings.renderScale.name()); diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/gl/blending/BlendModeOverride.java b/modern/src/main/shaders_java/net/irisshaders/iris/gl/blending/BlendModeOverride.java index 22cb8f238..f6da2fb6a 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/gl/blending/BlendModeOverride.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/gl/blending/BlendModeOverride.java @@ -9,6 +9,10 @@ public class BlendModeOverride { this.blendMode = blendMode; } + public BlendMode getBlendMode() { + return blendMode; + } + public static void restore() { BlendModeStorage.restoreBlend(); } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/gl/shader/StandardMacros.java b/modern/src/main/shaders_java/net/irisshaders/iris/gl/shader/StandardMacros.java index bc9bebe34..850d7fd56 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/gl/shader/StandardMacros.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/gl/shader/StandardMacros.java @@ -5,6 +5,8 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlUtil; import net.irisshaders.iris.Iris; import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.engine.ClrwlRenderingPhase; import net.irisshaders.iris.helpers.StringPair; import net.irisshaders.iris.pathways.HandRenderer; import net.irisshaders.iris.pipeline.WorldRenderingPhase; @@ -53,6 +55,15 @@ public class StandardMacros { define(standardDefines, getVendor()); define(standardDefines, getRenderer()); define(standardDefines, "IS_IRIS"); + + if (Colorwheel.isFlywheelLoaded()) { + define(standardDefines, "HAS_COLORWHEEL"); + define(standardDefines, "COLORWHEEL_VERSION", Colorwheel.FORMATTED_VERSION); + + for (ClrwlRenderingPhase phase : ClrwlRenderingPhase.values()) { + define(standardDefines, "CLRWL_RENDER_STAGE_" + phase.name(), Integer.toString(phase.getValue())); + } + } define(standardDefines, "IRIS_HAS_TRANSLUCENCY_SORTING"); define(standardDefines, "IRIS_TAG_SUPPORT", "2"); diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/MixinLevelRenderer.java b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/MixinLevelRenderer.java index f3ebb52bc..7b3ca27f5 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/MixinLevelRenderer.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/MixinLevelRenderer.java @@ -10,6 +10,7 @@ import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.layer.IsOutlineRenderStateShard; import net.irisshaders.iris.layer.OuterWrappedRenderType; import net.irisshaders.iris.pathways.HandRenderer; +import net.irisshaders.iris.pipeline.ShaderRenderPassEvent; import net.irisshaders.iris.pipeline.WorldRenderingPhase; import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.shadows.frustum.fallback.NonCullingFrustum; @@ -150,6 +151,21 @@ public class MixinLevelRenderer { } } + @Inject(method = "renderLevel", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", args = "ldc=string")) + private void iris$afterTranslucents(CallbackInfo ci, + //? if <1.20.6 { + @Local(ordinal = 0, argsOnly = true) PoseStack poseStack, + @Local(ordinal = 0, argsOnly = true) Matrix4f projection, + //?} else { + /*@Local(ordinal = 0, argsOnly = true) Matrix4f modelMatrix, + @Local(ordinal = 1, argsOnly = true) Matrix4f projection, + *///?} + @Local(ordinal = 0, argsOnly = true) Camera camera) { + //? if <1.20.6 + Matrix4f modelMatrix = poseStack.last().pose(); + ShaderRenderPassEvent.BUS.post(new ShaderRenderPassEvent(ShaderRenderPassEvent.Stage.TRANSLUCENT, modelMatrix, projection, camera, celeritas$currentTickDelta)); + } + // Setup shadow terrain & render shadows before the main terrain setup. We need to do things in this order to // avoid breaking other mods such as Light Overlay: https://github.com/IrisShaders/Iris/issues/1356 diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBlockRenderDispatcher.java b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBlockRenderDispatcher.java new file mode 100644 index 000000000..58abe6dad --- /dev/null +++ b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBlockRenderDispatcher.java @@ -0,0 +1,42 @@ +package net.irisshaders.iris.mixin.vertices; + +import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.ExtendedDataHelper; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import org.embeddedt.embeddium.impl.util.WorldUtil; +import org.spongepowered.asm.mixin.Mixin; + +/** + * The fluid counterpart of {@link MixinModelBlockRenderer}. + */ +@Mixin(BlockRenderDispatcher.class) +public class MixinBlockRenderDispatcher { + @WrapMethod(method = "renderLiquid") + private void iris$beginFluid(BlockPos pos, BlockAndTintGetter level, VertexConsumer consumer, BlockState blockState, + FluidState fluidState, Operation original) { + if (!(consumer instanceof BlockSensitiveBufferBuilder blockSensitive)) { + original.call(pos, level, consumer, blockState, fluidState); + return; + } + + var blockStateIds = WorldRenderingSettings.INSTANCE.getBlockStateIds(); + short id = blockStateIds == null ? -1 : (short) blockStateIds.getOrDefault(fluidState.createLegacyBlock(), -1); + + blockSensitive.beginBlock(id, ExtendedDataHelper.FLUID_RENDER_TYPE, (byte) WorldUtil.getLightEmission(blockState, level, pos), + pos.getX(), pos.getY(), pos.getZ()); + + try { + original.call(pos, level, consumer, blockState, fluidState); + } finally { + blockSensitive.endBlock(); + } + } +} diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java index 8d56c3bdb..86cf48f87 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java @@ -60,6 +60,8 @@ public abstract class MixinBufferBuilder implements BlockSensitiveBufferBuilder, @Unique private short currentRenderType = -1; @Unique + private byte currentLightEmission; + @Unique private int currentLocalPosX; @Unique private int currentLocalPosY; @@ -218,7 +220,7 @@ public abstract class MixinBufferBuilder implements BlockSensitiveBufferBuilder, float x = buffer.getFloat(posIndex); float y = buffer.getFloat(posIndex + 4); float z = buffer.getFloat(posIndex + 8); - this.putInt(0, ExtendedDataHelper.computeMidBlock(x, y, z, currentLocalPosX, currentLocalPosY, currentLocalPosZ)); + this.putInt(0, ExtendedDataHelper.computeMidBlock(x, y, z, currentLocalPosX, currentLocalPosY, currentLocalPosZ) | ((currentLightEmission & 0xFF) << 24)); this.nextElement(); } @@ -259,9 +261,10 @@ public abstract class MixinBufferBuilder implements BlockSensitiveBufferBuilder, } @Override - public void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ) { + public void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ) { this.currentBlock = block; this.currentRenderType = renderType; + this.currentLightEmission = lightEmission; this.currentLocalPosX = localPosX; this.currentLocalPosY = localPosY; this.currentLocalPosZ = localPosZ; @@ -271,6 +274,7 @@ public abstract class MixinBufferBuilder implements BlockSensitiveBufferBuilder, public void endBlock() { this.currentBlock = -1; this.currentRenderType = -1; + this.currentLightEmission = 0; this.currentLocalPosX = 0; this.currentLocalPosY = 0; this.currentLocalPosZ = 0; @@ -300,7 +304,7 @@ public abstract class MixinBufferBuilder implements BlockSensitiveBufferBuilder, long position = pointer + iris$offsetPosition; int midBlock = ExtendedDataHelper.computeMidBlock( MemoryUtil.memGetFloat(position), MemoryUtil.memGetFloat(position + 4), MemoryUtil.memGetFloat(position + 8), - currentLocalPosX, currentLocalPosY, currentLocalPosZ); + currentLocalPosX, currentLocalPosY, currentLocalPosZ) | ((currentLightEmission & 0xFF) << 24); MemoryUtil.memPutInt(pointer + iris$offsetMidBlock, midBlock); } else { long entity = pointer + iris$offsetEntity; @@ -439,6 +443,8 @@ public abstract class MixinBufferBuilder implements VertexConsumer, BlockSensiti @Unique private short currentRenderType = -1; @Unique + private byte currentLightEmission; + @Unique private int currentLocalPosX; @Unique private int currentLocalPosY; @@ -489,7 +495,7 @@ public abstract class MixinBufferBuilder implements VertexConsumer, BlockSensiti if (midBlock != -1L) { MemoryUtil.memPutInt(midBlock, ExtendedDataHelper.computeMidBlock( MemoryUtil.memGetFloat(position), MemoryUtil.memGetFloat(position + 4L), MemoryUtil.memGetFloat(position + 8L), - currentLocalPosX, currentLocalPosY, currentLocalPosZ)); + currentLocalPosX, currentLocalPosY, currentLocalPosZ) | ((currentLightEmission & 0xFF) << 24)); } } else { long entity = beginElement(IrisVertexFormats.ENTITY_ID_ELEMENT); @@ -557,9 +563,10 @@ public abstract class MixinBufferBuilder implements VertexConsumer, BlockSensiti } @Override - public void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ) { + public void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ) { currentBlock = block; currentRenderType = renderType; + currentLightEmission = lightEmission; currentLocalPosX = localPosX; currentLocalPosY = localPosY; currentLocalPosZ = localPosZ; @@ -569,6 +576,7 @@ public abstract class MixinBufferBuilder implements VertexConsumer, BlockSensiti public void endBlock() { currentBlock = -1; currentRenderType = -1; + currentLightEmission = 0; currentLocalPosX = 0; currentLocalPosY = 0; currentLocalPosZ = 0; diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinModelBlockRenderer.java b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinModelBlockRenderer.java new file mode 100644 index 000000000..2dad08f0a --- /dev/null +++ b/modern/src/main/shaders_java/net/irisshaders/iris/mixin/vertices/MixinModelBlockRenderer.java @@ -0,0 +1,54 @@ +package net.irisshaders.iris.mixin.vertices; + +import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.ExtendedDataHelper; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +//? if forge +import net.minecraftforge.client.model.data.ModelData; +//? if neoforge +//import net.neoforged.neoforge.client.model.data.ModelData; +import org.embeddedt.embeddium.impl.util.WorldUtil; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Tells block-sensitive consumers which block they receive, so block models tesselated outside of chunk meshing + * (Flywheel models, falling blocks) carry the block's ID and light emission. + */ +@Mixin(ModelBlockRenderer.class) +public class MixinModelBlockRenderer { + @WrapMethod(method = "tesselateBlock(Lnet/minecraft/world/level/BlockAndTintGetter;Lnet/minecraft/client/resources/model/BakedModel;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;ZLnet/minecraft/util/RandomSource;JI" + + /*? if forge {*/ "Lnet/minecraftforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;" + /*?}*/ + /*? if neoforge {*/ /*"Lnet/neoforged/neoforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;" + *//*?}*/ + ")V"/*? if forgelike {*/, remap = false/*?}*/) + private void iris$beginBlock(BlockAndTintGetter level, BakedModel model, BlockState state, BlockPos pos, PoseStack poseStack, + VertexConsumer consumer, boolean checkSides, RandomSource random, long seed, int packedOverlay, + /*? if forgelike {*/ModelData modelData, RenderType renderType, /*?}*/Operation original) { + if (!(consumer instanceof BlockSensitiveBufferBuilder blockSensitive)) { + original.call(level, model, state, pos, poseStack, consumer, checkSides, random, seed, packedOverlay/*? if forgelike {*/, modelData, renderType/*?}*/); + return; + } + + var blockStateIds = WorldRenderingSettings.INSTANCE.getBlockStateIds(); + short id = blockStateIds == null ? -1 : (short) blockStateIds.getOrDefault(state, -1); + + blockSensitive.beginBlock(id, ExtendedDataHelper.BLOCK_RENDER_TYPE, (byte) WorldUtil.getLightEmission(state, level, pos), + pos.getX(), pos.getY(), pos.getZ()); + + try { + original.call(level, model, state, pos, poseStack, consumer, checkSides, random, seed, packedOverlay/*? if forgelike {*/, modelData, renderType/*?}*/); + } finally { + blockSensitive.endBlock(); + } + } +} diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java index 803efd032..6a66aa84c 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java @@ -109,9 +109,11 @@ import org.lwjgl.opengl.GL43C; import org.taumc.celeritas.shaders.CeleritasShaders; import java.io.IOException; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.OptionalInt; @@ -1251,6 +1253,39 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend }); } + public RenderTargets getRenderTargets() { + return renderTargets; + } + + public ShadowRenderTargets getShadowRenderTargets() { + return shadowTargetsSupplier.get(); + } + + private enum FlywheelPass { SOLID, TRANSLUCENT, SHADOW } + + private record FlywheelFramebufferKey(ProgramSource source, FlywheelPass pass) {} + + // Flywheel engines are rebuilt more often than the pipeline, so they share these rather than creating their own. + private final Map flywheelFramebuffers = new HashMap<>(); + + /** + * Returns the gbuffers framebuffer for a Flywheel program. The render targets own it and keep it valid across + * resizes, so callers must not destroy it. + */ + public GlFramebuffer getFlywheelGbuffersFramebuffer(ProgramSource source, boolean afterTranslucent) { + var key = new FlywheelFramebufferKey(source, afterTranslucent ? FlywheelPass.TRANSLUCENT : FlywheelPass.SOLID); + return flywheelFramebuffers.computeIfAbsent(key, k -> renderTargets.createGbufferFramebuffer( + afterTranslucent ? flippedAfterTranslucent : flippedAfterPrepare, source.getDirectives().getDrawBuffers())); + } + + /** + * Returns the shadow framebuffer for a Flywheel program, owned by the shadow render targets. + */ + public GlFramebuffer getFlywheelShadowFramebuffer(ProgramSource source) { + return flywheelFramebuffers.computeIfAbsent(new FlywheelFramebufferKey(source, FlywheelPass.SHADOW), + k -> getShadowRenderTargets().createShadowFramebuffer(ImmutableSet.of(), source.getDirectives().getDrawBuffers())); + } + @Override public void destroy() { destroyed = true; diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/ShaderRenderPassEvent.java b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/ShaderRenderPassEvent.java new file mode 100644 index 000000000..129bb0b87 --- /dev/null +++ b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/ShaderRenderPassEvent.java @@ -0,0 +1,57 @@ +package net.irisshaders.iris.pipeline; + +import net.minecraft.client.Camera; +import org.joml.Matrix4fc; +import org.taumc.celeritas.api.eventbus.EmbeddiumEvent; +import org.taumc.celeritas.api.eventbus.EventHandlerRegistrar; + +/** + * Posted at the points of a shader pack's frame where renderers outside the level renderer draw their geometry. + * Internal to Celeritas; not a supported extension point. + */ +public class ShaderRenderPassEvent extends EmbeddiumEvent { + public static final EventHandlerRegistrar BUS = new EventHandlerRegistrar<>(); + + public enum Stage { + /** Shadow pass, before block entities. */ + SHADOW_SOLID, + /** Shadow pass, before translucent terrain. Only posted if the pack renders translucent shadows. */ + SHADOW_TRANSLUCENT, + /** Main pass, after translucent terrain and the remaining translucent entity batches. */ + TRANSLUCENT + } + + private final Stage stage; + private final Matrix4fc modelView; + private final Matrix4fc projection; + private final Camera camera; + private final float partialTick; + + public ShaderRenderPassEvent(Stage stage, Matrix4fc modelView, Matrix4fc projection, Camera camera, float partialTick) { + this.stage = stage; + this.modelView = modelView; + this.projection = projection; + this.camera = camera; + this.partialTick = partialTick; + } + + public Stage getStage() { + return stage; + } + + public Matrix4fc getModelView() { + return modelView; + } + + public Matrix4fc getProjection() { + return projection; + } + + public Camera getCamera() { + return camera; + } + + public float getPartialTick() { + return partialTick; + } +} diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/foss_transform/ShaderTransformer.java b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/foss_transform/ShaderTransformer.java index 4c209cb0b..afdc6afc3 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/foss_transform/ShaderTransformer.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/pipeline/foss_transform/ShaderTransformer.java @@ -120,6 +120,25 @@ public class ShaderTransformer { return builder.toString(); } + /** + * Renames identifiers that are keywords to the AST parser but valid in the given GLSL version, prefixing them + * with {@code iris_renamed_}. + */ + public static String renameReservedWords(String input, int version) { + input = replaceTexture(input); + + for (int reservedVersion : versionedReservedWords.keySet()) { + if (version < reservedVersion) { + for (String reservedWord : versionedReservedWords.get(reservedVersion)) { + String newName = "iris_renamed_" + reservedWord; + input = input.replaceAll("\\b" + reservedWord + "\\b", newName); + } + } + } + + return input; + } + private static

Map transformInternal(String name, Map inputs, Patch patchType, P parameters) { EnumMap result = new EnumMap<>(ShaderType.class); EnumMap types = new EnumMap<>(ShaderType.class); @@ -154,20 +173,7 @@ public class ShaderTransformer { String profileString = "#version " + versionString + " " + profile + "\n"; - // This handles some reserved keywords which cause the AST parser to fail - // but aren't necessarily invalid for GLSL versions prior to 400. This simple - // renames the matching strings and prefixes them with iris_renamed_ - - input = replaceTexture(input); - - for (int version : versionedReservedWords.keySet()) { - if (versionInt < version) { - for (String reservedWord : versionedReservedWords.get(version)) { - String newName = "iris_renamed_" + reservedWord; - input = input.replaceAll("\\b" + reservedWord + "\\b", newName); - } - } - } + input = renameReservedWords(input, versionInt); var parsedShader = ShaderParser.parseShader(input); var translationUnit = parsedShader.full(); diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/ShaderPack.java b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/ShaderPack.java index 4c78b8935..b1110f2aa 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/ShaderPack.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/ShaderPack.java @@ -9,6 +9,8 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlShaderProperties; import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.gl.texture.TextureDefinition; import net.irisshaders.iris.helpers.StringPair; @@ -76,6 +78,8 @@ public class ShaderPack { private final Set activeFeatures; private final Function sourceProvider; private final ShaderProperties shaderProperties; + @Nullable + private final ClrwlShaderProperties clrwlProperties; private final List dimensionIds; @Getter private Map dimensionMap; @@ -276,6 +280,13 @@ public class ShaderPack { return source; }; + // Read before any ProgramSet is built, since each one parses its Flywheel programs against these. + this.clrwlProperties = Colorwheel.isFlywheelLoaded() + ? loadProperties(root, "colorwheel.properties") + .map(source -> new ClrwlShaderProperties(source, shaderPackOptions, finalEnvironmentDefines1)) + .orElseGet(ClrwlShaderProperties::new) + : null; + this.base = new ProgramSet(AbsolutePackPath.fromAbsolutePath("/" + dimensionMap.getOrDefault(new NamespacedId("*", "*"), "")), sourceProvider, shaderProperties, this); this.overrides = new HashMap<>(); @@ -567,6 +578,18 @@ public class ShaderPack { return languageMap; } + public ShaderProperties getShaderProperties() { + return shaderProperties; + } + + /** + * @return the parsed {@code colorwheel.properties}, or {@code null} when Flywheel is not installed + */ + @Nullable + public ClrwlShaderProperties getClrwlProperties() { + return clrwlProperties; + } + public ShaderPackOptions getShaderPackOptions() { return shaderPackOptions; } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java index a15e6bb92..fd9f22a4f 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java @@ -1,6 +1,8 @@ package net.irisshaders.iris.shaderpack.include; import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlProgramId; import net.irisshaders.iris.shaderpack.loading.ProgramArrayId; import net.irisshaders.iris.shaderpack.loading.ProgramId; @@ -69,6 +71,14 @@ public class ShaderPackSourceNames { } } + if (Colorwheel.isFlywheelLoaded()) { + for (ClrwlProgramId programId : ClrwlProgramId.values()) { + addStarts(potentialFileNames, programId.programName()); + } + + addComputeStarts(potentialFileNames, "clrwl_shadow_distort"); + } + return potentialFileNames.build(); } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java index 3dccab038..5a99de8d9 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java @@ -1,5 +1,7 @@ package net.irisshaders.iris.shaderpack.programs; +import net.irisshaders.iris.compat.flywheel.Colorwheel; +import net.irisshaders.iris.compat.flywheel.shaderpack.ClrwlPackPrograms; import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.gl.blending.BlendModeOverride; import net.irisshaders.iris.shaderpack.ShaderPack; @@ -12,6 +14,7 @@ import net.irisshaders.iris.shaderpack.properties.PackDirectives; import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import org.jetbrains.annotations.Nullable; import org.taumc.celeritas.shaders.CeleritasShaders; import java.util.*; @@ -66,6 +69,8 @@ public class ProgramSet implements ProgramSetInterface { private final ProgramSource dhShadow; private final ShaderPack pack; private final ProgramSource gbuffersDamagedBlock; + @Nullable + private final ClrwlPackPrograms clrwlPrograms; public ProgramSet(AbsolutePackPath directory, Function sourceProvider, ShaderProperties shaderProperties, ShaderPack pack) { @@ -154,6 +159,10 @@ public class ProgramSet implements ProgramSetInterface { this.finalCompute = readComputeArray(directory, sourceProvider, "final", shaderProperties); locateDirectives(); + + this.clrwlPrograms = Colorwheel.isFlywheelLoaded() + ? new ClrwlPackPrograms(directory, sourceProvider, this, shaderProperties, pack.getClrwlProperties()) + : null; } @SafeVarargs @@ -167,7 +176,7 @@ public class ProgramSet implements ProgramSetInterface { return Optional.empty(); } - private static ProgramSource readProgramSource(AbsolutePackPath directory, + public static ProgramSource readProgramSource(AbsolutePackPath directory, Function sourceProvider, String program, ProgramSet programSet, ShaderProperties properties, boolean readTesselation) { return readProgramSource(directory, sourceProvider, program, programSet, properties, null, readTesselation); @@ -217,7 +226,7 @@ public class ProgramSet implements ProgramSetInterface { defaultBlendModeOverride); } - private static ComputeSource readComputeSource(AbsolutePackPath directory, + public static ComputeSource readComputeSource(AbsolutePackPath directory, Function sourceProvider, String program, ProgramSet programSet, ShaderProperties properties) { AbsolutePackPath computePath = directory.resolve(program + ".csh"); @@ -572,4 +581,12 @@ public class ProgramSet implements ProgramSetInterface { public ShaderPack getPack() { return pack; } + + /** + * @return this set's Flywheel programs, or {@code null} when Flywheel is not installed + */ + @Nullable + public ClrwlPackPrograms getClrwlPrograms() { + return clrwlPrograms; + } } diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowMatrices.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowMatrices.java index c6a5b979d..0a354ddb9 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowMatrices.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowMatrices.java @@ -5,8 +5,8 @@ import com.mojang.math.Axis; import org.joml.Matrix4f; public class ShadowMatrices { - private static final float NEAR = 0.05f; - private static final float FAR = 256.0f; + public static final float NEAR = 0.05f; + public static final float FAR = 256.0f; /** * Distance the shadow camera is pulled back from the player camera along the shadow light vector, applied by diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowRenderer.java b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowRenderer.java index 443f02116..4f6ed5266 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowRenderer.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/shadows/ShadowRenderer.java @@ -16,6 +16,7 @@ import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gui.option.IrisVideoSettings; import net.irisshaders.iris.mixin.LevelRendererAccessor; import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.pipeline.ShaderRenderPassEvent; import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.properties.PackDirectives; import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; @@ -529,6 +530,8 @@ public class ShadowRenderer { levelRenderer.getLevel().getProfiler().popPush("build blockentities"); + ShaderRenderPassEvent.BUS.post(new ShaderRenderPassEvent(ShaderRenderPassEvent.Stage.SHADOW_SOLID, MODELVIEW, shadowProjection, playerCamera, tickDelta)); + Predicate blockEntityFilter; if (shouldRenderLightBlockEntities && !shouldRenderBlockEntities) { blockEntityFilter = be -> WorldUtil.getLightEmission(be.getBlockState(), be.getLevel(), be.getBlockPos()) > 0; @@ -561,6 +564,8 @@ public class ShadowRenderer { // It doesn't matter a ton, since this just means that they won't be sorted in the normal rendering pass. // Just something to watch out for, however... if (shouldRenderTranslucent) { + ShaderRenderPassEvent.BUS.post(new ShaderRenderPassEvent(ShaderRenderPassEvent.Stage.SHADOW_TRANSLUCENT, MODELVIEW, shadowProjection, playerCamera, tickDelta)); + //? if <1.20.6 { levelRenderer.invokeRenderChunkLayer(RenderType.translucent(), modelView, cameraX, cameraY, cameraZ, shadowProjection); //?} else diff --git a/modern/src/main/shaders_java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java b/modern/src/main/shaders_java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java index 5aa38163a..438dd8f39 100644 --- a/modern/src/main/shaders_java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java +++ b/modern/src/main/shaders_java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java @@ -1,7 +1,7 @@ package net.irisshaders.iris.vertices; public interface BlockSensitiveBufferBuilder { - void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ); + void beginBlock(short block, short renderType, byte lightEmission, int localPosX, int localPosY, int localPosZ); void endBlock(); }