Parallel shader transformation and use Transformer instead of Utils (#1191)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2025-12-23 09:11:32 -08:00
1 parent f0d45b0d62
commit 89132f3ef9
16 files changed
+743 -302

No files matched your search

+193 -1
View File
@@ -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 <T> CompletableFuture<T> submitTracked(Supplier<T> 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<Void> 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
@@ -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) {
@@ -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<Pair<String, InputAvailability>, Map<PatchShaderType, String>> 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<Integer, CompletableFuture<Map<PatchShaderType, String>>> prepareTransformFutures = submitCompositeTransforms(programs.getPrepare());
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> deferredTransformFutures = submitCompositeTransforms(programs.getDeferred());
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> compositeTransformFutures = submitCompositeTransforms(programs.getComposite());
final CompletableFuture<Map<PatchShaderType, String>> finalTransformFuture =
programs.getCompositeFinal()
.filter(ProgramSource::isValid)
.map(DeferredWorldRenderingPipeline::submitCompositeTransform)
.orElse(null);
final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver);
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
final Optional<ProgramSource> shadowSource = programs.getShadow();
final CompletableFuture<Map<PatchShaderType, String>> sodiumTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> sodiumTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> 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<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> 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<Pair<ProgramId, InputAvailability>, Pass> cachedPasses = new HashMap<>();
final Map<Pair<ProgramId, InputAvailability>, 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<PatchShaderType, String> 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<String, InputAvailability> key = Pair.of(source.getName(), availability);
Map<PatchShaderType, String> 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<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
}
private static Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> submitCompositeTransforms(ProgramSource[] sources) {
// Count valid sources for initial capacity
int count = 0;
for (ProgramSource source : sources) {
if (source != null && source.isValid()) count++;
}
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> 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<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>
submitAttributeTransforms(ProgramFallbackResolver resolver) {
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>();
final Set<String> 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<String, InputAvailability> 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<Map<PatchShaderType, String>> submitSodiumTerrainTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchSodiumTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
}
@SafeVarargs
private static <T> Optional<T> first(Optional<T>... candidates) {
for (Optional<T> candidate : candidates) {
if (candidate.isPresent()) {
return candidate;
}
}
return Optional.empty();
}
}
@@ -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<String> terrainVertex = Optional.empty();
Optional<String> terrainGeometry = Optional.empty();
@@ -46,55 +47,63 @@ public class SodiumTerrainPipeline {
ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers,
IntFunction<ProgramSamplers> createShadowSamplers,
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms) {
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms,
String terrainSourceName,
String translucentSourceName,
String shadowSourceName,
CompletableFuture<Map<PatchShaderType, String>> terrainFuture,
CompletableFuture<Map<PatchShaderType, String>> translucentFuture,
CompletableFuture<Map<PatchShaderType, String>> shadowFuture) {
this.parent = Objects.requireNonNull(parent);
Optional<ProgramSource> terrainSource = first(programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic());
Optional<ProgramSource> translucentSource = first(programSet.getGbuffersWater(), terrainSource);
Optional<ProgramSource> shadowSource = programSet.getShadow();
this.programSet = programSet;
this.customUniforms = customUniforms;
terrainSource.ifPresent(sources -> {
Map<PatchShaderType, String> 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<PatchShaderType, String> 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<PatchShaderType, String> 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<PatchShaderType, String> 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<PatchShaderType, String> 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<PatchShaderType, String> 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 <T> Optional<T> first(Optional<T>... candidates) {
for (Optional<T> candidate : candidates) {
if (candidate.isPresent()) {
return candidate;
}
}
return Optional.empty();
}
}
@@ -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<String, String> 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)," +
@@ -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<PatchShaderType, GLSLParser.Translation_unitContext> trees, Parameters parameters) {
public static void transformGrouped(Map<PatchShaderType, Transformer> 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<String, GLSLParser.Single_declarationContext> outDec = Util.findQualifiers(prevTree, GLSLLexer.OUT);
Map<String, GLSLParser.Single_declarationContext> 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<String, GLSLParser.Single_declarationContext> inDec = Util.findQualifiers(currentTree, GLSLLexer.IN);
Map<String, GLSLParser.Single_declarationContext> 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);
}
}
}
@@ -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");
}
}
}
@@ -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<TransformKey<?>, Map<PatchShaderType, String>> 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<PatchShaderType, String> 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 <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, GLSLParser.Translation_unitContext> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
List<GLSLParser.Translation_unitContext> textureLodExtensionPatches = new ArrayList<>();
List<GLSLParser.Translation_unitContext> hacky120Patches = new ArrayList<>();
List<Transformer> textureLodExtensionPatches = new ArrayList<>();
List<Transformer> 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("<EOF>")) {
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);
}
}
}
}
@@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> 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);
}
}
@@ -10,7 +10,12 @@ import java.util.Map;
public class TransformPatcher {
private static final int MAX_CACHE_ENTRIES = 400;
private static final Map<TransformPatcher.CacheKey, Map<PatchShaderType, String>> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true);
private static final Map<TransformPatcher.CacheKey, Map<PatchShaderType, String>> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<CacheKey, Map<PatchShaderType, String>> 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<PatchShaderType, String> 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<PatchShaderType, String> existing = cache.get(key);
if (existing != null) {
return existing;
}
cache.put(key, result);
}
}
}
@@ -108,4 +120,10 @@ public class TransformPatcher {
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE));
}
public static void clearCache() {
synchronized (cache) {
cache.clear();
}
}
}
@@ -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
@@ -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<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips, CustomUniforms customUniforms) {
this.noiseTexture = noiseTexture;
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.renderTargets = renderTargets;
this.customTextureIds = customTextureIds;
this.customUniforms = customUniforms;
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips,
CustomUniforms customUniforms,
Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> 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<Integer, Boolean> explicitPreFlips, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> 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<Pass> passes = ImmutableList.builder();
final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>();
Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> 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<PatchShaderType, String> 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<Integer, Boolean> explicitFlips = directives.getExplicitFlips();
final ImmutableMap<Integer, Boolean> 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<PatchShaderType, String> getTransformed(ProgramSource source, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures, int index, String stageName) {
if (transformFutures != null) {
final CompletableFuture<Map<PatchShaderType, String>> future = transformFutures.get(index);
if (future != null) {
try {
final Map<PatchShaderType, String> 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<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed,
ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
@@ -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<String, IntSupplier> 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<Integer> flippedBuffers,
CenterDepthSampler centerDepthSampler,
Supplier<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds,
ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms) {
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.customTextureIds = customTextureIds;
ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms,
CompletableFuture<Map<PatchShaderType, String>> 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<Integer> flippedBuffers, ImmutableSet<Integer> flippedAtLeastOnce, CompletableFuture<Map<PatchShaderType, String>> 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<PatchShaderType, String> 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<PatchShaderType, String> getTransformed(ProgramSource source, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture, String stageName) {
if (precomputedTransformFuture != null) {
try {
final Map<PatchShaderType, String> 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<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed,
ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
final String vertex = transformed.get(PatchShaderType.VERTEX);
final String geometry = transformed.get(PatchShaderType.GEOMETRY);
final String fragment = transformed.get(PatchShaderType.FRAGMENT);
@@ -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<ShadowRenderTargets> shadowTargetsSupplier,
@NotNull Object2ObjectMap<String, IntSupplier> customTextureIds,
@NotNull CustomUniforms customUniforms
) {}