diff --git a/dependencies.gradle b/dependencies.gradle index 4476be2f5..68fd3f88a 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -60,7 +60,7 @@ dependencies { compileOnly('org.jetbrains:annotations:26.0.2') api("com.github.GTNewHorizons:GTNHLib:0.8.21:dev") shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 - shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") { + shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-25.g3a943bb") { exclude module: "antlr4" // we only want to shadow the runtime module } shadowImplementation("org.antlr:antlr4-runtime:4.13.2") diff --git a/src/main/java/net/coderbot/iris/Iris.java b/src/main/java/net/coderbot/iris/Iris.java index f84f05685..0a51df094 100644 --- a/src/main/java/net/coderbot/iris/Iris.java +++ b/src/main/java/net/coderbot/iris/Iris.java @@ -16,6 +16,9 @@ import net.coderbot.iris.config.IrisConfig; import net.coderbot.iris.gl.shader.StandardMacros; import net.coderbot.iris.gui.screen.ShaderPackScreen; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.pipeline.transform.ShaderTransformer; +import net.coderbot.iris.pipeline.transform.TransformPatcher; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; import net.coderbot.iris.pipeline.PipelineManager; import net.coderbot.iris.pipeline.WorldRenderingPipeline; @@ -54,8 +57,18 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinWorkerThread; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.stream.Stream; import java.util.zip.ZipError; import java.util.zip.ZipException; @@ -82,6 +95,8 @@ public class Iris { private static String currentPackName; @Getter private static boolean initialized; + @Getter + private static int shaderPackLoadId = 0; private static PipelineManager pipelineManager; @Getter @@ -99,6 +114,175 @@ public class Iris { @Getter private static boolean fallback; + /** + * Lazy executor for parallelizing shader transformations during shader pack loading. + * Creates threads on demand and shuts down after a period of inactivity. + */ + public static final class ShaderTransformExecutor { + private static final long IDLE_TIMEOUT_SECONDS = 120; + private static final int THREAD_COUNT = Math.max(2, Math.min(12, Runtime.getRuntime().availableProcessors() / 2)); + + private static final Object lock = new Object(); + private static ExecutorService executor; + private static ScheduledExecutorService scheduler; + private static volatile long lastActivityTime; + private static final AtomicInteger inFlight = new AtomicInteger(0); + private static boolean idleCheckScheduled; + + private ShaderTransformExecutor() {} + + private static void noteActivity() { + lastActivityTime = System.nanoTime(); + } + + public static ExecutorService get() { + synchronized (lock) { + noteActivity(); + + if (executor != null && !executor.isShutdown()) { + return executor; + } + + executor = new ForkJoinPool( + THREAD_COUNT, + pool -> { + ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + t.setName("Shader-Transform-" + t.getPoolIndex()); + t.setDaemon(true); + return t; + }, + null, // UncaughtExceptionHandler + true // asyncMode - FIFO, better for independent tasks + ); + logger.debug("Created shader transform executor with " + THREAD_COUNT + " threads"); + + if (scheduler == null || scheduler.isShutdown()) { + scheduler = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "Shader-Transform-Scheduler"); + t.setDaemon(true); + return t; + }); + } + if (!idleCheckScheduled) { + idleCheckScheduled = true; + scheduleIdleCheck(IDLE_TIMEOUT_SECONDS); + } + + return executor; + } + } + + private static void scheduleIdleCheck(long delaySeconds) { + try { + scheduler.schedule(ShaderTransformExecutor::checkIdleShutdown, delaySeconds, TimeUnit.SECONDS); + } catch (Exception e) { + // If scheduling fails, reset the flag so a future get() can try again + idleCheckScheduled = false; + logger.warn("Failed to schedule idle check", e); + } + } + + /** + * Ensures the executor exists and begins spinning up worker threads. + * Intended for UI entrypoints (eg. shader settings screen open). + */ + public static void prepare() { + // Submit empty tasks to warm up all worker threads without blocking the UI thread. + for (int i = 0; i < THREAD_COUNT; i++) { + submitTracked(() -> { }); + } + } + + /** + * Warm up the threadpool by running a representative shader transformation. + */ + public static void warmup() { + final String vertexShader = "#version 120\nvoid main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }"; + final String fragmentShader = "#version 120\nvoid main() { gl_FragColor = vec4(1.0); }"; + try { + submitTracked(() -> { + TransformPatcher.patchComposite(vertexShader, null, fragmentShader); + TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true)); + }).get(); + } catch (Exception e) { + logger.warn("Warmup failed", e); + } + } + + public static CompletableFuture submitTracked(Supplier supplier) { + Objects.requireNonNull(supplier); + noteActivity(); + inFlight.incrementAndGet(); + try { + return CompletableFuture.supplyAsync(() -> { + try { + return supplier.get(); + } finally { + noteActivity(); + inFlight.decrementAndGet(); + } + }, get()); + } catch (Exception e) { + inFlight.decrementAndGet(); + throw e; + } + } + + public static CompletableFuture submitTracked(Runnable runnable) { + Objects.requireNonNull(runnable); + noteActivity(); + inFlight.incrementAndGet(); + try { + return CompletableFuture.runAsync(() -> { + try { + runnable.run(); + } finally { + noteActivity(); + inFlight.decrementAndGet(); + } + }, get()); + } catch (Exception e) { + inFlight.decrementAndGet(); + throw e; + } + } + + private static void checkIdleShutdown() { + synchronized (lock) { + final ExecutorService current = executor; + if (current == null || current.isShutdown()) { + // Executor already gone, shut down scheduler + if (scheduler != null && !scheduler.isShutdown()) { + scheduler.shutdown(); + scheduler = null; + } + idleCheckScheduled = false; + return; + } + + final long idleNanos = System.nanoTime() - lastActivityTime; + final long idleSeconds = TimeUnit.NANOSECONDS.toSeconds(idleNanos); + + if (idleSeconds >= IDLE_TIMEOUT_SECONDS && inFlight.get() == 0) { + logger.debug("Shutting down idle shader transform executor after " + idleSeconds + " seconds"); + current.shutdown(); + executor = null; + scheduler.shutdown(); + scheduler = null; + idleCheckScheduled = false; + + // Clear transformation caches - no longer needed after loading + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + } else { + // Still active (or in-flight), schedule another check. + final long remainingSeconds = Math.max(1, IDLE_TIMEOUT_SECONDS - idleSeconds + 1); + scheduleIdleCheck(remainingSeconds); + } + } + } + } + private static KeyBinding reloadKeybind; private static KeyBinding toggleShadersKeybind; private static KeyBinding shaderpackScreenKeybind; @@ -194,6 +378,9 @@ public class Iris { return; } + // Warm up the threadpool so shader transformations are faster when we need them + ShaderTransformExecutor.warmup(); + PBRTextureManager.INSTANCE.init(); // Only load the shader pack when we can access OpenGL @@ -575,7 +762,12 @@ public class Iris { try { - return new DeferredWorldRenderingPipeline(programs); + shaderPackLoadId++; + long startTime = System.nanoTime(); + WorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs); + long endTime = System.nanoTime(); + logger.info("[Load #{}] Total shaderpack load time for '{}': {} ms", shaderPackLoadId, currentPackName, String.format("%.1f", (endTime - startTime) / 1_000_000.0)); + return pipeline; } catch (Exception e) { logger.error("Failed to create shader rendering pipeline, disabling shaders!", e); // TODO: This should be reverted if a dimension change causes shaders to compile again diff --git a/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java b/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java index 0b03294e5..92f6e848c 100644 --- a/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java +++ b/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java @@ -79,6 +79,9 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable { this.parent = parent; + // Prime the shader transform executor so reloads from this screen don't pay thread spin-up costs. + Iris.ShaderTransformExecutor.prepare(); + String irisName = Iris.MODNAME; // + " " + Iris.getVersion(); // TEMP if (Iris.INSTANCE.isDevelopmentEnvironment) { diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index b4fe507c6..973dcae32 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -32,6 +32,7 @@ import net.coderbot.iris.postprocess.BufferFlipper; import net.coderbot.iris.postprocess.CenterDepthSampler; import net.coderbot.iris.postprocess.CompositeRenderer; import net.coderbot.iris.postprocess.FinalPassRenderer; +import net.coderbot.iris.postprocess.ProgramBuildContext; import net.coderbot.iris.rendertarget.IRenderTargetExt; import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture; import net.coderbot.iris.rendertarget.RenderTargets; @@ -78,8 +79,10 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.OptionalInt; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import java.util.function.Supplier; @@ -127,6 +130,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final SodiumTerrainPipeline sodiumTerrainPipeline; + private final Map, Map> attributeTransforms; + private final HorizonRenderer horizonRenderer = new HorizonRenderer(); private final float sunPathRotation; @@ -159,6 +164,27 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R public DeferredWorldRenderingPipeline(ProgramSet programs) { Objects.requireNonNull(programs); + final Map>> prepareTransformFutures = submitCompositeTransforms(programs.getPrepare()); + final Map>> deferredTransformFutures = submitCompositeTransforms(programs.getDeferred()); + final Map>> compositeTransformFutures = submitCompositeTransforms(programs.getComposite()); + + final CompletableFuture> finalTransformFuture = + programs.getCompositeFinal() + .filter(ProgramSource::isValid) + .map(DeferredWorldRenderingPipeline::submitCompositeTransform) + .orElse(null); + + final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs); + final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver); + + final Optional terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic()); + final Optional translucentSource = first(programs.getGbuffersWater(), terrainSource); + final Optional shadowSource = programs.getShadow(); + + final CompletableFuture> sodiumTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); + final CompletableFuture> sodiumTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); + final CompletableFuture> sodiumShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); + this.cloudSetting = programs.getPackDirectives().getCloudSetting(); this.shouldRenderUnderwaterOverlay = programs.getPackDirectives().underwaterOverlay(); this.shouldRenderVignette = programs.getPackDirectives().vignette(); @@ -239,31 +265,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R PatchedShaderPrinter.resetPrintState(); - this.prepareRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getPrepare(), programs.getPrepareCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), - programs.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms); + final ProgramBuildContext prepareBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), customUniforms); + final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms); + final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms); + this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare"); flippedAfterPrepare = flipper.snapshot(); - this.deferredRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getDeferred(), programs.getDeferredCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), - programs.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms); + this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred"); flippedAfterTranslucent = flipper.snapshot(); - this.compositeRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getComposite(), programs.getCompositeCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), - programs.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms); - this.finalPassRenderer = new FinalPassRenderer(programs, renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, flipper.snapshot(), - centerDepthSampler, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), - this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms); + this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite"); + this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final"); // [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)] - ProgramId[] ids = new ProgramId[] { + final ProgramId[] ids = new ProgramId[] { ProgramId.Basic, ProgramId.Textured, ProgramId.TexturedLit, ProgramId.SkyBasic, ProgramId.SkyTextured, ProgramId.SkyTextured, null, null, ProgramId.Terrain, @@ -288,14 +305,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R throw new IllegalStateException("Program ID table length mismatch"); } - ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs); + this.attributeTransforms = new HashMap<>(); + for (Map.Entry, CompletableFuture>> entry : attributeTransformFutures.entrySet()) { + try { + this.attributeTransforms.put(entry.getKey(), entry.getValue().join()); + } catch (Exception e) { + Iris.logger.error("Failed to transform shader: {}", entry.getKey().getLeft(), e); + throw new RuntimeException("Shader transformation failed for " + entry.getKey().getLeft(), e); + } + } - Map, Pass> cachedPasses = new HashMap<>(); + final Map, Pass> cachedPasses = new HashMap<>(); this.shadowComputes = createShadowComputes(programs.getShadowCompute()); this.table = new ProgramTable<>((condition, availability) -> { - int idx; + final int idx; if (availability.texture && availability.lightmap) { idx = 2; @@ -311,10 +336,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R id = ids[idx]; } - ProgramId finalId = id; + final ProgramId finalId = id; return cachedPasses.computeIfAbsent(Pair.of(id, availability), p -> { - ProgramSource source = resolver.resolveNullable(p.getLeft()); + final ProgramSource source = resolver.resolveNullable(p.getLeft()); if (condition == RenderCondition.SHADOW) { if (!shadowDirectives.isShadowEnabled().orElse(shadowRenderTargets != null)) { @@ -427,7 +452,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R }; this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers, shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages, - shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms); + shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms, + terrainSource.map(ProgramSource::getName).orElse(null), + translucentSource.map(ProgramSource::getName).orElse(null), + shadowSource.map(ProgramSource::getName).orElse(null), + sodiumTerrainFuture, sodiumTranslucentFuture, sodiumShadowFuture); } private RenderTargets getRenderTargets() { @@ -592,12 +621,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } private Pass createPass(ProgramSource source, InputAvailability availability, boolean shadow, ProgramId id) { - // TODO: Properly handle empty shaders? - Map transformed = TransformPatcher.patchAttributes( - source.getVertexSource().orElseThrow(NullPointerException::new), - source.getGeometrySource().orElse(null), - source.getFragmentSource().orElseThrow(NullPointerException::new), - availability); + // Use pre-computed transform if available, otherwise transform synchronously + Pair key = Pair.of(source.getName(), availability); + Map transformed = attributeTransforms.get(key); + + if (transformed == null) { + // Fallback to synchronous transform if not pre-computed + transformed = TransformPatcher.patchAttributes( + source.getVertexSource().orElseThrow(NullPointerException::new), + source.getGeometrySource().orElse(null), + source.getFragmentSource().orElseThrow(NullPointerException::new), + availability); + } + String vertex = transformed.get(PatchShaderType.VERTEX); String geometry = transformed.get(PatchShaderType.GEOMETRY); String fragment = transformed.get(PatchShaderType.FRAGMENT); @@ -1266,4 +1302,59 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R PBRTextureManager.notifyPBRTexturesChanged(); } } + + private static final InputAvailability INPUT_NONE = new InputAvailability(false, false); + private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false); + private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true); + private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP }; + + private static CompletableFuture> submitCompositeTransform(ProgramSource source) { + return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null))); + } + + private static Map>> submitCompositeTransforms(ProgramSource[] sources) { + // Count valid sources for initial capacity + int count = 0; + for (ProgramSource source : sources) { + if (source != null && source.isValid()) count++; + } + final Map>> futures = new HashMap<>(count); + for (int i = 0; i < sources.length; i++) { + if (sources[i] != null && sources[i].isValid()) { + futures.put(i, submitCompositeTransform(sources[i])); + } + } + return futures; + } + + private static Map, CompletableFuture>> + submitAttributeTransforms(ProgramFallbackResolver resolver) { + final Map, CompletableFuture>> futures = new HashMap<>(); + final Set processedSourceNames = new HashSet<>(); + for (ProgramId id : ProgramId.values()) { + ProgramSource source = resolver.resolveNullable(id); + if (source != null && !processedSourceNames.contains(source.getName())) { + processedSourceNames.add(source.getName()); + for (InputAvailability avail : INPUT_AVAILABILITIES) { + Pair key = Pair.of(source.getName(), avail); + futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null), avail))); + } + } + } + return futures; + } + + private static CompletableFuture> submitSodiumTerrainTransform(ProgramSource source) { + return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchSodiumTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null))); + } + + @SafeVarargs + private static Optional first(Optional... candidates) { + for (Optional candidate : candidates) { + if (candidate.isPresent()) { + return candidate; + } + } + return Optional.empty(); + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java b/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java index 721daa7b6..4b05ed43d 100644 --- a/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java @@ -5,9 +5,7 @@ import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; import net.coderbot.iris.shaderpack.ProgramSet; -import net.coderbot.iris.shaderpack.ProgramSource; import net.coderbot.iris.uniforms.CommonUniforms; import net.coderbot.iris.uniforms.ExternallyManagedUniforms; import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; @@ -16,8 +14,11 @@ import net.coderbot.iris.uniforms.custom.CustomUniforms; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; +import net.coderbot.iris.Iris; + public class SodiumTerrainPipeline { Optional terrainVertex = Optional.empty(); Optional terrainGeometry = Optional.empty(); @@ -46,55 +47,63 @@ public class SodiumTerrainPipeline { ProgramSet programSet, IntFunction createTerrainSamplers, IntFunction createShadowSamplers, IntFunction createTerrainImages, - IntFunction createShadowImages, CustomUniforms customUniforms) { + IntFunction createShadowImages, CustomUniforms customUniforms, + String terrainSourceName, + String translucentSourceName, + String shadowSourceName, + CompletableFuture> terrainFuture, + CompletableFuture> translucentFuture, + CompletableFuture> shadowFuture) { this.parent = Objects.requireNonNull(parent); - Optional terrainSource = first(programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()); - Optional translucentSource = first(programSet.getGbuffersWater(), terrainSource); - Optional shadowSource = programSet.getShadow(); - this.programSet = programSet; this.customUniforms = customUniforms; - terrainSource.ifPresent(sources -> { - Map result = TransformPatcher.patchSodiumTerrain( - sources.getVertexSource().orElse(null), - sources.getGeometrySource().orElse(null), - sources.getFragmentSource().orElse(null)); - terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); - terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); - terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); + if (terrainFuture != null) { + try { + Map result = terrainFuture.join(); + terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); + terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); + terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); - PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium", - terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null)); - }); + PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_sodium", + terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null)); + } catch (Exception e) { + Iris.logger.error("Failed to transform terrain shader: {}", terrainSourceName, e); + throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e); + } + } - translucentSource.ifPresent(sources -> { - Map result = TransformPatcher.patchSodiumTerrain( - sources.getVertexSource().orElse(null), - sources.getGeometrySource().orElse(null), - sources.getFragmentSource().orElse(null)); - translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); - translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); - translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); + if (translucentFuture != null) { + try { + Map result = translucentFuture.join(); + translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); + translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); + translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); - PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium", - translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null)); - }); + PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_sodium", + translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null)); + } catch (Exception e) { + Iris.logger.error("Failed to transform translucent shader: {}", translucentSourceName, e); + throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e); + } + } - shadowSource.ifPresent(sources -> { - Map result = TransformPatcher.patchSodiumTerrain( - sources.getVertexSource().orElse(null), - sources.getGeometrySource().orElse(null), - sources.getFragmentSource().orElse(null)); - shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); - shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); - shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); + if (shadowFuture != null) { + try { + Map result = shadowFuture.join(); + shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); + shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); + shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); - PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium", - shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null)); - }); + PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_sodium", + shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null)); + } catch (Exception e) { + Iris.logger.error("Failed to transform shadow shader: {}", shadowSourceName, e); + throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e); + } + } this.createTerrainSamplers = createTerrainSamplers; this.createShadowSamplers = createShadowSamplers; @@ -177,15 +186,4 @@ public class SodiumTerrainPipeline { public void unbindFramebuffer() { GlStateManager.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); }*/ - - @SafeVarargs - private static Optional first(Optional... candidates) { - for (Optional candidate : candidates) { - if (candidate.isPresent()) { - return candidate; - } - } - - return Optional.empty(); - } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java index b84697bf7..c93d2482b 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -2,15 +2,17 @@ package net.coderbot.iris.pipeline.transform; import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; -import org.taumc.glsl.grammar.GLSLParser; -import org.taumc.glsl.Util; +import org.taumc.glsl.Transformer; + +import java.util.HashMap; +import java.util.Map; /** * Implements AttributeShaderTransformer using glsl-transformer AST * transformation methods. */ class AttributeTransformer { - public static void transform(GLSLParser.Translation_unitContext translationUnit, AttributeParameters parameters, String profile, int version) { + public static void transform(Transformer transformer, AttributeParameters parameters, String profile, int version) { boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility")); if (isCore) { if (parameters.type == PatchShaderType.VERTEX) { @@ -23,22 +25,24 @@ class AttributeTransformer { // lightmap texture coordinate. // See https://github.com/IrisShaders/Iris/issues/1149 if (parameters.inputs.lightmap) { - Util.rename(translationUnit, "gl_MultiTexCoord2", "gl_MultiTexCoord1"); + transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); } + Map texCoordReplacements = new HashMap<>(); if (!parameters.inputs.lightmap) { - Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)"); - Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)"); + texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)"); + texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)"); } if (!parameters.inputs.texture) { - Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)"); + texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)"); } + texCoordReplacements.forEach(transformer::replaceExpression); - patchTextureMatrices(translationUnit, parameters.inputs.lightmap); + patchTextureMatrices(transformer, parameters.inputs.lightmap); if (parameters.type.glShaderType == ShaderType.VERTEX - && Util.hasVariable(translationUnit, "gl_MultiTexCoord3") - && !Util.hasVariable(translationUnit, "mc_midTexCoord")) { + && transformer.hasVariable("gl_MultiTexCoord3") + && !transformer.hasVariable("mc_midTexCoord")) { // TODO: proper type conversion // gl_MultiTexCoord3 is a super legacy alias of mc_midTexCoord. We don't do this // replacement if we think mc_midTexCoord could be defined just we can't handle @@ -46,13 +50,13 @@ class AttributeTransformer { // to define mc_midTexCoord only if it's not defined, and if it is defined, // figure out its type, then replace all occurrences of gl_MultiTexCoord3 with // the correct conversion from mc_midTexCoord's declared type to vec4. - Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord"); - Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;"); + transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord"); + transformer.injectVariable("attribute vec4 mc_midTexCoord;"); } } - private static void patchTextureMatrices(GLSLParser.Translation_unitContext translationUnit, boolean hasLightmap) { - Util.rename(translationUnit, "gl_TextureMatrix", "iris_TextureMatrix"); + private static void patchTextureMatrices(Transformer transformer, boolean hasLightmap) { + transformer.rename("gl_TextureMatrix", "iris_TextureMatrix"); // TODO: These were originally marked const, but that breaks things // If these are marked const, then using them below in the iris_LightmapTextureMatrix creation @@ -61,13 +65,13 @@ class AttributeTransformer { // Not sure if it really matters if these are marked const or not. Alternatively they can be marked const // and the values hardcoded within the places that use them here, that seems to work fine, but this probably // stayed closer to the original way it worked. - Util.injectVariable(translationUnit, "float iris_ONE_OVER_256 = 0.00390625;"); - Util.injectVariable(translationUnit, "float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;"); + transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;"); + transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;"); if (hasLightmap) { - Util.injectVariable(translationUnit, "mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];"); + transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];"); } else { - Util.injectVariable(translationUnit, "mat4 iris_LightmapTextureMatrix =" + + transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" + "mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," + " 0.0, iris_ONE_OVER_256, 0.0, 0.0," + " 0.0, 0.0, iris_ONE_OVER_256, 0.0," + @@ -75,7 +79,7 @@ class AttributeTransformer { } // column major - Util.injectVariable(translationUnit, "mat4 iris_TextureMatrix[8] = mat4[8](" + + transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" + "gl_TextureMatrix[0]," + "iris_LightmapTextureMatrix," + "mat4(1.0)," + diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java index 0a431b536..facd34bbc 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java @@ -3,7 +3,7 @@ package net.coderbot.iris.pipeline.transform; import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.antlr.v4.runtime.tree.ParseTree; -import org.taumc.glsl.Util; +import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLParser; @@ -14,7 +14,7 @@ public class CompatibilityTransformer { private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.GEOMETRY, ShaderType.FRAGMENT}; - public static void transformEach(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + public static void transformEach(Transformer transformer, Parameters parameters) { if (parameters.type == PatchShaderType.VERTEX) { ; // TODO: sildur's jankness @@ -22,7 +22,7 @@ public class CompatibilityTransformer { // Why is this the GLSL transformation code in Iris, tell sildur to fix it and remove this? // it's still there in current, modern Iris // See https://github.com/IrisShaders/Iris/issues/509 - Util.replaceExpression(translationUnit, "fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)"); + transformer.replaceExpression("fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)"); } /** @@ -34,8 +34,8 @@ public class CompatibilityTransformer { * identifiers from which the declaration was removed previously. * See https://wiki.shaderlabs.org/wiki/Compiler_Behavior_Notes */ - Util.removeUnusedFunctions(translationUnit); - Util.removeConstAssignment(translationUnit); + transformer.removeUnusedFunctions(); + transformer.removeConstAssignment(); // TODO: glsl-transformation-lib doesn't have a way to identify empty declarations // this transformation is not done in current versions of Iris, so not sure it's necessary @@ -49,7 +49,7 @@ public class CompatibilityTransformer { } // does transformations that require cross-shader type data - public static void transformGrouped(Map trees, Parameters parameters) { + public static void transformGrouped(Map trees, Parameters parameters) { /** * find attributes that are declared as "in" in geometry or fragment but not * declared as "out" in the previous stage. The missing "out" declarations for @@ -88,32 +88,32 @@ public class CompatibilityTransformer { } PatchShaderType prevPatchTypes = PatchShaderType.fromGlShaderType(prevType)[0]; - GLSLParser.Translation_unitContext prevTree = trees.get(prevPatchTypes); + Transformer prevTransformer = trees.get(prevPatchTypes); // find out declarations - Map outDec = Util.findQualifiers(prevTree, GLSLLexer.OUT); + Map outDec = prevTransformer.findQualifiers(GLSLLexer.OUT); for (PatchShaderType currentType : patchTypes) { - GLSLParser.Translation_unitContext currentTree = trees.get(currentType); + Transformer currentTransformer = trees.get(currentType); - if (currentTree == null) { + if (currentTransformer == null) { continue; } - Map inDec = Util.findQualifiers(currentTree, GLSLLexer.IN); + Map inDec = currentTransformer.findQualifiers(GLSLLexer.IN); for (String in : inDec.keySet()) { if (in.startsWith("gl_")) { continue; } if (!outDec.containsKey(in)) { - if (!Util.containsCall(currentTree, in)) { + if (!currentTransformer.containsCall(in)) { continue; } - Util.makeOutDeclaration(prevTree, inDec.get(in), in); + prevTransformer.makeOutDeclaration(inDec.get(in), in); - if (!Util.hasAssigment(prevTree, in)) { - Util.initialize(prevTree, inDec.get(in), in); + if (!prevTransformer.hasAssigment(in)) { + prevTransformer.initialize(inDec.get(in), in); } } else { ParseTree outType = outDec.get(in).fully_specified_type().type_specifier().type_specifier_nonarray().children.get(0); @@ -124,8 +124,8 @@ public class CompatibilityTransformer { } if (inType.getText().equals(outType.getText())) { - if (!Util.hasAssigment(prevTree, in)) { - Util.initialize(prevTree, inDec.get(in), in); + if (!prevTransformer.hasAssigment(in)) { + prevTransformer.initialize(inDec.get(in), in); } } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java index e524bff0c..1fb6aa685 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java @@ -1,16 +1,15 @@ package net.coderbot.iris.pipeline.transform; -import org.taumc.glsl.Util; -import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.Transformer; class CompositeDepthTransformer { - public static void transform(GLSLParser.Translation_unitContext translationUnit) { + public static void transform(Transformer transformer) { // replace original declaration - int type = Util.findType(translationUnit, "centerDepthSmooth"); + int type = transformer.findType("centerDepthSmooth"); if (type != 0) { - Util.injectVariable(translationUnit, "uniform sampler2D iris_centerDepthSmooth;"); - Util.replaceExpression(translationUnit, "centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r"); + transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;"); + transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r"); } } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java index 14c79e42e..7ca9699b9 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java @@ -6,18 +6,11 @@ import net.coderbot.iris.Iris; import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; -import org.antlr.v4.runtime.BailErrorStrategy; -import org.antlr.v4.runtime.CharStreams; -import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.ConsoleErrorListener; -import org.antlr.v4.runtime.DefaultErrorStrategy; -import org.antlr.v4.runtime.Parser; -import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import org.taumc.glsl.Util; +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLLexer; -import org.taumc.glsl.grammar.GLSLParser; import java.util.ArrayList; import java.util.Arrays; @@ -30,8 +23,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class ShaderTransformer { - static String tab = ""; - private static final Pattern versionPattern = Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?"); private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^\\s*(in|out)(\\s+)"); @@ -39,6 +30,12 @@ public class ShaderTransformer { private static final Object2ObjectLinkedOpenHashMap, Map> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>(); private static final boolean useCache = true; + public static void clearCache() { + synchronized (shaderTransformationCache) { + shaderTransformationCache.clear(); + } + } + /** * These are words which need to be renamed by iris if a shader uses them, regardless o the GLSL version. * The words will get caught and renamed to iris_renamed_$WORD @@ -109,39 +106,36 @@ public class ShaderTransformer { var key = new TransformKey<>(patchType, inputs, parameters); - result = shaderTransformationCache.getAndMoveToFirst(key); + synchronized (shaderTransformationCache) { + result = shaderTransformationCache.getAndMoveToLast(key); + } if(result == null || !useCache) { result = transformInternal(inputs, patchType, parameters); // Clear this, we don't want whatever random type was last transformed being considered for the key parameters.type = null; - if(shaderTransformationCache.size() >= CACHE_SIZE) { - shaderTransformationCache.removeLast(); + synchronized (shaderTransformationCache) { + // Double-check in case another thread added it while we were transforming + Map existing = shaderTransformationCache.getAndMoveToLast(key); + if (existing != null) { + return existing; + } + if(shaderTransformationCache.size() >= CACHE_SIZE) { + shaderTransformationCache.removeFirst(); + } + shaderTransformationCache.putAndMoveToLast(key, result); } - shaderTransformationCache.putAndMoveToLast(key, result); } return result; } } - private static void configureNoError(Parser parser) { - parser.setErrorHandler(new BailErrorStrategy()); - parser.removeErrorListeners(); - parser.getInterpreter().setPredictionMode(PredictionMode.SLL); - } - - private static void configureError(Parser parser) { - parser.setErrorHandler(new DefaultErrorStrategy()); - parser.addErrorListener(ConsoleErrorListener.INSTANCE); - parser.getInterpreter().setPredictionMode(PredictionMode.LL); - } - private static

Map transformInternal(EnumMap inputs, Patch patchType, P parameters) { EnumMap result = new EnumMap<>(PatchShaderType.class); - EnumMap types = new EnumMap<>(PatchShaderType.class); + EnumMap types = new EnumMap<>(PatchShaderType.class); EnumMap prepatched = new EnumMap<>(PatchShaderType.class); - List textureLodExtensionPatches = new ArrayList<>(); - List hacky120Patches = new ArrayList<>(); + List textureLodExtensionPatches = new ArrayList<>(); + List hacky120Patches = new ArrayList<>(); Stopwatch watch = Stopwatch.createStarted(); @@ -190,37 +184,35 @@ public class ShaderTransformer { } } - GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(input)); - GLSLParser parser = new GLSLParser(new CommonTokenStream(lexer)); - parser.setBuildParseTree(true); - configureNoError(parser); + var parsedShader = ShaderParser.parseShader(input); + var transformer = new Transformer(parsedShader.full()); - GLSLParser.Translation_unitContext translationUnit; - try { - translationUnit = doTransform(parser, patchType, parameters, profile, versionInt); - } catch (Exception e) { - lexer.reset(); - parser.reset(); - configureError(parser); - translationUnit = doTransform(parser, patchType, parameters, profile, versionInt); - } + doTransform(transformer, patchType, parameters, profile, versionInt); // Check if we need to patch in texture LOD extension enabling - if (versionInt <= 120 && (Util.containsCall(translationUnit, "texture2DLod") || Util.containsCall(translationUnit, "texture3DLod") || Util.containsCall(translationUnit, "texture2DGradARB"))) { - textureLodExtensionPatches.add(translationUnit); + if (versionInt <= 120 && (transformer.containsCall("texture2DLod") || transformer.containsCall("texture3DLod") || transformer.containsCall("texture2DGradARB"))) { + textureLodExtensionPatches.add(transformer); } // Check if we need to patch in some hacky GLSL 120 compat if (versionInt <= 120) { - hacky120Patches.add(translationUnit); + hacky120Patches.add(transformer); } - types.put(type, translationUnit); + types.put(type, transformer); prepatched.put(type, profileString); } CompatibilityTransformer.transformGrouped(types, parameters); for (var entry : types.entrySet()) { - String formattedShader = getFormattedShader(entry.getValue(), prepatched.get(entry.getKey())); + final Transformer transformer = entry.getValue(); + final String header = prepatched.get(entry.getKey()); + final StringBuilder formattedShaderBuilder = new StringBuilder(); + + transformer.mutateTree(tree -> { + formattedShaderBuilder.append(getFormattedShader(tree, header)); + }); + + String formattedShader = formattedShaderBuilder.toString(); // Restore identifiers that were temporarily renamed to dodge GLSL reserved keywords. formattedShader = formattedShader.replace("iris_renamed_texture", "texture"); @@ -229,13 +221,13 @@ public class ShaderTransformer { // Please don't mind the entire rest of this loop basically, we're doing awful fragile regex on the transformed // shader output to do things that I can't figure out with AST because I'm bad at it - if (textureLodExtensionPatches.contains(entry.getValue())) { + if (textureLodExtensionPatches.contains(transformer)) { String[] parts = formattedShader.split("\n", 2); parts[1] = "#extension GL_ARB_shader_texture_lod : require\n" + parts[1]; formattedShader = parts[0] + "\n" + parts[1]; } - if (hacky120Patches.contains(entry.getValue())) { + if (hacky120Patches.contains(transformer)) { // Forcibly enable GL_EXT_gpu_shader4, it has a lot of compatibility backports with GLSL 130+ // and seems more or less universally supported by hardware/drivers String[] parts = formattedShader.split("\n", 2); @@ -252,99 +244,98 @@ public class ShaderTransformer { result.put(entry.getKey(), formattedShader); } watch.stop(); - Iris.logger.info("Transformed shader for {} in {}", patchType.name(), watch); + Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch); return result; } - private static GLSLParser.Translation_unitContext doTransform(GLSLParser parser, Patch patchType, Parameters parameters, String profile, int versionInt) { - GLSLParser.Translation_unitContext translationUnit = parser.translation_unit(); + private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) { switch (patchType) { case SODIUM_TERRAIN: - SodiumTransformer.transform(translationUnit, parameters); + SodiumTransformer.transform(transformer, parameters); break; case COMPOSITE: - CompositeDepthTransformer.transform(translationUnit); + CompositeDepthTransformer.transform(transformer); break; case ATTRIBUTES: - AttributeTransformer.transform(translationUnit, (AttributeParameters) parameters, profile, versionInt); + AttributeTransformer.transform(transformer, (AttributeParameters) parameters, profile, versionInt); break; default: throw new IllegalStateException("Unknown patch type: " + patchType.name()); } - CompatibilityTransformer.transformEach(translationUnit, parameters); - return translationUnit; + CompatibilityTransformer.transformEach(transformer, parameters); } - public static void applyIntelHd4000Workaround(GLSLParser.Translation_unitContext translationUnit) { - Util.renameFunctionCall(translationUnit, "ftransform", "iris_ftransform"); + public static void applyIntelHd4000Workaround(Transformer transformer) { + transformer.renameFunctionCall("ftransform", "iris_ftransform"); } - public static void replaceGlMultiTexCoordBounded(GLSLParser.Translation_unitContext translationUnit, int min, int max) { + public static void replaceGlMultiTexCoordBounded(Transformer transformer, int min, int max) { for (int i = min; i <= max; i++) { - Util.replaceExpression(translationUnit, "gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)"); + transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)"); } } - public static void patchMultiTexCoord3(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { - if (parameters.type.glShaderType == ShaderType.VERTEX && Util.hasVariable(translationUnit, "gl_MultiTexCoord3") && !Util.hasVariable(translationUnit, "mc_midTexCoord")) { - Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord"); - Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;"); + public static void patchMultiTexCoord3(Transformer transformer, Parameters parameters) { + if (parameters.type.glShaderType == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) { + transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord"); + transformer.injectVariable("attribute vec4 mc_midTexCoord;"); } } - public static void replaceMidTexCoord(GLSLParser.Translation_unitContext translationUnit, float textureScale) { - int type = Util.findType(translationUnit, "mc_midTexCoord"); + public static void replaceMidTexCoord(Transformer transformer, float textureScale) { + int type = transformer.findType("mc_midTexCoord"); if (type != 0) { - Util.removeVariable(translationUnit, "mc_midTexCoord"); + transformer.removeVariable("mc_midTexCoord"); } - Util.replaceExpression(translationUnit, "mc_midTexCoord", "iris_MidTex"); + transformer.replaceExpression("mc_midTexCoord", "iris_MidTex"); switch (type) { case 0: return; case GLSLLexer.BOOL: return; case GLSLLexer.FLOAT: - Util.injectFunction(translationUnit, "float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed + transformer.injectFunction("float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed break; case GLSLLexer.VEC2: - Util.injectFunction(translationUnit, "vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;"); + transformer.injectFunction("vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;"); break; case GLSLLexer.VEC3: - Util.injectFunction(translationUnit, "vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);"); + transformer.injectFunction("vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);"); break; case GLSLLexer.VEC4: - Util.injectFunction(translationUnit, "vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);"); + transformer.injectFunction("vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);"); break; default: } - Util.injectVariable(translationUnit, "in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly? + transformer.injectVariable("in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly? } - public static void addIfNotExists(GLSLParser.Translation_unitContext translationUnit, String name, String code) { - if (!Util.hasVariable(translationUnit, name)) { - Util.injectVariable(translationUnit, code); + public static void addIfNotExists(Transformer transformer, String name, String code) { + if (!transformer.hasVariable(name)) { + transformer.injectVariable(code); } } - public static void addIfNotExistsType(GLSLParser.Translation_unitContext translationUnit, String name, String type) { - if (!Util.hasVariable(translationUnit, name)) { - Util.injectVariable(translationUnit, type + " " + name + ";"); + public static void addIfNotExistsType(Transformer transformer, String name, String type) { + if (!transformer.hasVariable(name)) { + transformer.injectVariable(type + " " + name + ";"); } } public static String getFormattedShader(ParseTree tree, String string) { StringBuilder sb = new StringBuilder(string + "\n"); - getFormattedShader(tree, sb); + String[] tabHolder = {""}; + getFormattedShader(tree, sb, tabHolder); return sb.toString(); } - private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder) { + private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder) { if (tree instanceof TerminalNode) { - String text = tree.getText(); + final String text = tree.getText(); if (text.equals("")) { return; } @@ -355,20 +346,21 @@ public class ShaderTransformer { stringBuilder.append(text); if (text.equals("{")) { stringBuilder.append(" \n\t"); - tab = "\t"; + tabHolder[0] = "\t"; } if (text.equals("}")) { - stringBuilder.deleteCharAt(stringBuilder.length() - 2); - tab = ""; + if (stringBuilder.length() >= 2) { + stringBuilder.deleteCharAt(stringBuilder.length() - 2); + } + tabHolder[0] = ""; } - stringBuilder.append(text.equals(";") ? " \n" + tab : " "); + stringBuilder.append(text.equals(";") ? " \n" + tabHolder[0] : " "); } else { - for(int i = 0; i < tree.getChildCount(); ++i) { - getFormattedShader(tree.getChild(i), stringBuilder); + for (int i = 0; i < tree.getChildCount(); ++i) { + getFormattedShader(tree.getChild(i), stringBuilder, tabHolder); } } - } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java index 2fbaa6f5d..2194565ee 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java @@ -1,19 +1,21 @@ package net.coderbot.iris.pipeline.transform; import net.coderbot.iris.pipeline.transform.parameter.Parameters; -import org.taumc.glsl.Util; -import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.Transformer; + +import java.util.HashMap; +import java.util.Map; class SodiumTransformer { - public static void transform(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + public static void transform(Transformer transformer, Parameters parameters) { switch (parameters.type) { // For Sodium patching, treat fragment and geometry the same case FRAGMENT: case GEOMETRY: - transformFragment(translationUnit, parameters); + transformFragment(transformer, parameters); break; case VERTEX: - transformVertex(translationUnit, parameters); + transformVertex(transformer, parameters); break; default: throw new IllegalStateException("Unexpected Sodium terrain patching shader type: " + parameters.type); @@ -23,53 +25,62 @@ class SodiumTransformer { /** * Transforms vertex shaders. */ - public static void transformVertex(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + public static void transformVertex(Transformer transformer, Parameters parameters) { + transformer.injectVariable("attribute vec3 iris_Pos;"); + transformer.injectVariable("attribute vec4 iris_Color;"); + transformer.injectVariable("attribute vec2 iris_TexCoord;"); + transformer.injectVariable("attribute vec2 iris_LightCoord;"); + transformer.injectVariable("attribute vec3 iris_Normal;"); + transformer.injectVariable("uniform vec3 u_ModelScale;"); + transformer.injectVariable("uniform vec2 u_TextureScale;"); + transformer.injectVariable("attribute vec4 iris_ModelOffset;"); - Util.injectVariable(translationUnit, "attribute vec3 iris_Pos;"); - Util.injectVariable(translationUnit, "attribute vec4 iris_Color;"); - Util.injectVariable(translationUnit, "attribute vec2 iris_TexCoord;"); - Util.injectVariable(translationUnit, "attribute vec2 iris_LightCoord;"); - Util.injectVariable(translationUnit, "attribute vec3 iris_Normal;"); - Util.injectVariable(translationUnit, "uniform vec3 u_ModelScale;"); - Util.injectVariable(translationUnit, "uniform vec2 u_TextureScale;"); - Util.injectVariable(translationUnit, "attribute vec4 iris_ModelOffset;"); - Util.injectFunction(translationUnit, "vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);"); - Util.injectFunction(translationUnit, "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); + transformer.injectFunction("vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);"); + transformer.injectFunction("vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); - transformShared(translationUnit, parameters); + transformShared(transformer, parameters); - Util.replaceExpression(translationUnit, "gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)"); - Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)"); - Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "iris_LightTexCoord"); - Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "iris_LightTexCoord"); - Util.rename(translationUnit, "gl_Color", "iris_Color"); - Util.rename(translationUnit, "gl_Normal", "iris_Normal"); - Util.rename(translationUnit, "ftransform", "iris_ftransform"); + Map vertexReplacements = new HashMap<>(); + vertexReplacements.put("gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)"); + vertexReplacements.put("gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)"); + vertexReplacements.put("gl_MultiTexCoord1", "iris_LightTexCoord"); + vertexReplacements.put("gl_MultiTexCoord2", "iris_LightTexCoord"); + vertexReplacements.forEach(transformer::replaceExpression); + + Map vertexRenames = new HashMap<>(); + vertexRenames.put("gl_Color", "iris_Color"); + vertexRenames.put("gl_Normal", "iris_Normal"); + vertexRenames.put("ftransform", "iris_ftransform"); + transformer.rename(vertexRenames); } /** * Transforms fragment shaders. The fragment shader does only the shared things * from the vertex shader. */ - public static void transformFragment(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + public static void transformFragment(Transformer transformer, Parameters parameters) { // interestingly there is nothing that isn't shared - transformShared(translationUnit, parameters); + transformShared(transformer, parameters); } /** * Does the things that transformVertex and transformFragment have in common. */ - private static void transformShared(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { - Util.injectVariable(translationUnit, "uniform mat4 iris_ModelViewMatrix;"); - Util.injectVariable(translationUnit, "uniform mat4 u_ModelViewProjectionMatrix;"); - Util.injectVariable(translationUnit, "uniform mat4 iris_NormalMatrix;"); - Util.injectVariable(translationUnit, "uniform mat4 iris_LightmapTextureMatrix;"); + private static void transformShared(Transformer transformer, Parameters parameters) { + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 u_ModelViewProjectionMatrix;"); + transformer.injectVariable("uniform mat4 iris_NormalMatrix;"); + transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;"); - Util.rename(translationUnit, "gl_ModelViewMatrix", "iris_ModelViewMatrix"); - Util.rename(translationUnit, "gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix"); - Util.replaceExpression(translationUnit, "gl_NormalMatrix", "mat3(iris_NormalMatrix)"); + Map renames = new HashMap<>(); + renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix"); + renames.put("gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix"); + transformer.rename(renames); - Util.replaceExpression(translationUnit, "gl_TextureMatrix[0]", "mat4(1.0)"); - Util.replaceExpression(translationUnit, "gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); + Map sharedReplacements = new HashMap<>(); + sharedReplacements.put("gl_NormalMatrix", "mat3(iris_NormalMatrix)"); + sharedReplacements.put("gl_TextureMatrix[0]", "mat4(1.0)"); + sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); + sharedReplacements.forEach(transformer::replaceExpression); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java index 65fe8f066..e2259fd25 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -10,7 +10,12 @@ import java.util.Map; public class TransformPatcher { private static final int MAX_CACHE_ENTRIES = 400; - private static final Map> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true); + private static final Map> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true) { + @Override + protected boolean removeEldestEntry(Map.Entry> eldest) { + return size() > MAX_CACHE_ENTRIES; + } + }; private static final boolean useCache = true; @@ -46,7 +51,7 @@ public class TransformPatcher { return false; if (getClass() != obj.getClass()) return false; - TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj; + final TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj; if (fragment == null) { if (other.fragment != null) return false; @@ -77,11 +82,11 @@ public class TransformPatcher { } // check if this has been cached - TransformPatcher.CacheKey key; + TransformPatcher.CacheKey key = null; Map result = null; if (useCache) { key = new TransformPatcher.CacheKey(parameters, vertex, geometry, fragment); - if (cache.containsKey(key)) { + synchronized (cache) { result = cache.get(key); } } @@ -90,7 +95,14 @@ public class TransformPatcher { if (result == null) { result = ShaderTransformer.transform(vertex, geometry, fragment, parameters); if (useCache) { - cache.put(key, result); + synchronized (cache) { + // Double-check in case another thread added it while we were transforming + final Map existing = cache.get(key); + if (existing != null) { + return existing; + } + cache.put(key, result); + } } } @@ -108,4 +120,10 @@ public class TransformPatcher { public static Map patchComposite(String vertex, String geometry, String fragment) { return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE)); } + + public static void clearCache() { + synchronized (cache) { + cache.clear(); + } + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java index cc5e2507c..b05ec8ce0 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java @@ -5,7 +5,7 @@ import net.coderbot.iris.pipeline.transform.PatchShaderType; public class Parameters implements JobParameters { public final Patch patch; - public PatchShaderType type; // may only be set by TransformPatcher + public PatchShaderType type; // WARNING: adding new fields requires updating hashCode and equals methods! // name of the shader, this should not be part of hash/equals diff --git a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java index d4cd1e241..85403e207 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java @@ -39,6 +39,8 @@ import org.lwjgl.opengl.GL30; import java.util.Map; import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.function.IntSupplier; import java.util.function.Supplier; @@ -58,17 +60,25 @@ public class CompositeRenderer { IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier, CenterDepthSampler centerDepthSampler, BufferFlipper bufferFlipper, Supplier shadowTargetsSupplier, - Object2ObjectMap customTextureIds, ImmutableMap explicitPreFlips, CustomUniforms customUniforms) { - this.noiseTexture = noiseTexture; - this.updateNotifier = updateNotifier; - this.centerDepthSampler = centerDepthSampler; - this.renderTargets = renderTargets; - this.customTextureIds = customTextureIds; - this.customUniforms = customUniforms; + Object2ObjectMap customTextureIds, ImmutableMap explicitPreFlips, + CustomUniforms customUniforms, + Map>> precomputedTransformFutures) { + this(sources, computes, bufferFlipper, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), explicitPreFlips, precomputedTransformFutures, "unknown"); + } + + public CompositeRenderer(ProgramSource[] sources, ComputeSource[][] computes, BufferFlipper bufferFlipper, ProgramBuildContext context, ImmutableMap explicitPreFlips, Map>> precomputedTransformFutures, String stageName) { + this.noiseTexture = context.noiseTexture(); + this.updateNotifier = context.updateNotifier(); + this.centerDepthSampler = context.centerDepthSampler(); + this.renderTargets = context.renderTargets(); + this.customTextureIds = context.customTextureIds(); + this.customUniforms = context.customUniforms(); final ImmutableList.Builder passes = ImmutableList.builder(); final ImmutableSet.Builder flippedAtLeastOnce = new ImmutableSet.Builder<>(); + Map>> transformFutures = precomputedTransformFutures; + explicitPreFlips.forEach((buffer, shouldFlip) -> { if (shouldFlip) { bufferFlipper.flip(buffer); @@ -84,28 +94,29 @@ public class CompositeRenderer { if (source == null || !source.isValid()) { if (computes[i] != null) { - ComputeOnlyPass pass = new ComputeOnlyPass(); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); + final ComputeOnlyPass pass = new ComputeOnlyPass(); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); passes.add(pass); } continue; } - Pass pass = new Pass(); - ProgramDirectives directives = source.getDirectives(); + final Pass pass = new Pass(); + final ProgramDirectives directives = source.getDirectives(); - pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); - int[] drawBuffers = directives.getDrawBuffers(); + Map transformed = getTransformed(source, transformFutures, i, stageName); + pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); + final int[] drawBuffers = directives.getDrawBuffers(); - GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers); + final GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers); int passWidth = 0, passHeight = 0; // Flip the buffers that this shader wrote to, and set pass width and height - ImmutableMap explicitFlips = directives.getExplicitFlips(); + final ImmutableMap explicitFlips = directives.getExplicitFlips(); for (int buffer : drawBuffers) { - RenderTarget target = renderTargets.get(buffer); + final RenderTarget target = renderTargets.get(buffer); if ((passWidth > 0 && passWidth != target.getWidth()) || (passHeight > 0 && passHeight != target.getHeight())) { throw new IllegalStateException("Pass widths must match"); } @@ -145,6 +156,25 @@ public class CompositeRenderer { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); } + private static Map getTransformed(ProgramSource source, Map>> transformFutures, int index, String stageName) { + if (transformFutures != null) { + final CompletableFuture> future = transformFutures.get(index); + if (future != null) { + try { + final Map result = future.join(); + if (result != null) { + return result; + } + } catch (CompletionException e) { + throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "' (pass " + index + ")", e.getCause() != null ? e.getCause() : e); + } + } + } + + // Fallback: transform synchronously + return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new)); + } + public void recalculateSizes() { for (Pass pass : passes) { if (pass instanceof ComputeOnlyPass) { @@ -291,13 +321,9 @@ public class CompositeRenderer { } // TODO: Don't just copy this from DeferredWorldRenderingPipeline - private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, - Supplier shadowTargetsSupplier) { - // TODO: Properly handle empty shaders - Map transformed = TransformPatcher.patchComposite( - source.getVertexSource().orElseThrow(NullPointerException::new), - source.getGeometrySource().orElse(null), - source.getFragmentSource().orElseThrow(NullPointerException::new)); + private Program createProgramFromTransformed(ProgramSource source, Map transformed, + ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, + Supplier shadowTargetsSupplier) { String vertex = transformed.get(PatchShaderType.VERTEX); String geometry = transformed.get(PatchShaderType.GEOMETRY); String fragment = transformed.get(PatchShaderType.FRAGMENT); diff --git a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java index a2d84d12c..d1c351349 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java @@ -40,6 +40,8 @@ import org.lwjgl.opengl.GL30; import java.util.Map; import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.function.IntSupplier; import java.util.function.Supplier; @@ -59,33 +61,38 @@ public class FinalPassRenderer { private final Object2ObjectMap customTextureIds; private final CustomUniforms customUniforms; - // TODO: The length of this argument list is getting a bit ridiculous public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier, ImmutableSet flippedBuffers, CenterDepthSampler centerDepthSampler, Supplier shadowTargetsSupplier, Object2ObjectMap customTextureIds, - ImmutableSet flippedAtLeastOnce, CustomUniforms customUniforms) { - this.updateNotifier = updateNotifier; - this.centerDepthSampler = centerDepthSampler; - this.customTextureIds = customTextureIds; + ImmutableSet flippedAtLeastOnce, CustomUniforms customUniforms, + CompletableFuture> precomputedTransformFuture) { + this(pack, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), flippedBuffers, flippedAtLeastOnce, precomputedTransformFuture, "final"); + } - this.noiseTexture = noiseTexture; - this.renderTargets = renderTargets; - this.customUniforms = customUniforms; - this.finalPass = pack.getCompositeFinal().map(source -> { - Pass pass = new Pass(); - ProgramDirectives directives = source.getDirectives(); + public FinalPassRenderer(ProgramSet pack, ProgramBuildContext context, ImmutableSet flippedBuffers, ImmutableSet flippedAtLeastOnce, CompletableFuture> precomputedTransformFuture, String stageName) { + this.updateNotifier = context.updateNotifier(); + this.centerDepthSampler = context.centerDepthSampler(); + this.customTextureIds = context.customTextureIds(); - pass.program = createProgram(source, flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier); - pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier); + this.noiseTexture = context.noiseTexture(); + this.renderTargets = context.renderTargets(); + this.customUniforms = context.customUniforms(); + this.finalPass = pack.getCompositeFinal().filter(ProgramSource::isValid).map(source -> { + final Pass pass = new Pass(); + final ProgramDirectives directives = source.getDirectives(); + + final Map transformed = getTransformed(source, precomputedTransformFuture, stageName); + pass.program = createProgramFromTransformed(source, transformed, flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier()); + pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier()); pass.stageReadsFromAlt = flippedBuffers; pass.mipmappedBuffers = directives.getMipmappedBuffers(); return pass; }).orElse(null); - IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared(); + final IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared(); // The name of this method might seem a bit odd here, but we want a framebuffer with color attachments that line // up with whatever was written last (since we're reading from these framebuffers) instead of trying to create @@ -128,6 +135,20 @@ public class FinalPassRenderer { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); } + private static Map getTransformed(ProgramSource source, CompletableFuture> precomputedTransformFuture, String stageName) { + if (precomputedTransformFuture != null) { + try { + final Map result = precomputedTransformFuture.join(); + if (result != null) { + return result; + } + } catch (CompletionException e) { + throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "'", e.getCause() != null ? e.getCause() : e); + } + } + return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new)); + } + private static final class Pass { Program program; ComputeProgram[] computes; @@ -314,13 +335,9 @@ public class FinalPassRenderer { } // TODO: Don't just copy this from DeferredWorldRenderingPipeline - private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, - Supplier shadowTargetsSupplier) { - // TODO: Properly handle empty shaders - Map transformed = TransformPatcher.patchComposite( - source.getVertexSource().orElseThrow(NullPointerException::new), - source.getGeometrySource().orElse(null), - source.getFragmentSource().orElseThrow(NullPointerException::new)); + private Program createProgramFromTransformed(ProgramSource source, Map transformed, + ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, + Supplier shadowTargetsSupplier) { final String vertex = transformed.get(PatchShaderType.VERTEX); final String geometry = transformed.get(PatchShaderType.GEOMETRY); final String fragment = transformed.get(PatchShaderType.FRAGMENT); diff --git a/src/main/java/net/coderbot/iris/postprocess/ProgramBuildContext.java b/src/main/java/net/coderbot/iris/postprocess/ProgramBuildContext.java new file mode 100644 index 000000000..2d1db5bc7 --- /dev/null +++ b/src/main/java/net/coderbot/iris/postprocess/ProgramBuildContext.java @@ -0,0 +1,23 @@ +package net.coderbot.iris.postprocess; + +import com.github.bsideup.jabel.Desugar; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.coderbot.iris.rendertarget.RenderTargets; +import net.coderbot.iris.shadows.ShadowRenderTargets; +import net.coderbot.iris.uniforms.FrameUpdateNotifier; +import net.coderbot.iris.uniforms.custom.CustomUniforms; +import org.jetbrains.annotations.NotNull; + +import java.util.function.IntSupplier; +import java.util.function.Supplier; + +@Desugar +public record ProgramBuildContext( + @NotNull RenderTargets renderTargets, + @NotNull IntSupplier noiseTexture, + @NotNull FrameUpdateNotifier updateNotifier, + @NotNull CenterDepthSampler centerDepthSampler, + @NotNull Supplier shadowTargetsSupplier, + @NotNull Object2ObjectMap customTextureIds, + @NotNull CustomUniforms customUniforms +) {} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java new file mode 100644 index 000000000..1f9ac4276 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/transform/ShaderTransformerTest.java @@ -0,0 +1,67 @@ +package net.coderbot.iris.pipeline.transform; + +import org.junit.jupiter.api.Test; +import org.taumc.glsl.ShaderParser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ShaderTransformerTest { + + @Test + void transformIsDeterministicUnderConcurrency() throws ExecutionException, InterruptedException { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + + final String vertex = "#version 120\nvoid main(){gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;}"; + final String fragment = "#version 120\nvoid main(){gl_FragColor = vec4(1.0);}"; + + ExecutorService exec = Executors.newFixedThreadPool(8); + try { + List>> tasks = new ArrayList<>(); + for (int i = 0; i < 64; i++) { + tasks.add(() -> TransformPatcher.patchComposite(vertex, null, fragment)); + } + + List>> futures = exec.invokeAll(tasks); + Map first = futures.get(0).get(); + assertNotNull(first); + + for (Future> f : futures) { + Map r = f.get(); + assertEquals(first, r); + } + } finally { + exec.shutdownNow(); + } + } + + @Test + void formattedShaderIsParseable() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + + final String vertex = "#version 120\nvoid main(){gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;}"; + final String fragment = "#version 120\nvoid main(){gl_FragColor = vec4(1.0);}"; + + Map transformed = TransformPatcher.patchComposite(vertex, null, fragment); + assertNotNull(transformed); + + String v = transformed.get(PatchShaderType.VERTEX); + String f = transformed.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + + ShaderParser.parseShader(v); + ShaderParser.parseShader(f); + } +}