mirror of
https://github.com/GTNewHorizons/Angelica.git
synced 2026-11-22 05:12:16 +00:00
SDL Vertex Replay + Dragon API (#2224)
This commit is contained in:
1 parent
3389b952d0
commit
5ed1c92590
25 files changed
+2035
-101
No files matched your search
@@ -181,6 +181,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
|
||||
// Custom images and SSBOs
|
||||
private final Set<GlImage> customImages;
|
||||
private final VertexWriteReplays vertexWriteReplays = new VertexWriteReplays();
|
||||
private final GlImage[] imagesToClear;
|
||||
@Nullable
|
||||
private final ShaderStorageBufferHolder ssboHolder;
|
||||
@@ -1181,6 +1182,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
ProgramBuilder builder = beginBuilder(source.getName(), transformed);
|
||||
wireGbufferProgram(builder, availability, shadow);
|
||||
final Program program = builder.build();
|
||||
vertexWriteReplays.attach(source.getName(), program, transformed, (samplers, images) -> wireGbufferResources(samplers, images, availability, shadow));
|
||||
|
||||
final Pass pass = createPassInner(program, source.getDirectives(), shadow, id);
|
||||
this.customUniforms.mapholderToPass(builder, pass);
|
||||
@@ -1194,17 +1196,20 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
private void wireGbufferProgram(ProgramBuilder builder, InputAvailability availability, boolean shadow) {
|
||||
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
|
||||
this.customUniforms.assignTo(builder);
|
||||
wireGbufferResources(builder, builder, availability, shadow);
|
||||
}
|
||||
|
||||
private void wireGbufferResources(SamplerHolder samplers, ImageHolder images, InputAvailability availability, boolean shadow) {
|
||||
final Supplier<ImmutableSet<Integer>> flipped = shadow ? flippedShadowGbuffers : flippedGbuffers;
|
||||
|
||||
TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW;
|
||||
|
||||
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor =
|
||||
ProgramSamplers.customTextureSamplerInterceptor(builder,
|
||||
ProgramSamplers.customTextureSamplerInterceptor(samplers,
|
||||
customTextureManager.getCustomTextureIdMap(textureStage));
|
||||
|
||||
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
|
||||
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
|
||||
IrisImages.addRenderTargetImages(images, flipped, renderTargets);
|
||||
|
||||
if (!shouldBindPBR) {
|
||||
shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor);
|
||||
@@ -1220,7 +1225,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
|
||||
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
|
||||
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
|
||||
IrisImages.addCustomImages(builder, customImages);
|
||||
IrisImages.addCustomImages(images, customImages);
|
||||
|
||||
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
|
||||
if (!shadow) {
|
||||
@@ -1229,7 +1234,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
|
||||
if (shadowRenderTargets != null) {
|
||||
recordSamplerUsage(IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true));
|
||||
IrisImages.addShadowColorImages(builder, shadowRenderTargets, null);
|
||||
IrisImages.addShadowColorImages(images, shadowRenderTargets, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1527,6 +1532,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
final ProgramBuilder builder = beginBuilder(sourceName + kind.variantSuffix, transformed);
|
||||
wireGbufferProgram(builder, availability, shadow);
|
||||
final Program variant = builder.build();
|
||||
vertexWriteReplays.attach(sourceName + kind.variantSuffix, variant, transformed, (samplers, images) -> wireGbufferResources(samplers, images, availability, shadow));
|
||||
this.customUniforms.mapholderToPass(builder, variant);
|
||||
return variant;
|
||||
} catch (Exception e) {
|
||||
@@ -1606,6 +1612,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
|
||||
}
|
||||
}
|
||||
}
|
||||
vertexWriteReplays.destroy();
|
||||
if (shadowVoxelizationCompute != null) {
|
||||
shadowVoxelizationCompute.destroy();
|
||||
shadowVoxelizationCompute = null;
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package net.coderbot.iris.pipeline;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.VertexWriteReplaySetup;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import net.coderbot.iris.Iris;
|
||||
import net.coderbot.iris.gl.image.ImageHolder;
|
||||
import net.coderbot.iris.gl.program.ComputeProgram;
|
||||
import net.coderbot.iris.gl.program.Program;
|
||||
import net.coderbot.iris.gl.program.ProgramBuilder;
|
||||
import net.coderbot.iris.gl.sampler.GlSampler;
|
||||
import net.coderbot.iris.gl.sampler.SamplerHolder;
|
||||
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
|
||||
import net.coderbot.iris.pipeline.transform.PatchShaderType;
|
||||
import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor;
|
||||
import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor.VertexInput;
|
||||
import net.coderbot.iris.samplers.IrisSamplers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
/**
|
||||
* SDL-GPU only allows image writes from compute, so a gbuffers/shadow vertex shader that writes images gets a compute
|
||||
* twin that the backend runs over every draw made with the program.
|
||||
*/
|
||||
final class VertexWriteReplays {
|
||||
|
||||
private final List<ComputeProgram> twins = new ArrayList<>();
|
||||
private final IntArrayList attachedPrograms = new IntArrayList();
|
||||
|
||||
void attach(String name, Program program, Map<PatchShaderType, String> transformed, BiConsumer<SamplerHolder, ImageHolder> wireResources) {
|
||||
BackendManager.RENDER_BACKEND.setVertexWriteReplay(program.getProgramId(), null);
|
||||
final String source = transformed.get(PatchShaderType.COMPUTE);
|
||||
if (RwImageStoreExtractor.parseSentinel(source) != RwImageStoreExtractor.RwExtractMode.VERTEX_REPLAY) return;
|
||||
|
||||
final ComputeProgram twin;
|
||||
try {
|
||||
twin = ProgramBuilder.beginCompute(name + "_vertex_replay", source, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS).buildCompute();
|
||||
} catch (RuntimeException e) {
|
||||
Iris.logger.error("Vertex image write replay for {} failed to build; its image writes are dropped", name, e);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<String> writtenImages = RwImageStoreExtractor.parseVertexReplayImages(source);
|
||||
final List<String> images = new ArrayList<>(writtenImages);
|
||||
images.addAll(RwImageStoreExtractor.parseVertexReplayReadImages(source));
|
||||
final List<String> samplers = new ArrayList<>();
|
||||
for (String sampler : RwImageStoreExtractor.parseVertexReplaySamplers(source)) {
|
||||
if (RenderSystem.getUniformLocation(twin.getProgramId(), sampler) != -1) samplers.add(sampler);
|
||||
}
|
||||
final ResourceCollector resources = new ResourceCollector(images, samplers);
|
||||
wireResources.accept(resources, resources);
|
||||
for (int i = 0; i < resources.images.length; i++) {
|
||||
if (resources.images[i] == null) {
|
||||
Iris.logger.warn("Vertex image writes of {} use image {}, which the pipeline does not provide; they are dropped", name, resources.imageNames.get(i));
|
||||
twin.destroy();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final List<VertexInput> inputs = RwImageStoreExtractor.parseVertexReplayInputs(source);
|
||||
final String[] inputNames = new String[inputs.size()];
|
||||
final int[] inputLocations = new int[inputs.size()];
|
||||
for (int i = 0; i < inputs.size(); i++) {
|
||||
inputNames[i] = inputs.get(i).name();
|
||||
inputLocations[i] = inputs.get(i).location();
|
||||
}
|
||||
BackendManager.RENDER_BACKEND.setVertexWriteReplay(program.getProgramId(), new VertexWriteReplaySetup(twin.getProgramId(),
|
||||
inputNames, inputLocations, resources.images, writtenImages.size(),
|
||||
resources.samplerNames.toArray(new String[0]), resources.samplerUnits, resources.samplerTextures, resources.samplerObjects,
|
||||
RwImageStoreExtractor.VG_REPLAY_VERTEX_BUFFER_BINDING, RwImageStoreExtractor.VG_REPLAY_VERTEX_BUFFER_COUNT, RwImageStoreExtractor.VG_REPLAY_INDEX_BUFFER_BINDING));
|
||||
attachedPrograms.add(program.getProgramId());
|
||||
twins.add(twin);
|
||||
}
|
||||
|
||||
void destroy() {
|
||||
for (int i = 0; i < attachedPrograms.size(); i++) BackendManager.RENDER_BACKEND.setVertexWriteReplay(attachedPrograms.getInt(i), null);
|
||||
attachedPrograms.clear();
|
||||
for (ComputeProgram twin : twins) twin.destroy();
|
||||
twins.clear();
|
||||
}
|
||||
|
||||
private static final class ResourceCollector implements SamplerHolder, ImageHolder {
|
||||
final List<String> imageNames;
|
||||
final IntSupplier[] images;
|
||||
final List<String> samplerNames;
|
||||
final int[] samplerUnits;
|
||||
final IntSupplier[] samplerTextures;
|
||||
final int[] samplerObjects;
|
||||
|
||||
ResourceCollector(List<String> imageNames, List<String> samplerNames) {
|
||||
this.imageNames = imageNames;
|
||||
this.images = new IntSupplier[imageNames.size()];
|
||||
this.samplerNames = samplerNames;
|
||||
this.samplerUnits = new int[samplerNames.size()];
|
||||
Arrays.fill(samplerUnits, -1);
|
||||
this.samplerTextures = new IntSupplier[samplerNames.size()];
|
||||
this.samplerObjects = new int[samplerNames.size()];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasImage(String name) {
|
||||
return imageNames.contains(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTextureImage(IntSupplier textureID, InternalTextureFormat internalFormat, String name) {
|
||||
final int index = imageNames.indexOf(name);
|
||||
if (index >= 0 && images[index] == null) images[index] = textureID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasSampler(String name) {
|
||||
return samplerNames.contains(name) || imageNames.contains(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addExternalSampler(int textureUnit, String... names) {
|
||||
for (String name : names) {
|
||||
final int index = samplerNames.indexOf(name);
|
||||
if (index >= 0 && unassigned(index)) samplerUnits[index] = textureUnit;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
|
||||
return addDynamicSampler(type, texture, notifier, sampler, names);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) {
|
||||
return addDynamicSampler(type, texture, null, sampler, names);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
|
||||
boolean used = false;
|
||||
for (String name : names) {
|
||||
final int index = samplerNames.indexOf(name);
|
||||
if (index < 0) continue;
|
||||
used = true;
|
||||
if (unassigned(index)) {
|
||||
samplerTextures[index] = texture;
|
||||
samplerObjects[index] = sampler != null ? sampler.getId() : 0;
|
||||
}
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
private boolean unassigned(int index) {
|
||||
return samplerUnits[index] < 0 && samplerTextures[index] == null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package net.coderbot.iris.pipeline.transform;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import net.coderbot.iris.gl.program.ComputeProgram;
|
||||
import net.coderbot.iris.postprocess.FullScreenQuadRenderer;
|
||||
import net.coderbot.iris.uniforms.custom.CustomUniforms;
|
||||
import org.lwjgl.opengl.GL20;
|
||||
import org.lwjgl.opengl.GL42;
|
||||
@@ -16,6 +17,7 @@ public final class PreRasterComputeDispatcher {
|
||||
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
|
||||
compute.use();
|
||||
uniforms.push(compute);
|
||||
if (mode == RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH) FullScreenQuadRenderer.uploadCompositeMatrices();
|
||||
int targetSizeLoc = cachedTargetSizeLoc;
|
||||
if (mode == RwImageStoreExtractor.RwExtractMode.COMPOSITE_FSH) {
|
||||
if (targetSizeLoc == LOC_UNRESOLVED) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import org.antlr.v4.runtime.CommonToken;
|
||||
import org.antlr.v4.runtime.ParserRuleContext;
|
||||
import org.antlr.v4.runtime.tree.ParseTree;
|
||||
import org.antlr.v4.runtime.tree.TerminalNode;
|
||||
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
||||
import org.taumc.glsl.ShaderParser;
|
||||
import org.taumc.glsl.Transformer;
|
||||
import org.taumc.glsl.grammar.GLSLLexer;
|
||||
@@ -25,23 +26,26 @@ import java.util.Set;
|
||||
|
||||
public final class RwImageStoreExtractor {
|
||||
|
||||
public enum RwExtractMode { CHUNK, COMPOSITE_VSH, COMPOSITE_FSH }
|
||||
public enum RwExtractMode { CHUNK, COMPOSITE_VSH, COMPOSITE_FSH, VERTEX_REPLAY }
|
||||
|
||||
public static RwExtractMode parseSentinel(String computeSource) {
|
||||
if (computeSource == null) return null;
|
||||
if (computeSource.startsWith("// _vg_mode: chunk")) return RwExtractMode.CHUNK;
|
||||
if (computeSource.startsWith("// _vg_mode: composite-vsh")) return RwExtractMode.COMPOSITE_VSH;
|
||||
if (computeSource.startsWith("// _vg_mode: composite-fsh")) return RwExtractMode.COMPOSITE_FSH;
|
||||
if (computeSource.startsWith("// _vg_mode: vertex-replay")) return RwExtractMode.VERTEX_REPLAY;
|
||||
return null;
|
||||
}
|
||||
|
||||
public record VertexInput(String name, String glslType, int location) {}
|
||||
|
||||
public record AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr, boolean liveBranch) {
|
||||
public AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr) {
|
||||
this(name, glslType, byteOffset, unpackExpr, true);
|
||||
}
|
||||
}
|
||||
|
||||
public record Result(String strippedSource, String computeSource, Set<String> writtenImages, RwExtractMode mode) {}
|
||||
public record Result(String strippedSource, String computeSource, Set<String> writtenImages, RwExtractMode mode, boolean keepsImageAtomics) {}
|
||||
|
||||
public record ImageDecl(String name, String glslType, String layoutFormat) {}
|
||||
|
||||
@@ -53,6 +57,9 @@ public final class RwImageStoreExtractor {
|
||||
|
||||
public static final int VG_VBUF_SSBO_BINDING = 9;
|
||||
public static final int VG_RANGES_SSBO_BINDING = 10;
|
||||
public static final int VG_REPLAY_VERTEX_BUFFER_BINDING = 9;
|
||||
public static final int VG_REPLAY_VERTEX_BUFFER_COUNT = 4;
|
||||
public static final int VG_REPLAY_INDEX_BUFFER_BINDING = VG_REPLAY_VERTEX_BUFFER_BINDING + VG_REPLAY_VERTEX_BUFFER_COUNT;
|
||||
private static final int STRIDE_BYTES = 48;
|
||||
private static final int STRIDE_UINTS = STRIDE_BYTES / 4;
|
||||
|
||||
@@ -73,6 +80,10 @@ public final class RwImageStoreExtractor {
|
||||
);
|
||||
|
||||
public static Result tryExtract(String source, PatchShaderType stage, String programName) {
|
||||
return tryExtract(source, stage, programName, null);
|
||||
}
|
||||
|
||||
public static Result tryExtract(String source, PatchShaderType stage, String programName, RwExtractMode vertexMode) {
|
||||
if (source == null) return null;
|
||||
if (stage != PatchShaderType.VERTEX && stage != PatchShaderType.FRAGMENT) return null;
|
||||
|
||||
@@ -94,17 +105,184 @@ public final class RwImageStoreExtractor {
|
||||
final Map<String, String> chunkAttrAstTypes = (stage == PatchShaderType.VERTEX) ? collectChunkAttrAstTypes(decls) : Map.of();
|
||||
final Set<String> chunkAttrsUsed = (stage == PatchShaderType.VERTEX) ? collectChunkAttrsUsed(decls, root, source) : Set.of();
|
||||
|
||||
final RwExtractMode mode = (stage == PatchShaderType.VERTEX) ? (chunkAttrsUsed.isEmpty() ? RwExtractMode.COMPOSITE_VSH : RwExtractMode.CHUNK) : RwExtractMode.COMPOSITE_FSH;
|
||||
final RwExtractMode mode = (stage == PatchShaderType.VERTEX)
|
||||
? (vertexMode != null ? vertexMode : chunkAttrsUsed.isEmpty() ? RwExtractMode.COMPOSITE_VSH : RwExtractMode.CHUNK)
|
||||
: RwExtractMode.COMPOSITE_FSH;
|
||||
|
||||
final List<AttributeSlot> attrs = (mode == RwExtractMode.CHUNK) ? collectVertexAttributes(chunkAttrsUsed, chunkAttrAstTypes) : List.of();
|
||||
final Set<String> quadInputs = (mode == RwExtractMode.COMPOSITE_VSH) ? declaredQuadInputs(decls) : Set.of();
|
||||
final boolean definesFtransform = definesFunction(root, "iris_ftransform");
|
||||
|
||||
final String stripped = buildRasterOutputViaSourceSlicing(source, decls, exprs, writtenImages, declared, mode);
|
||||
|
||||
final Transformer tc = new Transformer(root);
|
||||
applyComputeMutations(tc, writtenImages, declared, chunkAttrsUsed, mode, nonWriteonlyImages);
|
||||
final String compute = buildComputeOutput(root, mode, writtenImages, nonWriteonlyImages, declared, attrs);
|
||||
applyComputeMutations(tc, writtenImages, declared, mode == RwExtractMode.COMPOSITE_VSH ? quadInputs : chunkAttrsUsed, mode, nonWriteonlyImages);
|
||||
final String compute = buildComputeOutput(root, mode, writtenImages, nonWriteonlyImages, declared, attrs, quadInputs, definesFtransform, null);
|
||||
|
||||
return new Result(stripped, compute, writtenImages, mode);
|
||||
return new Result(stripped, compute, writtenImages, mode, keepsImageAtomics(root, writtenImages));
|
||||
}
|
||||
|
||||
public static Result tryExtractVertexReplay(String source) {
|
||||
if (source == null) return null;
|
||||
|
||||
final ShaderParser.ParsedShader parsed = ShaderParser.parseShader(source);
|
||||
final GLSLParser.Translation_unitContext root = parsed.full();
|
||||
|
||||
final List<GLSLParser.Single_declarationContext> decls = new ArrayList<>();
|
||||
final List<GLSLParser.Postfix_expressionContext> exprs = new ArrayList<>();
|
||||
GlslAstHelpers.collectInto(root,
|
||||
new List[] { decls, exprs },
|
||||
new Class<?>[] { GLSLParser.Single_declarationContext.class, GLSLParser.Postfix_expressionContext.class });
|
||||
|
||||
final Map<String, ImageDecl> declared = collectImageDecls(decls);
|
||||
final Set<String> writtenImages = new LinkedHashSet<>();
|
||||
final Set<String> nonWriteonlyImages = new LinkedHashSet<>();
|
||||
classifyImageCalls(exprs, declared, writtenImages, nonWriteonlyImages);
|
||||
if (writtenImages.isEmpty()) return null;
|
||||
|
||||
final String stripped = buildRasterOutputViaSourceSlicing(source, decls, exprs, writtenImages, declared, RwExtractMode.VERTEX_REPLAY);
|
||||
final List<VertexInput> inputs = collectVertexInputs(decls);
|
||||
if (inputs == null) return new Result(stripped, null, writtenImages, RwExtractMode.VERTEX_REPLAY, false);
|
||||
|
||||
final List<String> readImages = readOnlyImages(exprs, declared, writtenImages);
|
||||
final Set<String> inputNames = new LinkedHashSet<>();
|
||||
for (VertexInput input : inputs) inputNames.add(input.name());
|
||||
final Transformer tc = new Transformer(root);
|
||||
applyComputeMutations(tc, writtenImages, declared, inputNames, RwExtractMode.VERTEX_REPLAY, nonWriteonlyImages);
|
||||
for (String name : readImages) tc.removeVariable(name);
|
||||
final ReplayLayout layout = new ReplayLayout(inputs, readImages, replayHeader(inputs, writtenImages, readImages, collectSamplerNames(decls)));
|
||||
final String compute = buildComputeOutput(root, RwExtractMode.VERTEX_REPLAY, writtenImages, nonWriteonlyImages, declared, List.of(), Set.of(), false, layout);
|
||||
|
||||
return new Result(stripped, compute, writtenImages, RwExtractMode.VERTEX_REPLAY, keepsImageAtomics(root, writtenImages));
|
||||
}
|
||||
|
||||
private record ReplayLayout(List<VertexInput> inputs, List<String> readImages, String header) {}
|
||||
|
||||
private static final String REPLAY_INPUTS_HEADER = "// _vg_inputs:";
|
||||
private static final String REPLAY_IMAGES_HEADER = "// _vg_images:";
|
||||
private static final String REPLAY_READ_IMAGES_HEADER = "// _vg_read_images:";
|
||||
private static final String REPLAY_SAMPLERS_HEADER = "// _vg_samplers:";
|
||||
|
||||
private static String replayHeader(List<VertexInput> inputs, Set<String> writtenImages, List<String> readImages, List<String> samplers) {
|
||||
final StringBuilder out = new StringBuilder(REPLAY_INPUTS_HEADER);
|
||||
for (VertexInput input : inputs) out.append(' ').append(input.name()).append(':').append(input.glslType()).append(':').append(input.location());
|
||||
out.append('\n').append(REPLAY_IMAGES_HEADER);
|
||||
for (String image : sortedImages(writtenImages)) out.append(' ').append(image);
|
||||
out.append('\n').append(REPLAY_READ_IMAGES_HEADER);
|
||||
for (String image : readImages) out.append(' ').append(image);
|
||||
out.append('\n').append(REPLAY_SAMPLERS_HEADER);
|
||||
for (String sampler : samplers) out.append(' ').append(sampler);
|
||||
return out.append('\n').toString();
|
||||
}
|
||||
|
||||
/** Images the shader reads but never writes, sorted; the replay binds them after the written ones. */
|
||||
private static List<String> readOnlyImages(List<GLSLParser.Postfix_expressionContext> exprs, Map<String, ImageDecl> declared, Set<String> writtenImages) {
|
||||
final Set<String> read = new LinkedHashSet<>();
|
||||
for (var expr : exprs) {
|
||||
if (GlslAstHelpers.extractCallName(expr) == null) continue;
|
||||
final String firstArg = GlslAstHelpers.firstArgIdentifier(expr);
|
||||
if (declared.containsKey(firstArg) && !writtenImages.contains(firstArg)) read.add(firstArg);
|
||||
}
|
||||
final List<String> sorted = new ArrayList<>(read);
|
||||
Collections.sort(sorted);
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/** The images a vertex-replay compute source only reads, in the order of their bindings after the written ones. */
|
||||
public static List<String> parseVertexReplayReadImages(String computeSource) {
|
||||
return headerTokens(computeSource, REPLAY_READ_IMAGES_HEADER);
|
||||
}
|
||||
|
||||
/** The samplers a vertex-replay compute source declares. */
|
||||
public static List<String> parseVertexReplaySamplers(String computeSource) {
|
||||
return headerTokens(computeSource, REPLAY_SAMPLERS_HEADER);
|
||||
}
|
||||
|
||||
/** The inputs of a vertex-replay compute source, in the order of its {@code _vg_attr} slots. */
|
||||
public static List<VertexInput> parseVertexReplayInputs(String computeSource) {
|
||||
final List<VertexInput> out = new ArrayList<>();
|
||||
for (String token : headerTokens(computeSource, REPLAY_INPUTS_HEADER)) {
|
||||
final String[] parts = token.split(":");
|
||||
if (parts.length != 3) continue;
|
||||
out.add(new VertexInput(parts[0], parts[1], Integer.parseInt(parts[2])));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The images a vertex-replay compute source writes, in the order of their bindings. */
|
||||
public static List<String> parseVertexReplayImages(String computeSource) {
|
||||
return headerTokens(computeSource, REPLAY_IMAGES_HEADER);
|
||||
}
|
||||
|
||||
private static List<String> headerTokens(String computeSource, String header) {
|
||||
if (computeSource == null) return List.of();
|
||||
final int start = computeSource.indexOf(header);
|
||||
if (start < 0) return List.of();
|
||||
final int end = computeSource.indexOf('\n', start);
|
||||
final String line = computeSource.substring(start + header.length(), end < 0 ? computeSource.length() : end).trim();
|
||||
if (line.isEmpty()) return List.of();
|
||||
return List.of(line.split(" "));
|
||||
}
|
||||
|
||||
private static final Set<String> REPLAYABLE_INPUT_TYPES = Set.of(
|
||||
"float", "vec2", "vec3", "vec4", "int", "ivec2", "ivec3", "ivec4", "uint", "uvec2", "uvec3", "uvec4");
|
||||
|
||||
/** Global {@code in}/{@code attribute} declarations, or null if one of them cannot be fetched per component. */
|
||||
private static List<VertexInput> collectVertexInputs(List<GLSLParser.Single_declarationContext> decls) {
|
||||
final List<VertexInput> out = new ArrayList<>();
|
||||
for (var decl : decls) {
|
||||
final var fst = decl.fully_specified_type();
|
||||
if (fst == null || fst.type_qualifier() == null) continue;
|
||||
if (GlslAstHelpers.enclosingOfType(decl, GLSLParser.Function_definitionContext.class) != null) continue;
|
||||
boolean isInput = false;
|
||||
int location = -1;
|
||||
for (var sq : fst.type_qualifier().single_type_qualifier()) {
|
||||
if (sq.storage_qualifier() != null) {
|
||||
final String storage = sq.storage_qualifier().getText();
|
||||
if (storage.equals("in") || storage.equals("attribute")) isInput = true;
|
||||
}
|
||||
final var lq = sq.layout_qualifier();
|
||||
if (lq == null || lq.layout_qualifier_id_list() == null) continue;
|
||||
for (var id : lq.layout_qualifier_id_list().layout_qualifier_id()) {
|
||||
if (id.IDENTIFIER() == null || !"location".equals(id.IDENTIFIER().getText())) continue;
|
||||
try {
|
||||
location = Integer.parseInt(id.getText().substring(id.getText().indexOf('=') + 1).trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isInput) continue;
|
||||
final String type = fst.type_specifier().getText();
|
||||
if (!REPLAYABLE_INPUT_TYPES.contains(type)) return null;
|
||||
final List<GLSLParser.Typeless_declarationContext> declarators = new ArrayList<>();
|
||||
declarators.add(decl.typeless_declaration());
|
||||
if (decl.getParent() instanceof GLSLParser.Init_declarator_listContext list) declarators.addAll(list.typeless_declaration());
|
||||
for (var typeless : declarators) {
|
||||
if (typeless == null || typeless.IDENTIFIER() == null || typeless.array_specifier() != null) return null;
|
||||
out.add(new VertexInput(typeless.IDENTIFIER().getText(), type, location));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Global sampler uniforms, which the replay may read even after the graphics program stops reading them. */
|
||||
private static List<String> collectSamplerNames(List<GLSLParser.Single_declarationContext> decls) {
|
||||
final List<String> out = new ArrayList<>();
|
||||
for (var decl : decls) {
|
||||
final var fst = decl.fully_specified_type();
|
||||
if (fst == null || fst.type_specifier() == null) continue;
|
||||
if (GlslAstHelpers.enclosingOfType(decl, GLSLParser.Function_definitionContext.class) != null) continue;
|
||||
final String type = fst.type_specifier().getText();
|
||||
if (!type.startsWith("sampler") && !type.startsWith("isampler") && !type.startsWith("usampler")) continue;
|
||||
final List<GLSLParser.Typeless_declarationContext> declarators = new ArrayList<>();
|
||||
declarators.add(decl.typeless_declaration());
|
||||
if (decl.getParent() instanceof GLSLParser.Init_declarator_listContext list) declarators.addAll(list.typeless_declaration());
|
||||
for (var typeless : declarators) {
|
||||
if (typeless != null && typeless.IDENTIFIER() != null) out.add(typeless.IDENTIFIER().getText());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, ImageDecl> collectImageDecls(List<GLSLParser.Single_declarationContext> decls) {
|
||||
@@ -270,13 +448,22 @@ public final class RwImageStoreExtractor {
|
||||
private static void applyComputeMutations(Transformer tc, Set<String> writtenImages, Map<String, ImageDecl> declared, Set<String> chunkAttrsUsed, RwExtractMode mode, Set<String> nonWriteonlyImages) {
|
||||
hoistNonConstGlobalInitializers(tc);
|
||||
renameMainToVgBody(tc);
|
||||
rewriteImageAtomicsToNonAtomic(tc, declared, writtenImages, nonWriteonlyImages);
|
||||
if (mode != RwExtractMode.VERTEX_REPLAY) rewriteImageAtomicsToNonAtomic(tc, declared, writtenImages, nonWriteonlyImages);
|
||||
for (String name : writtenImages) tc.removeVariable(name);
|
||||
if (mode == RwExtractMode.CHUNK) {
|
||||
if (mode == RwExtractMode.CHUNK || mode == RwExtractMode.VERTEX_REPLAY) {
|
||||
for (String name : chunkAttrsUsed) tc.removeVariable(name);
|
||||
convertInterfaceBlocks(tc);
|
||||
if (mode == RwExtractMode.VERTEX_REPLAY) {
|
||||
stripInterfaceLayoutQualifiers(tc);
|
||||
removeQualifierOnlyDeclarations(tc);
|
||||
}
|
||||
stripStorageQualifiers(tc, Set.of("out", "varying"));
|
||||
} else if (mode == RwExtractMode.COMPOSITE_VSH) {
|
||||
for (String name : chunkAttrsUsed) tc.removeVariable(name);
|
||||
tc.renameFunctionCall("ftransform", "iris_ftransform");
|
||||
convertInterfaceBlocks(tc);
|
||||
stripInterfaceLayoutQualifiers(tc);
|
||||
removeQualifierOnlyDeclarations(tc);
|
||||
stripStorageQualifiers(tc, Set.of("in", "attribute", "out", "varying"));
|
||||
} else if (mode == RwExtractMode.COMPOSITE_FSH) {
|
||||
stripFragOutputs(tc);
|
||||
@@ -311,6 +498,14 @@ public final class RwImageStoreExtractor {
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean keepsImageAtomics(GLSLParser.Translation_unitContext computeRoot, Set<String> writtenImages) {
|
||||
for (var expr : GlslAstHelpers.collectAll(computeRoot, GLSLParser.Postfix_expressionContext.class)) {
|
||||
final String fname = GlslAstHelpers.extractCallName(expr);
|
||||
if (fname != null && ATOMIC_CALLS.contains(fname) && writtenImages.contains(GlslAstHelpers.firstArgIdentifier(expr))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCallTopLevelStatement(GLSLParser.Postfix_expressionContext expr) {
|
||||
final GLSLParser.StatementContext stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class);
|
||||
if (stmt == null) return false;
|
||||
@@ -409,6 +604,7 @@ public final class RwImageStoreExtractor {
|
||||
t.mutateTree(tree -> {
|
||||
for (var sq : GlslAstHelpers.collectAll(tree, GLSLParser.Storage_qualifierContext.class)) {
|
||||
if (!kill.contains(sq.getText())) continue;
|
||||
if (GlslAstHelpers.enclosingOfType(sq, GLSLParser.Parameter_declarationContext.class) != null) continue;
|
||||
blankLeadingToken(sq);
|
||||
}
|
||||
});
|
||||
@@ -428,6 +624,91 @@ public final class RwImageStoreExtractor {
|
||||
|
||||
private static final Set<String> AUXILIARY_STORAGE_QUALIFIERS = Set.of("centroid", "sample", "patch");
|
||||
|
||||
private static final Set<String> INTERFACE_STORAGE_QUALIFIERS = Set.of("in", "out", "attribute", "varying");
|
||||
|
||||
private static void removeQualifierOnlyDeclarations(Transformer t) {
|
||||
t.mutateTree(tree -> {
|
||||
if (tree.children == null) return;
|
||||
tree.children.removeIf(child -> child instanceof GLSLParser.External_declarationContext ed
|
||||
&& ed.declaration() != null && isQualifierOnly(ed.declaration()));
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isQualifierOnly(GLSLParser.DeclarationContext decl) {
|
||||
if (decl.LEFT_BRACE() != null) return false;
|
||||
if (decl.init_declarator_list() == null) return decl.type_qualifier() != null && qualifiesStageInterface(decl.type_qualifier());
|
||||
final var single = decl.init_declarator_list().single_declaration();
|
||||
return single != null && single.typeless_declaration() == null && decl.init_declarator_list().COMMA().isEmpty()
|
||||
&& single.fully_specified_type() != null && single.fully_specified_type().type_qualifier() != null
|
||||
&& qualifiesStageInterface(single.fully_specified_type().type_qualifier());
|
||||
}
|
||||
|
||||
private static boolean qualifiesStageInterface(GLSLParser.Type_qualifierContext tq) {
|
||||
for (var sq : tq.single_type_qualifier()) {
|
||||
if (sq.invariant_qualifier() != null || sq.precise_qualifier() != null) return true;
|
||||
if (sq.storage_qualifier() != null && INTERFACE_STORAGE_QUALIFIERS.contains(sq.storage_qualifier().getText())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void convertInterfaceBlocks(Transformer t) {
|
||||
t.mutateTree(tree -> {
|
||||
if (tree.children == null) return;
|
||||
tree.children.removeIf(child -> child instanceof GLSLParser.External_declarationContext ed
|
||||
&& isInterfaceBlock(ed.declaration()) && "gl_PerVertex".equals(ed.declaration().IDENTIFIER(0).getText()));
|
||||
for (var child : tree.children) {
|
||||
if (!(child instanceof GLSLParser.External_declarationContext ed) || !isInterfaceBlock(ed.declaration())) continue;
|
||||
final GLSLParser.DeclarationContext decl = ed.declaration();
|
||||
final String blockName = decl.IDENTIFIER(0).getText();
|
||||
blankAllTerminals(decl.type_qualifier());
|
||||
if (decl.IDENTIFIER().size() > 1) {
|
||||
setFirstTerminal(decl.type_qualifier(), "struct");
|
||||
setText(decl.RIGHT_BRACE(), "}; " + blockName);
|
||||
} else {
|
||||
setText(decl.IDENTIFIER(0), "");
|
||||
setText(decl.LEFT_BRACE(), "");
|
||||
setText(decl.RIGHT_BRACE(), "");
|
||||
setText(decl.SEMICOLON(), "");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isInterfaceBlock(GLSLParser.DeclarationContext decl) {
|
||||
return decl != null && decl.LEFT_BRACE() != null && decl.type_qualifier() != null && !decl.IDENTIFIER().isEmpty()
|
||||
&& qualifiesStageInterface(decl.type_qualifier());
|
||||
}
|
||||
|
||||
private static void setText(TerminalNode node, String text) {
|
||||
if (node != null && node.getSymbol() instanceof CommonToken ct) ct.setText(text);
|
||||
}
|
||||
|
||||
private static void setFirstTerminal(ParseTree node, String text) {
|
||||
if (node instanceof TerminalNode tn) {
|
||||
setText(tn, text);
|
||||
return;
|
||||
}
|
||||
if (node.getChildCount() > 0) setFirstTerminal(node.getChild(0), text);
|
||||
}
|
||||
|
||||
private static void stripInterfaceLayoutQualifiers(Transformer t) {
|
||||
t.mutateTree(tree -> {
|
||||
for (var tq : GlslAstHelpers.collectAll(tree, GLSLParser.Type_qualifierContext.class)) {
|
||||
boolean isInterface = false;
|
||||
for (var sq : tq.single_type_qualifier()) {
|
||||
if (sq.storage_qualifier() != null && INTERFACE_STORAGE_QUALIFIERS.contains(sq.storage_qualifier().getText())) {
|
||||
isInterface = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isInterface) continue;
|
||||
for (var sq : tq.single_type_qualifier()) {
|
||||
if (sq.layout_qualifier() != null) blankAllTerminals(sq.layout_qualifier());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void blankLeadingToken(ParserRuleContext ctx) {
|
||||
if (ctx.getChildCount() == 0) return;
|
||||
if (!(ctx.getChild(0) instanceof TerminalNode tn)) return;
|
||||
@@ -537,19 +818,42 @@ public final class RwImageStoreExtractor {
|
||||
});
|
||||
}
|
||||
|
||||
private static String buildComputeOutput(GLSLParser.Translation_unitContext computeRoot, RwExtractMode mode, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, List<AttributeSlot> attrs) {
|
||||
private static final Set<String> QUAD_INPUTS = Set.of("iris_Vertex", "iris_MultiTexCoord0");
|
||||
|
||||
private static Set<String> declaredQuadInputs(List<GLSLParser.Single_declarationContext> decls) {
|
||||
final Set<String> out = new LinkedHashSet<>();
|
||||
for (var decl : decls) {
|
||||
if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue;
|
||||
if (GlslAstHelpers.enclosingOfType(decl, GLSLParser.Function_definitionContext.class) != null) continue;
|
||||
final String name = decl.typeless_declaration().IDENTIFIER().getText();
|
||||
if (QUAD_INPUTS.contains(name)) out.add(name);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean definesFunction(GLSLParser.Translation_unitContext root, String name) {
|
||||
for (var fdef : GlslAstHelpers.collectAll(root, GLSLParser.Function_definitionContext.class)) {
|
||||
final var id = fdef.function_prototype().IDENTIFIER();
|
||||
if (id != null && name.equals(id.getText())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String buildComputeOutput(GLSLParser.Translation_unitContext computeRoot, RwExtractMode mode, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, List<AttributeSlot> attrs, Set<String> quadInputs, boolean definesFtransform, ReplayLayout replay) {
|
||||
final StringBuilder out = new StringBuilder(8192);
|
||||
out.append("// _vg_mode: ").append(modeTag(mode)).append('\n');
|
||||
if (replay != null) out.append(replay.header());
|
||||
out.append("#version 460 core\n");
|
||||
switch (mode) {
|
||||
case CHUNK -> emitChunkPrelude(out, writtenImages, nonWriteonlyImages, declared, attrs);
|
||||
case COMPOSITE_VSH -> emitCompositeVshPrelude(out, writtenImages, nonWriteonlyImages, declared);
|
||||
case COMPOSITE_VSH -> emitCompositeVshPrelude(out, writtenImages, nonWriteonlyImages, declared, quadInputs, definesFtransform);
|
||||
case COMPOSITE_FSH -> emitCompositeFshPrelude(out, writtenImages, nonWriteonlyImages, declared);
|
||||
case VERTEX_REPLAY -> emitVertexReplayPrelude(out, writtenImages, nonWriteonlyImages, declared, replay);
|
||||
}
|
||||
out.append('\n');
|
||||
out.append(GlslTransformUtils.getFormattedShader(computeRoot, ""));
|
||||
out.append('\n');
|
||||
emitDispatchMain(out, mode, attrs);
|
||||
emitDispatchMain(out, mode, attrs, replay != null ? replay.inputs() : List.of(), quadInputs);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@@ -558,19 +862,26 @@ public final class RwImageStoreExtractor {
|
||||
case CHUNK -> "chunk";
|
||||
case COMPOSITE_VSH -> "composite-vsh";
|
||||
case COMPOSITE_FSH -> "composite-fsh";
|
||||
case VERTEX_REPLAY -> "vertex-replay";
|
||||
};
|
||||
}
|
||||
|
||||
private static void emitImageDecls(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
|
||||
private static List<String> sortedImages(Set<String> writtenImages) {
|
||||
final List<String> sorted = new ArrayList<>(writtenImages);
|
||||
Collections.sort(sorted);
|
||||
return sorted;
|
||||
}
|
||||
|
||||
private static void emitImageDecls(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
|
||||
final List<String> sorted = sortedImages(writtenImages);
|
||||
final Map<String, ImageInformation> infos = activeCustomImages;
|
||||
for (int i = 0; i < sorted.size(); i++) {
|
||||
final String name = sorted.get(i);
|
||||
final ImageDecl d = declared.get(name);
|
||||
if (d == null) continue;
|
||||
final InternalTextureFormat fmt = (infos != null && infos.get(name) != null) ? infos.get(name).internalTextureFormat() : null;
|
||||
final String layoutInner = (fmt != null) ? "binding = " + i + ", " + fmt.name().toLowerCase(Locale.ROOT) : "binding = " + i;
|
||||
final String format = fmt != null ? fmt.name().toLowerCase(Locale.ROOT) : d.layoutFormat();
|
||||
final String layoutInner = (format != null) ? "binding = " + i + ", " + format : "binding = " + i;
|
||||
final String qualifier = nonWriteonlyImages.contains(name) ? "" : "writeonly ";
|
||||
out.append("layout(").append(layoutInner).append(") ").append(qualifier).append("uniform ").append(d.glslType()).append(' ').append(name).append(";\n");
|
||||
}
|
||||
@@ -604,7 +915,7 @@ public final class RwImageStoreExtractor {
|
||||
out.append("void _vert_init() {}\n");
|
||||
}
|
||||
|
||||
private static void emitCompositeVshPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
|
||||
private static void emitCompositeVshPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, Set<String> quadInputs, boolean definesFtransform) {
|
||||
out.append("layout(local_size_x = 64) in;\n\n");
|
||||
emitImageDecls(out, writtenImages, nonWriteonlyImages, declared);
|
||||
out.append("\nconst vec4 _vg_quad[4] = vec4[4](\n");
|
||||
@@ -614,10 +925,67 @@ public final class RwImageStoreExtractor {
|
||||
out.append(" vec4(0.0, 0.0, 0.0, 1.0));\n");
|
||||
out.append("vec4 _vg_gl_vertex;\n");
|
||||
out.append("int _vg_gl_vertex_id;\n");
|
||||
out.append("vec4 _vg_sink_pos;\n");
|
||||
out.append("float _vg_sink_psize;\n");
|
||||
out.append("float _vg_sink_clip[8];\n");
|
||||
out.append("#define gl_Vertex _vg_gl_vertex\n");
|
||||
out.append("#define gl_VertexID _vg_gl_vertex_id\n");
|
||||
out.append("uniform mat4 gl_ModelViewProjectionMatrix;\n");
|
||||
out.append("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }\n");
|
||||
out.append("#define gl_Position _vg_sink_pos\n");
|
||||
out.append("#define gl_PointSize _vg_sink_psize\n");
|
||||
out.append("#define gl_ClipDistance _vg_sink_clip\n");
|
||||
for (String input : quadInputs) out.append("vec4 ").append(input).append(";\n");
|
||||
if (!definesFtransform) {
|
||||
out.append("uniform mat4 gl_ModelViewProjectionMatrix;\n");
|
||||
out.append("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }\n");
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitVertexReplayPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, ReplayLayout replay) {
|
||||
final List<VertexInput> inputs = replay.inputs();
|
||||
out.append("layout(local_size_x = 64) in;\n\n");
|
||||
emitImageDecls(out, writtenImages, nonWriteonlyImages, declared);
|
||||
final Map<String, ImageInformation> infos = activeCustomImages;
|
||||
for (int i = 0; i < replay.readImages().size(); i++) {
|
||||
final ImageDecl d = declared.get(replay.readImages().get(i));
|
||||
final InternalTextureFormat fmt = infos.get(d.name()) != null ? infos.get(d.name()).internalTextureFormat() : null;
|
||||
final String format = fmt != null ? fmt.name().toLowerCase(Locale.ROOT) : d.layoutFormat();
|
||||
out.append("layout(binding = ").append(writtenImages.size() + i).append(format != null ? ", " + format : "").append(") readonly uniform ")
|
||||
.append(d.glslType()).append(' ').append(d.name()).append(";\n");
|
||||
}
|
||||
out.append('\n');
|
||||
for (int i = 0; i < VG_REPLAY_VERTEX_BUFFER_COUNT; i++) {
|
||||
out.append("layout(std430, binding = ").append(VG_REPLAY_VERTEX_BUFFER_BINDING + i)
|
||||
.append(") readonly buffer _VgVertices").append(i).append(" { uint d[]; } _vg_vertices").append(i).append(";\n");
|
||||
}
|
||||
out.append("layout(std430, binding = ").append(VG_REPLAY_INDEX_BUFFER_BINDING).append(") readonly buffer _VgIndices { uint d[]; } _vg_indices;\n\n");
|
||||
final int slots = Math.max(1, inputs.size());
|
||||
out.append("uniform uvec4 _vg_attr[").append(slots).append("];\n");
|
||||
out.append("uniform vec4 _vg_attrDefault[").append(slots).append("];\n");
|
||||
out.append("uniform ivec4 _vg_draw;\n");
|
||||
out.append("uniform ivec3 _vg_index;\n");
|
||||
out.append("uniform uvec2 _vg_restart;\n");
|
||||
out.append("uniform int _vg_invocationBase;\n\n");
|
||||
out.append("vec4 _vg_sink_pos;\n");
|
||||
out.append("float _vg_sink_psize;\n");
|
||||
out.append("float _vg_sink_clip[8];\n");
|
||||
out.append("int _vg_vertex_id;\n");
|
||||
out.append("int _vg_instance_id;\n");
|
||||
out.append("#define gl_Position _vg_sink_pos\n");
|
||||
out.append("#define gl_PointSize _vg_sink_psize\n");
|
||||
out.append("#define gl_ClipDistance _vg_sink_clip\n");
|
||||
out.append("#define gl_VertexID _vg_vertex_id\n");
|
||||
out.append("#define gl_VertexIndex _vg_vertex_id\n");
|
||||
out.append("#define gl_InstanceID _vg_instance_id\n");
|
||||
out.append("#define gl_InstanceIndex _vg_instance_id\n");
|
||||
for (String suffix : new String[] { "", "ARB" }) {
|
||||
out.append("#define gl_BaseVertex").append(suffix).append(" _vg_draw.w\n");
|
||||
out.append("#define gl_BaseInstance").append(suffix).append(" 0\n");
|
||||
out.append("#define gl_DrawID").append(suffix).append(" 0\n");
|
||||
}
|
||||
out.append('\n');
|
||||
for (VertexInput input : inputs) out.append(input.glslType()).append(' ').append(input.name()).append(";\n");
|
||||
out.append('\n');
|
||||
out.append(ShaderLoader.getShaderSource("angelica:include/vertex_replay_fetch.glsl"));
|
||||
}
|
||||
|
||||
private static void emitCompositeFshPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
|
||||
@@ -643,7 +1011,7 @@ public final class RwImageStoreExtractor {
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitDispatchMain(StringBuilder out, RwExtractMode mode, List<AttributeSlot> attrs) {
|
||||
private static void emitDispatchMain(StringBuilder out, RwExtractMode mode, List<AttributeSlot> attrs, List<VertexInput> inputs, Set<String> quadInputs) {
|
||||
out.append("void main() {\n");
|
||||
switch (mode) {
|
||||
case CHUNK -> {
|
||||
@@ -665,6 +1033,7 @@ public final class RwImageStoreExtractor {
|
||||
out.append(" uint vid = gl_GlobalInvocationID.x;\n");
|
||||
out.append(" if (vid >= 4u) return;\n");
|
||||
out.append(" _vg_gl_vertex = _vg_quad[vid];\n");
|
||||
for (String input : quadInputs) out.append(" ").append(input).append(" = _vg_quad[vid];\n");
|
||||
out.append(" _vg_gl_vertex_id = int(vid);\n");
|
||||
out.append(" _vg_body();\n");
|
||||
}
|
||||
@@ -674,10 +1043,37 @@ public final class RwImageStoreExtractor {
|
||||
out.append(" _vg_gl_fragcoord_raw = vec4(vec2(px) + 0.5, 0.0, 1.0);\n");
|
||||
out.append(" _vg_body();\n");
|
||||
}
|
||||
case VERTEX_REPLAY -> {
|
||||
out.append(" uint _vg_g = uint(_vg_invocationBase) + gl_GlobalInvocationID.x;\n");
|
||||
out.append(" uint _vg_count = uint(_vg_draw.y);\n");
|
||||
out.append(" if (_vg_count == 0u || _vg_g >= _vg_count * uint(_vg_draw.z)) return;\n");
|
||||
out.append(" uint _vg_v = _vg_g % _vg_count;\n");
|
||||
out.append(" uint _vg_i = _vg_g / _vg_count;\n");
|
||||
out.append(" uint _vg_vertex = uint(_vg_draw.x) + _vg_v;\n");
|
||||
out.append(" if (_vg_index.x != 0) {\n");
|
||||
out.append(" uint _vg_index_value = _vg_v < uint(_vg_index.z) ? _vg_read(4u, uint(_vg_index.y) + _vg_v * uint(_vg_index.x), uint(_vg_index.x)) : 0u;\n");
|
||||
out.append(" if (_vg_restart.x != 0u && _vg_index_value == _vg_restart.y) return;\n");
|
||||
out.append(" _vg_vertex = _vg_index_value + uint(_vg_draw.w);\n");
|
||||
out.append(" }\n");
|
||||
out.append(" _vg_vertex_id = int(_vg_vertex);\n");
|
||||
out.append(" _vg_instance_id = int(_vg_i);\n");
|
||||
for (int k = 0; k < inputs.size(); k++) {
|
||||
final VertexInput input = inputs.get(k);
|
||||
out.append(" ").append(input.name()).append(" = ").append(input.glslType()).append('(')
|
||||
.append(fetchFunctionFor(input.glslType())).append('(').append(k).append("u, _vg_vertex, _vg_i));\n");
|
||||
}
|
||||
out.append(" _vg_body();\n");
|
||||
}
|
||||
}
|
||||
out.append("}\n");
|
||||
}
|
||||
|
||||
private static String fetchFunctionFor(String glslType) {
|
||||
if (glslType.startsWith("u")) return "_vg_uint";
|
||||
if (glslType.startsWith("i")) return "_vg_int";
|
||||
return "_vg_float";
|
||||
}
|
||||
|
||||
private static List<AttributeSlot> collectVertexAttributes(Set<String> chunkAttrsUsed, Map<String, String> chunkAttrAstTypes) {
|
||||
final List<AttributeSlot> out = new ArrayList<>();
|
||||
for (String name : chunkAttrsUsed) {
|
||||
|
||||
@@ -237,7 +237,8 @@ public class ShaderTransformer {
|
||||
final ShaderDiskCache.Key k = ShaderDiskCache.key("iris-transform").str(patch.name());
|
||||
parameters.appendDiskKey(k);
|
||||
k.i(RenderSystem.getMaxGlslVersion()).b(RenderSystem.supportsSSBO()).b(RenderSystem.supportsImageLoadStore())
|
||||
.b(RenderSystem.isGLES()).b(BackendManager.RENDER_BACKEND.isSDLGPU()).i(maxSupportedHoistVersion);
|
||||
.b(RenderSystem.isGLES()).b(BackendManager.RENDER_BACKEND.isSDLGPU()).b(BackendManager.RENDER_BACKEND.supportsComputeImageAtomics())
|
||||
.i(maxSupportedHoistVersion);
|
||||
if (enabledRequirements == null) {
|
||||
k.i(-1);
|
||||
} else {
|
||||
@@ -559,18 +560,23 @@ public class ShaderTransformer {
|
||||
artifactsOut.put(shaderType, new StageArtifact(treeHolder[0], formattedShader.length() - printedBody.length()));
|
||||
}
|
||||
}
|
||||
if (BackendManager.RENDER_BACKEND.isSDLGPU()) extractRwImageStores(result, patchType, artifactsOut);
|
||||
if (BackendManager.RENDER_BACKEND.isSDLGPU()) extractRwImageStores(result, patchType, artifactsOut, BackendManager.RENDER_BACKEND.supportsComputeImageAtomics());
|
||||
watch.stop();
|
||||
Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
|
||||
return result;
|
||||
}
|
||||
|
||||
static void extractRwImageStores(EnumMap<PatchShaderType, String> result, Patch patchType, EnumMap<PatchShaderType, StageArtifact> artifactsOut) {
|
||||
static void extractRwImageStores(EnumMap<PatchShaderType, String> result, Patch patchType, EnumMap<PatchShaderType, StageArtifact> artifactsOut, boolean computeImageAtomics) {
|
||||
if (result.containsKey(PatchShaderType.COMPUTE)) return;
|
||||
if (patchType == Patch.ATTRIBUTES) {
|
||||
extractVertexReplay(result, artifactsOut, computeImageAtomics);
|
||||
return;
|
||||
}
|
||||
|
||||
final String vsh = result.get(PatchShaderType.VERTEX);
|
||||
final String fsh = result.get(PatchShaderType.FRAGMENT);
|
||||
final RwImageStoreExtractor.Result vshResult = (vsh != null) ? RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, patchType.name()) : null;
|
||||
final RwImageStoreExtractor.RwExtractMode vertexMode = patchType == Patch.COMPOSITE ? RwImageStoreExtractor.RwExtractMode.COMPOSITE_VSH : null;
|
||||
final RwImageStoreExtractor.Result vshResult = (vsh != null) ? RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, patchType.name(), vertexMode) : null;
|
||||
final RwImageStoreExtractor.Result fshResult = (fsh != null) ? RwImageStoreExtractor.tryExtract(fsh, PatchShaderType.FRAGMENT, patchType.name()) : null;
|
||||
|
||||
if (vshResult != null && fshResult != null) {
|
||||
@@ -581,14 +587,42 @@ public class ShaderTransformer {
|
||||
final PatchShaderType stage = vshResult != null ? PatchShaderType.VERTEX : PatchShaderType.FRAGMENT;
|
||||
result.put(stage, extracted.strippedSource());
|
||||
if (artifactsOut != null) artifactsOut.remove(stage);
|
||||
if (patchType == Patch.COMPOSITE || patchType == Patch.CELERITAS_TERRAIN) {
|
||||
if (patchType != Patch.COMPOSITE && patchType != Patch.CELERITAS_TERRAIN) {
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped image writes from {} (written={})", patchType.name(), extracted.writtenImages());
|
||||
} else if (extracted.keepsImageAtomics() && !computeImageAtomics) {
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped image writes from {}, they need image atomics this backend cannot run (written={})", patchType.name(), extracted.writtenImages());
|
||||
} else {
|
||||
result.put(PatchShaderType.COMPUTE, extracted.computeSource());
|
||||
Iris.logger.info("[RwImageStoreExtractor] Extracted compute pre-pass for {} (mode={}, written={})", patchType.name(), extracted.mode(), extracted.writtenImages());
|
||||
} else {
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped image writes from {} (written={})", patchType.name(), extracted.writtenImages());
|
||||
}
|
||||
}
|
||||
|
||||
private static void extractVertexReplay(EnumMap<PatchShaderType, String> result, EnumMap<PatchShaderType, StageArtifact> artifactsOut, boolean computeImageAtomics) {
|
||||
final String fsh = result.get(PatchShaderType.FRAGMENT);
|
||||
final RwImageStoreExtractor.Result fshResult = (fsh != null) ? RwImageStoreExtractor.tryExtract(fsh, PatchShaderType.FRAGMENT, Patch.ATTRIBUTES.name()) : null;
|
||||
if (fshResult != null) {
|
||||
result.put(PatchShaderType.FRAGMENT, fshResult.strippedSource());
|
||||
if (artifactsOut != null) artifactsOut.remove(PatchShaderType.FRAGMENT);
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped fragment image writes from ATTRIBUTES (written={})", fshResult.writtenImages());
|
||||
}
|
||||
|
||||
final String vsh = result.get(PatchShaderType.VERTEX);
|
||||
final RwImageStoreExtractor.Result vshResult = (vsh != null) ? RwImageStoreExtractor.tryExtractVertexReplay(vsh) : null;
|
||||
if (vshResult == null) return;
|
||||
result.put(PatchShaderType.VERTEX, vshResult.strippedSource());
|
||||
if (artifactsOut != null) artifactsOut.remove(PatchShaderType.VERTEX);
|
||||
if (vshResult.computeSource() == null) {
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped vertex image writes from ATTRIBUTES, an input cannot be replayed (written={})", vshResult.writtenImages());
|
||||
return;
|
||||
}
|
||||
if (vshResult.keepsImageAtomics() && !computeImageAtomics) {
|
||||
Iris.logger.info("[RwImageStoreExtractor] Dropped vertex image writes from ATTRIBUTES, they need image atomics this backend cannot run (written={})", vshResult.writtenImages());
|
||||
return;
|
||||
}
|
||||
result.put(PatchShaderType.COMPUTE, vshResult.computeSource());
|
||||
Iris.logger.info("[RwImageStoreExtractor] Extracted vertex replay for ATTRIBUTES (written={})", vshResult.writtenImages());
|
||||
}
|
||||
|
||||
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, int versionInt) {
|
||||
switch (patchType) {
|
||||
case CELERITAS_TERRAIN:
|
||||
|
||||
Reference in new issue
Block a user