Instance more things (#2104)

* Flyby: pin the start origin and fly just above the route's terrain

* Instancing: particles, dropped items, entity cubes + shadow batching and some SDL-GPU fixes
This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-09-16 14:56:24 -07:00
1 parent 94ee37bfed
commit 3876f7e693
158 files changed
+9956 -1404

No files matched your search

@@ -4,12 +4,14 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.joml.Vector4fc;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -37,6 +39,7 @@ public class AngelicaBufferSource implements Groupable {
private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS];
private final Object2IntLinkedOpenHashMap<RenderLayer> affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS);
private final Map<RenderLayer, List<BufferSegment>> typeToSegment = new Object2ObjectOpenHashMap<>();
private final ObjectArrayList<List<BufferSegment>> segmentLists = new ObjectArrayList<>();
private boolean prepared;
private final List<RenderLayer> order = new ArrayList<>();
@@ -86,7 +89,13 @@ public class AngelicaBufferSource implements Groupable {
final List<BufferSegment> builderSegments = builder.getSegments();
for (int i = 0, n = builderSegments.size(); i < n; i++) {
final BufferSegment segment = builderSegments.get(i);
typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment);
List<BufferSegment> segments = typeToSegment.get(segment.getRenderType());
if (segments == null) {
segments = new ArrayList<>();
typeToSegment.put(segment.getRenderType(), segments);
segmentLists.add(segments);
}
segments.add(segment);
}
}
order.clear();
@@ -168,7 +177,7 @@ public class AngelicaBufferSource implements Groupable {
anyIdSet = false;
}
private GroupIdKind effectiveIdKind() {
public GroupIdKind effectiveIdKind() {
return GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.ENTITIES ? GroupIdKind.ENTITY : idKind;
}
@@ -223,8 +232,8 @@ public class AngelicaBufferSource implements Groupable {
}
private void clearSegmentLists() {
for (List<BufferSegment> segments : typeToSegment.values()) {
segments.clear();
for (int i = 0, n = segmentLists.size(); i < n; i++) {
segmentLists.get(i).clear();
}
}
@@ -245,6 +254,7 @@ public class AngelicaBufferSource implements Groupable {
builder.freeAll();
}
typeToSegment.clear();
segmentLists.clear();
order.clear();
affinities.clear();
renderOrderManager.reset();
@@ -283,19 +293,20 @@ public class AngelicaBufferSource implements Groupable {
}
}
public void applyIdNoRebind(int id) {
anyIdSet = true;
if (effectiveIdKind() == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(id, 0);
} else {
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id);
}
public static int packEntityColor(Vector4fc c) {
return packAbgr(c.x(), c.y(), c.z(), c.w());
}
public static void setEntityColor(int packed) {
CapturedRenderingState.INSTANCE.setCurrentEntityColor(
((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f,
(packed & 0xFF) / 255f, (packed >>> 24) / 255f);
public static int packAbgr(float r, float g, float b, float a) {
return (unit(a) << 24) | (unit(b) << 16) | (unit(g) << 8) | unit(r);
}
private static int unit(float v) {
return (int) (Math.clamp(v, 0f, 1f) * 255f + 0.5f);
}
public static void setEntityColor(int abgr) {
CapturedRenderingState.INSTANCE.setCurrentEntityColor((abgr & 0xFF) / 255f, ((abgr >>> 8) & 0xFF) / 255f, ((abgr >>> 16) & 0xFF) / 255f, (abgr >>> 24) / 255f);
}
public static void setBlockEntityAndRebind(int blockEntityId) {
@@ -1,6 +1,7 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
@@ -10,7 +11,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.joml.Matrix4fc;
import org.joml.Vector3f;
import org.joml.Vector4fc;
import org.lwjgl.BufferUtils;
import java.nio.ByteBuffer;
@@ -79,7 +79,7 @@ public class SegmentedBufferBuilder {
private long allocatedBytes;
public void begin(RenderLayer type, int blockEntityId) {
final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
final int entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) {
return;
}
@@ -98,10 +98,6 @@ public class SegmentedBufferBuilder {
segmentStartVertex = current.vertexCount;
}
public static int packEntityColor(Vector4fc c) {
return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f);
}
public void addQuad(ModelQuadView quad) {
if (current == null) {
throw new IllegalStateException("addQuad() without begin()");
@@ -125,6 +121,19 @@ public class SegmentedBufferBuilder {
current.vertexCount += template.vertexCount;
}
public void addPackedVertices(int[] packed, int vertexCount, Matrix4fc mv, Vector3f scratch) {
if (current == null) {
throw new IllegalStateException("addPackedVertices() without begin()");
}
final VertexFormat format = currentType.getVertexFormat();
ensureCurrentCapacity(format.getVertexSize() * vertexCount);
final ByteBuffer buffer = current.buffer;
final long ptr = memAddress0(buffer) + buffer.position();
final long end = format.writeToBuffer0(ptr, packed, vertexCount * ModelQuadUtil.VERTEX_SIZE, mv, scratch);
buffer.position(buffer.position() + (int) (end - ptr));
current.vertexCount += vertexCount;
}
private void ensureCurrentCapacity(int bytes) {
final int before = current.buffer.capacity();
current.ensureCapacity(bytes);
+1 -1
View File
@@ -238,7 +238,7 @@ public class Iris {
try {
submitTracked(() -> {
TransformPatcher.patchComposite(vertexShader, null, fragmentShader);
TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true));
TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, InputAvailability.of(true, true));
}).get();
} catch (Exception e) {
logger.warn("Warmup failed", e);
@@ -1,64 +1,28 @@
package net.coderbot.iris.gbuffer_overrides.matching;
public class InputAvailability {
public enum InputAvailability {
NONE(false, false), TEXTURE(true, false), LIGHTMAP(false, true), BOTH(true, true);
public static final int NUM_VALUES = 8;
public static final InputAvailability[] VALUES = values();
public final boolean texture;
public final boolean lightmap;
public InputAvailability(boolean texture, boolean lightmap) {
InputAvailability(boolean texture, boolean lightmap) {
this.texture = texture;
this.lightmap = lightmap;
}
public static InputAvailability of(boolean texture, boolean lightmap) {
return VALUES[(texture ? 1 : 0) | (lightmap ? 2 : 0)];
}
public static InputAvailability unpack(int packed) {
return new InputAvailability((packed & 1) == 1, (packed & 2) == 2);
return VALUES[packed & 3];
}
public int pack() {
int packed = 0;
if (lightmap) {
packed |= 2;
}
if (texture) {
packed |= 1;
}
return packed;
}
@Override
public String toString() {
return "InputAvailability{" +
"texture=" + texture +
", lightmap=" + lightmap +
'}';
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (lightmap ? 1231 : 1237);
result = prime * result + (texture ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InputAvailability other = (InputAvailability) obj;
if (lightmap != other.lightmap)
return false;
if (texture != other.texture)
return false;
return true;
return ordinal();
}
}
@@ -13,6 +13,6 @@ public class StateTracker {
public boolean lightmapSampler;
public InputAvailability getInputs() {
return new InputAvailability(albedoSampler, lightmapSampler);
return InputAvailability.of(albedoSampler, lightmapSampler);
}
}
@@ -25,8 +25,10 @@ public class ProgramCreator {
int program = GLStateManager.glCreateProgram();
// TODO: This is *really* hardcoded, we need to refactor this to support external calls to glBindAttribLocation
RenderSystem.bindAttributeLocation(program, MC_ENTITY, "iris_Entity");
RenderSystem.bindAttributeLocation(program, MC_ENTITY, "mc_Entity");
RenderSystem.bindAttributeLocation(program, MC_MID_TEX_COORD, "mc_midTexCoord");
RenderSystem.bindAttributeLocation(program, AT_TANGENT, "iris_CubeTangent");
RenderSystem.bindAttributeLocation(program, AT_TANGENT, "at_tangent");
RenderSystem.bindAttributeLocation(program, AT_MIDBLOCK, "at_midBlock");
@@ -329,12 +329,20 @@ public class GbufferPrograms {
public static void setupSpecialRenderCondition(SpecialCondition override) {
currentSpecial = override;
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override));
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setSpecialCondition(override);
}
}
public static void teardownSpecialRenderCondition() {
currentSpecial = null;
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null));
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setSpecialCondition(null);
}
}
public static void runPhaseChangeNotifier() {
@@ -3,12 +3,17 @@ package net.coderbot.iris.layer;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.Locale;
import java.util.Objects;
public record PassOverride(SpecialCondition special, Boolean translucent, WorldRenderingPhase phase) {
public static final PassOverride NONE = new PassOverride(null, null, null);
private static final ObjectArrayList<PassOverride> INTERNED = new ObjectArrayList<>();
public PassOverride(SpecialCondition special, Boolean translucent) {
this(special, translucent, null);
}
@@ -17,8 +22,18 @@ public record PassOverride(SpecialCondition special, Boolean translucent, WorldR
final SpecialCondition special = GbufferPrograms.getSpecialCondition();
final Boolean translucent = GbufferPrograms.getDeclaredTranslucency();
final WorldRenderingPhase phase = GbufferPrograms.getOverridePhase();
return special == null && translucent == null && phase == null
? NONE : new PassOverride(special, translucent, phase);
if (special == null && translucent == null && phase == null) {
return NONE;
}
for (int i = 0, n = INTERNED.size(); i < n; i++) {
final PassOverride candidate = INTERNED.get(i);
if (candidate.special == special && candidate.phase == phase && Objects.equals(candidate.translucent, translucent)) {
return candidate;
}
}
final PassOverride created = new PassOverride(special, translucent, phase);
INTERNED.add(created);
return created;
}
public void apply() {
@@ -13,8 +13,13 @@ import org.joml.Matrix4fc;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.PendingProgramSelection;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility;
import com.gtnewhorizons.angelica.rendering.tesr.TesrInstancingPipeline;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.Iris;
@@ -111,6 +116,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -127,7 +133,7 @@ import java.util.function.Supplier;
/**
* Encapsulates the compiled shader program objects for the currently loaded shaderpack.
*/
public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener {
public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener, TesrInstancingPipeline, PendingProgramSelection {
private final RenderTargets renderTargets;
@Nullable
@@ -178,8 +184,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final ShaderStorageBufferHolder ssboHolder;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> attributeTransforms;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> instancedAttributeTransforms;
private boolean supportsTesrInstancing = true;
private final EnumMap<Instancing, Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>>> instancedAttributeTransforms = new EnumMap<>(Instancing.class);
private final boolean[] supportsInstancing = initialInstancingSupport();
private final ParityFlipState parityState = new ParityFlipState(AngelicaConfig.shaderParityFlip);
private final Supplier<ImmutableSet<Integer>> flippedGbuffers;
private final Supplier<ImmutableSet<Integer>> flippedShadowGbuffers;
@@ -214,7 +220,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean worldGroupActive = false;
private boolean isBeforeTranslucent;
private boolean isRenderingShadow = false;
private InputAvailability inputs = new InputAvailability(false, false);
private InputAvailability inputs = InputAvailability.of(false, false);
private SpecialCondition special = null;
private boolean shouldBindPBR;
@@ -254,8 +260,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
.orElse(null);
resolver = new ProgramFallbackResolver(programs);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver, ProgramId.values(), false);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> instancedTransformFutures = submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true);
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver, attributeProgramIds(Instancing.NONE), Instancing.NONE, mvBuiltinsMemo);
final EnumMap<Instancing, Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>> instancedTransformFutures = new EnumMap<>(Instancing.class);
for (Instancing kind : Instancing.VALUES) {
if (kind != Instancing.NONE) {
instancedTransformFutures.put(kind, submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo));
}
}
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> terrainSolidOverride = programs.getGbuffersTerrainSolid();
@@ -506,17 +518,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
Iris.logger.info("[Load #{}] DWRP phase=attribute-join elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0));
_tLast = System.nanoTime();
this.instancedAttributeTransforms = new HashMap<>();
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : instancedTransformFutures.entrySet()) {
try {
final Map<PatchShaderType, String> transformed = entry.getValue().join();
if (transformed == null) continue;
this.instancedAttributeTransforms.put(entry.getKey(), transformed);
} catch (Exception e) {
Iris.logger.warn("Instanced transform failed for {}; disabling TESR instancing", entry.getKey().getLeft(), e);
supportsTesrInstancing = false;
instancedAttributeTransforms.clear();
break;
for (Map.Entry<Instancing, Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>> kindEntry : instancedTransformFutures.entrySet()) {
final Instancing kind = kindEntry.getKey();
final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> joined = new HashMap<>();
this.instancedAttributeTransforms.put(kind, joined);
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : kindEntry.getValue().entrySet()) {
try {
final Map<PatchShaderType, String> transformed = entry.getValue().join();
if (transformed == null) continue;
joined.put(entry.getKey(), transformed);
} catch (Exception e) {
Iris.logger.warn("{} instanced transform failed for {}; disabling it", kind, entry.getKey().getLeft(), e);
supportsInstancing[kind.ordinal()] = false;
joined.clear();
break;
}
}
}
@@ -594,10 +610,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null),
programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer,
() -> usesSampler(IrisSamplers.USAGE_SHADOWTEX1));
Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram();
Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, new InputAvailability(true, true)).getProgram();
shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0)
|| (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0));
Program shadowProgram = table.match(RenderCondition.SHADOW, InputAvailability.of(true, true)).getProgram();
Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, InputAvailability.of(true, true)).getProgram();
shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0) || (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0));
shadowRenderer.setPlayerReflectionCaptureEnabled((shadowProgram != null && GLStateManager.glGetUniformLocation(shadowProgram.getProgramId(), "playerAtlas_img") != -1) || (shadowWaterProgram != null && GLStateManager.glGetUniformLocation(shadowWaterProgram.getProgramId(), "playerAtlas_img") != -1));
} else {
shadowRenderer = null;
@@ -644,7 +659,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
@@ -679,7 +694,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flippedAfterPrepareResolved, renderTargets, false, this);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
// Bind custom images as samplers (for texture() access to voxel_sampler, floodfill_sampler, etc.)
@@ -926,6 +941,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
current = null;
currentCondition = null;
clearPendingSelection();
}
public void restorePassAfterModProgram(int newProgram) {
@@ -966,7 +982,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
matchingBlend = true;
try {
matchPass();
requestMatch();
} finally {
matchingBlend = false;
}
@@ -974,7 +990,30 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean matchingBlend;
private void requestMatch() {
if (GLStateManager.isForeignDraw() || BatchEligibility.batchingAllowed()) {
GLSMHooks.pendingProgramSelection = this;
return;
}
matchPass();
}
@Override
public void resolvePendingProgram() {
if (GLSMHooks.pendingProgramSelection == this && !GLStateManager.isForeignDraw()) {
matchPass();
}
}
private void clearPendingSelection() {
if (GLSMHooks.pendingProgramSelection == this) {
GLSMHooks.pendingProgramSelection = null;
}
}
private void matchPass() {
clearPendingSelection();
if (!shouldOverrideShaders()) {
return;
}
@@ -989,6 +1028,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void onEntityRenderBoundary() {
GLSMHooks.resolvePendingProgram();
if (!shouldOverrideShaders()) {
return;
}
@@ -1026,6 +1067,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void rebindCurrentPass() {
GLSMHooks.resolvePendingProgram();
final Pass pass = this.current;
if (pass == null) {
if (GLStateManager.getActiveProgram() == 0) {
@@ -1147,11 +1189,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
framebufferAfterTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, programDirectives.getDrawBuffers());
}
builder.bindAttributeLocation(11, "mc_Entity");
builder.bindAttributeLocation(12, "mc_midTexCoord");
builder.bindAttributeLocation(13, "at_tangent");
builder.bindAttributeLocation(14, "at_midBlock");
AlphaTestOverride alphaTestOverride = programDirectives.getAlphaTestOverride()
.orElse(id.getDefaultAlphaTestOverride());
@@ -1186,7 +1223,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor);
}
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(hasTexture, hasLightmap));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(hasTexture, hasLightmap));
if (!isShadowPass) {
recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets));
}
@@ -1301,8 +1338,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private String instancingSourceName;
private InputAvailability instancingAvailability;
private boolean instancingShadow;
@Nullable private Program instancedVariant;
private boolean instancedVariantAttempted;
private final Program[] instancedVariants = new Program[Instancing.VALUES.length];
private final boolean[] instancedVariantAttempted = new boolean[Instancing.VALUES.length];
private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents,
@Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List<BufferBlendOverride> bufferBlendOverrides, boolean shadowViewport) {
@@ -1382,64 +1419,77 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
@Nullable
Program getInstancedVariant() {
if (!instancedVariantAttempted) {
instancedVariantAttempted = true;
if (instancingSourceName != null && supportsTesrInstancing) {
instancedVariant = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow);
Program instancedVariant(Instancing kind) {
final int i = kind.ordinal();
if (!instancedVariantAttempted[i]) {
instancedVariantAttempted[i] = true;
if (instancingSourceName != null && supportsInstancing[i]) {
instancedVariants[i] = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow, kind);
}
}
return instancedVariant;
return instancedVariants[i];
}
public void destroy() {
if (this.program != null) {
this.program.destroy();
}
if (this.instancedVariant != null) {
this.instancedVariant.destroy();
this.instancedVariant = null;
for (int i = 0; i < instancedVariants.length; i++) {
if (instancedVariants[i] != null) {
instancedVariants[i].destroy();
instancedVariants[i] = null;
}
}
}
}
@Nullable
private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow) {
final Map<PatchShaderType, String> transformed = instancedAttributeTransforms.get(Pair.of(sourceName, availability));
private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow, Instancing kind) {
final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> transforms = instancedAttributeTransforms.get(kind);
final Map<PatchShaderType, String> transformed = transforms != null ? transforms.get(Pair.of(sourceName, availability)) : null;
if (transformed == null) {
return null;
}
try {
final ProgramBuilder builder = beginBuilder(sourceName + "_instanced", transformed);
final ProgramBuilder builder = beginBuilder(sourceName + kind.variantSuffix, transformed);
wireGbufferProgram(builder, availability, shadow);
final Program variant = builder.build();
this.customUniforms.mapholderToPass(builder, variant);
return variant;
} catch (Exception e) {
Iris.logger.warn("TESR instanced variant link failed for {}; disabling TESR instancing", sourceName, e);
supportsTesrInstancing = false;
Iris.logger.warn("{} instanced variant link failed for {}; disabling it", kind, sourceName, e);
supportsInstancing[kind.ordinal()] = false;
return null;
}
}
public boolean supportsTesrInstancing() {
return supportsTesrInstancing;
static boolean[] initialInstancingSupport() {
final boolean[] out = new boolean[Instancing.VALUES.length];
out[Instancing.TEMPLATE.ordinal()] = true;
out[Instancing.CUBE.ordinal()] = AngelicaConfig.cubeInstancingEnabled();
out[Instancing.PARTICLE.ordinal()] = true;
return out;
}
public boolean hasTesrInstancedVariant() {
final Pass pass = current;
return pass != null && pass.getInstancedVariant() != null;
public boolean supportsInstancing(Instancing kind) {
return supportsInstancing[kind.ordinal()];
}
public void bindTesrInstancedVariant() {
final Pass pass = current;
final Program variant = pass.getInstancedVariant();
@Override
public boolean hasInstancedVariant(Instancing kind) {
return current != null && current.instancedVariant(kind) != null;
}
@Override
public void bindInstancedVariant(Instancing kind) {
final Program variant = current.instancedVariant(kind);
variant.use();
this.customUniforms.push(variant);
}
@Override
public void destroy() {
clearPendingSelection();
DepthColorStorage.unlockDepthColor();
BlendModeOverride.restore();
AlphaTestOverride.restore();
@@ -1683,7 +1733,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
@@ -1761,7 +1811,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
@@ -2141,7 +2191,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
public void setOverridePhase(WorldRenderingPhase phase) {
this.overridePhase = phase;
syncPhaseDebugGroup();
matchPass();
requestMatch();
GbufferPrograms.runPhaseChangeNotifier();
}
@@ -2149,7 +2199,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
public void setPhase(WorldRenderingPhase phase) {
this.phase = phase;
syncPhaseDebugGroup();
matchPass();
requestMatch();
GbufferPrograms.runPhaseChangeNotifier();
}
@@ -2179,19 +2229,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void setInputs(InputAvailability availability) {
this.inputs = availability;
matchPass();
requestMatch();
}
@Override
public void setSpecialCondition(SpecialCondition special) {
this.special = special;
matchPass();
requestMatch();
}
@Override
public void setDeclaredTranslucency(@Nullable Boolean translucent) {
this.declaredTranslucent = translucent;
matchPass();
requestMatch();
}
@Nullable
@@ -2229,12 +2279,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
private static final InputAvailability INPUT_NONE = new InputAvailability(false, false);
private static final InputAvailability INPUT_LIGHTMAP_ONLY = new InputAvailability(false, true);
private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false);
private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true);
private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_LIGHTMAP_ONLY, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP };
private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source, TextureStage stage,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(
@@ -2264,10 +2308,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
private static Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>
submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, boolean instanced) {
submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, Instancing instancing, Map<String, Boolean> mvBuiltinsMemo) {
if (instancing == Instancing.CUBE && !AngelicaConfig.cubeInstancingEnabled()) {
return Collections.emptyMap();
}
final boolean instanced = instancing != Instancing.NONE;
final boolean matrixInstanced = instancing.hasInstanceHead();
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>();
final Set<String> processedSourceNames = new HashSet<>();
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
for (ProgramId id : ids) {
if (id.getGroup() == ProgramGroup.Dh) continue;
final ProgramSource source = resolver.resolveNullable(id);
@@ -2276,9 +2324,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
final String vertexSource = source.getVertexSource().orElse(null);
final boolean scrollGlint = GlintScrollInjector.shouldInject(id, source);
for (InputAvailability avail : INPUT_AVAILABILITIES) {
for (InputAvailability avail : InputAvailability.VALUES) {
futures.put(Pair.of(source.getName(), avail), Iris.ShaderTransformExecutor.submitTracked(() -> {
if (instanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> {
if (matrixInstanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> {
final boolean references = referencesMvBuiltinsOutsideVertex(source);
if (references) {
Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", k);
@@ -2291,7 +2339,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final String tessControl = source.getTessControlSource().orElse(null);
final String tessEval = source.getTessEvalSource().orElse(null);
final String fragment = source.getFragmentSource().orElse(null);
return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint)
return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint, instancing)
: TransformPatcher.patchAttributes(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint);
}));
}
@@ -2301,9 +2349,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private static final ProgramId[] INSTANCED_PROGRAM_IDS = {
ProgramId.Block, ProgramId.BlockTrans, ProgramId.Entities, ProgramId.EntitiesTrans,
ProgramId.Shadow, ProgramId.ShadowWater
ProgramId.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint
};
private static final ProgramId[] PARTICLE_PROGRAM_IDS = {
ProgramId.Particles, ProgramId.ParticlesTrans
};
private static ProgramId[] attributeProgramIds(Instancing kind) {
return switch (kind) {
case NONE -> ProgramId.values();
case TEMPLATE, CUBE -> INSTANCED_PROGRAM_IDS;
case PARTICLE -> PARTICLE_PROGRAM_IDS;
};
}
private static final String[] MV_BUILTINS = {
"gl_ModelViewMatrix", "gl_ModelViewMatrixInverse",
"gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixInverse",
@@ -2371,8 +2431,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
.ifPresent(source -> submitCompositeTransform(source, TextureStage.COMPOSITE_AND_FINAL, tm));
final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
submitAttributeTransforms(resolver, ProgramId.values(), false);
submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true);
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
for (Instancing kind : Instancing.VALUES) {
submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo);
}
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
@@ -1,6 +1,10 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
@@ -30,27 +34,37 @@ class AttributeTransformer {
}
private static void transformCore(Transformer transformer, AttributeParameters parameters) {
final boolean instancedVertex = parameters.instanced && parameters.type == ShaderType.VERTEX;
final boolean wantsMvInverse = instancedVertex && transformer.containsCall("gl_ModelViewMatrixInverse");
CoreTransformHelper.injectMatrixUniforms(transformer, instancedVertex);
final boolean vertex = parameters.type == ShaderType.VERTEX;
final boolean instancedVertex = vertex && parameters.instancing != Instancing.NONE;
final boolean cubeVertex = vertex && parameters.instancing == Instancing.CUBE;
final boolean particleVertex = vertex && parameters.instancing == Instancing.PARTICLE;
final boolean matrixVertex = vertex && parameters.instancing.hasInstanceHead();
final boolean wantsMvInverse = matrixVertex && transformer.containsCall("gl_ModelViewMatrixInverse");
CoreTransformHelper.injectMatrixUniforms(transformer, vertex ? parameters.instancing : Instancing.NONE);
aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix");
aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix");
aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix");
if (parameters.type == ShaderType.VERTEX) {
transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;");
transformer.injectVariable("layout(location = 1) in vec4 iris_Color;");
transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;");
if (instancedVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
} else {
transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;");
if (!particleVertex) {
transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;");
transformer.injectVariable("layout(location = 1) in vec4 iris_Color;");
if (cubeVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord0;");
} else {
transformer.injectVariable("layout(location = " + PRIMARY_UV + ") in vec4 iris_MultiTexCoord0;");
}
if (instancedVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
} else {
transformer.injectVariable("layout(location = " + SECONDARY_UV + ") in vec4 iris_MultiTexCoord1;");
}
}
transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;");
transformer.rename("gl_Vertex", "iris_Vertex");
transformer.replaceExpression("gl_Color", instancedVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)");
transformer.replaceExpression("gl_Color", matrixVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)");
transformer.rename("gl_Normal", "iris_Normal");
aliasIfUsed(transformer, "vaNormal", "iris_Normal");
if (transformer.containsCall("vaPosition") && !transformer.hasVariable("vaPosition")) {
@@ -88,18 +102,83 @@ class AttributeTransformer {
if (instancedVertex) {
foldConstantAttribute(transformer, "mc_Entity", "-1.0", "vec2(-1.0, -1.0)", "vec3(-1.0, -1.0, 0.0)", "vec4(-1.0, -1.0, 0.0, 1.0)");
final StringBuilder init = new StringBuilder(256);
init.append("{ iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3);");
init.append(" iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz));");
if (wantsMvInverse) {
init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);");
final StringBuilder init = new StringBuilder(256).append("{ ");
if (particleVertex) {
init.append("iris_Vertex = ").append(InstancedGlslHelpers.particlePos("iris_InstCenterHalf", "iris_ParticleOffset")).append(';');
init.append(" iris_Color = iris_InstColor;");
init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.particleUv("iris_InstUv", "iris_ParticleCorner")).append(';');
init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0);");
assignMidTexCoord(transformer, init, "vec4((iris_InstUv.x + iris_InstUv.z) * 0.5, (iris_InstUv.y + iris_InstUv.w) * 0.5, 0.0, 1.0)");
} else {
init.append("iris_ModelViewMatrix = ").append(InstancedGlslHelpers.mat4FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';');
init.append(" iris_NormalMatrix = ").append(InstancedGlslHelpers.mat3FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';');
if (wantsMvInverse) {
init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);");
}
init.append(" iris_MultiTexCoord1 = vec4(").append(cubeVertex ? "iris_InstLightmapScale.xy" : "iris_InstLightmap").append(", 0.0, 1.0);");
if (cubeVertex) {
appendCubeTexCoords(transformer, init);
}
}
init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0); }");
init.append(" }");
transformer.prependMain(init.toString());
}
}
}
private static final int PRIMARY_UV = VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation();
private static final int SECONDARY_UV = VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation();
private static void appendCubeTexCoords(Transformer transformer, StringBuilder init) {
init.append(' ').append(InstancedGlslHelpers.cubePrelude("iris_", "iris_CubeMid", "iris_CubeDelta", "iris_Normal", "iris_CubeTex", " "));
init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeU.x", "iris_cubeU.y", "iris_cubeV.x", "iris_cubeV.y")).append(';');
final int tangentType = transformer.findType("at_tangent");
if (tangentType != 0) {
final String name = vecName(tangentType);
if (name == null || tangentType == GLSLLexer.VEC2) {
throw new IllegalStateException("Unsupported at_tangent type token " + tangentType + " for the cube instanced variant");
}
transformer.removeVariable("at_tangent");
transformer.injectVariable("layout(location = " + ProgramCreator.AT_TANGENT + ") in vec4 iris_CubeTangent;");
transformer.injectVariable(name + " at_tangent;");
init.append(" at_tangent = (iris_CubeTangent * (1.0 - 2.0 * iris_cubeMirror))").append(swizzle(tangentType)).append(';');
}
assignMidTexCoord(transformer, init, InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeMidU.x", "iris_cubeMidU.y", "iris_CubeMid.z", "iris_CubeMid.w"));
}
private static void assignMidTexCoord(Transformer transformer, StringBuilder init, String midExpression) {
final int midType = transformer.findType("mc_midTexCoord");
if (midType == 0) {
return;
}
final String name = vecName(midType);
if (name == null) {
throw new IllegalStateException("Unsupported mc_midTexCoord type token " + midType + " for the instanced variant");
}
transformer.removeVariable("mc_midTexCoord");
transformer.injectVariable(name + " mc_midTexCoord;");
init.append(" mc_midTexCoord = (").append(midExpression).append(')').append(swizzle(midType)).append(';');
}
private static String vecName(int type) {
return switch (type) {
case GLSLLexer.VEC2 -> "vec2";
case GLSLLexer.VEC3 -> "vec3";
case GLSLLexer.VEC4 -> "vec4";
default -> null;
};
}
private static String swizzle(int type) {
return switch (type) {
case GLSLLexer.VEC2 -> ".xy";
case GLSLLexer.VEC3 -> ".xyz";
default -> "";
};
}
private static void foldConstantAttribute(Transformer transformer, String name, String floatVal, String vec2Val, String vec3Val, String vec4Val) {
final int type = transformer.findType(name);
if (type == 0) {
@@ -1,6 +1,8 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
@@ -16,24 +18,37 @@ class CoreTransformHelper {
* Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix.
*/
static void injectMatrixUniforms(Transformer transformer) {
injectMatrixUniforms(transformer, false);
injectMatrixUniforms(transformer, Instancing.NONE);
}
static void injectMatrixUniforms(Transformer transformer, boolean instancedVertex) {
if (instancedVertex) {
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL0 + ") in vec4 iris_InstMat0;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL1 + ") in vec4 iris_InstMat1;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL2 + ") in vec4 iris_InstMat2;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL3 + ") in vec4 iris_InstMat3;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_COLOR + ") in vec4 iris_InstColor;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_LIGHTMAP + ") in vec2 iris_InstLightmap;");
transformer.injectVariable("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
} else {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
static void injectMatrixUniforms(Transformer transformer, Instancing instancing) {
switch (instancing) {
case PARTICLE -> {
transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.POSITION.getAttributeLocation() + ") in vec3 iris_ParticleOffset;");
transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation() + ") in vec2 iris_ParticleCorner;");
injectAttributeDecls(transformer, instancing);
transformer.injectVariable("vec4 iris_Vertex;");
transformer.injectVariable("vec4 iris_Color;");
transformer.injectVariable("vec4 iris_MultiTexCoord0;");
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
}
case TEMPLATE, CUBE -> {
injectAttributeDecls(transformer, instancing);
transformer.injectVariable("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
if (!declaresInvariantPosition(transformer)) {
transformer.injectVariable("invariant gl_Position;");
}
}
case NONE -> {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
}
}
transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;");
@@ -58,6 +73,25 @@ class CoreTransformHelper {
transformer.replaceExpression("gl_TextureMatrix", "mat4[8](iris_TextureMatrix, iris_LightmapTextureMatrix, mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0))");
}
private static void injectAttributeDecls(Transformer transformer, Instancing instancing) {
for (String decl : InstancedGlslHelpers.attributeDecls("iris_", instancing)) {
transformer.injectVariable(decl);
}
}
private static boolean declaresInvariantPosition(Transformer transformer) {
final boolean[] found = new boolean[1];
transformer.mutateTree(root -> {
for (int i = 0; i < root.getChildCount(); i++) {
if ("invariantgl_Position;".equals(root.getChild(i).getText())) {
found[0] = true;
return;
}
}
});
return found[0];
}
/**
* Inject vertex attributes and ftransform() replacement for composite/depth shaders. Uses locations matching FullScreenQuadRenderer's POSITION_TEXTURE VAO layout.
*/
@@ -1,18 +1,120 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLParser;
class EntityPatcher {
public static void patchEntityId(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
if (!hasInstanceAttributes(parameters)) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
return;
}
removeIfDeclared(transformer, "entityId");
removeIfDeclared(transformer, "blockEntityId");
removeIfDeclared(transformer, "currentRenderedItemId");
final String geometryIn = parameters.hasTesselation ? "iris_entityInfoTES" : "iris_entityInfo";
final String info = switch (parameters.type) {
case GEOMETRY -> geometryIn + "[0]";
case TESSELATION_CONTROL -> "iris_entityInfo[gl_InvocationID]";
case TESSELATION_EVAL -> "iris_entityInfoTCS[0]";
default -> "iris_entityInfo";
};
transformer.replaceExpression("entityId", info + ".x", GLSLParser::postfix_expression);
transformer.replaceExpression("blockEntityId", info + ".y", GLSLParser::postfix_expression);
transformer.replaceExpression("currentRenderedItemId", info + ".z", GLSLParser::postfix_expression);
switch (parameters.type) {
case VERTEX -> {
if (!transformer.hasVariable("iris_Entity")) {
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_ENTITY + ") in ivec4 iris_Entity;");
}
transformer.injectVariable("flat out ivec3 iris_entityInfo;");
transformer.prependMain("iris_entityInfo = iris_Entity.xyz;");
}
case TESSELATION_CONTROL -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoTCS[];");
transformer.injectVariable("flat in ivec3 iris_entityInfo[];");
transformer.prependMain("iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];");
}
case TESSELATION_EVAL -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoTES;");
transformer.injectVariable("flat in ivec3 iris_entityInfoTCS[];");
transformer.prependMain("iris_entityInfoTES = iris_entityInfoTCS[0];");
}
case GEOMETRY -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoGS;");
transformer.injectVariable("flat in ivec3 " + geometryIn + "[];");
transformer.prependMain("iris_entityInfoGS = " + geometryIn + "[0];");
}
case FRAGMENT -> {
if (transformer.containsCall("iris_entityInfo")) {
transformer.injectVariable("flat in ivec3 iris_entityInfo;");
if (parameters.hasGeometry) {
transformer.rename("iris_entityInfo", "iris_entityInfoGS");
} else if (parameters.hasTesselation) {
transformer.rename("iris_entityInfo", "iris_entityInfoTES");
}
}
}
default -> {}
}
}
public static void patchOverlayColor(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
if (!hasInstanceAttributes(parameters)) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
return;
}
removeIfDeclared(transformer, "entityColor");
switch (parameters.type) {
case VERTEX -> {
transformer.injectVariable("out vec4 entityColor;");
transformer.prependMain("{ entityColor = iris_InstOverlay; entityColor.rgb *= float(entityColor.a != 0.0); }");
}
case TESSELATION_CONTROL -> {
transformer.replaceExpression("entityColor", "entityColor[gl_InvocationID]", GLSLParser::postfix_expression);
transformer.injectVariable("patch out vec4 entityColorTCS;");
transformer.injectVariable("in vec4 entityColor[];");
transformer.prependMain("entityColorTCS = entityColor[gl_InvocationID];");
}
case TESSELATION_EVAL -> {
transformer.replaceExpression("entityColor", "entityColorTCS", GLSLParser::postfix_expression);
transformer.injectVariable("out vec4 entityColorTES;");
transformer.injectVariable("patch in vec4 entityColorTCS;");
transformer.prependMain("entityColorTES = entityColorTCS;");
}
case GEOMETRY -> {
final String geometryIn = parameters.hasTesselation ? "entityColorTES" : "entityColor";
transformer.replaceExpression("entityColor", geometryIn + "[0]", GLSLParser::postfix_expression);
transformer.injectVariable("out vec4 entityColorGS;");
transformer.injectVariable("in vec4 " + geometryIn + "[];");
transformer.prependMain("entityColorGS = " + geometryIn + "[0];");
}
case FRAGMENT -> {
if (transformer.containsCall("entityColor")) {
transformer.injectVariable("in vec4 entityColor;");
if (parameters.hasGeometry) {
transformer.rename("entityColor", "entityColorGS");
} else if (parameters.hasTesselation) {
transformer.rename("entityColor", "entityColorTES");
}
}
}
default -> {}
}
}
private static boolean hasInstanceAttributes(AttributeParameters parameters) {
return parameters.instancing.hasInstanceHead();
}
private static void injectUniformIfUndeclared(Transformer transformer, String name, String declaration) {
@@ -20,4 +122,10 @@ class EntityPatcher {
transformer.injectVariable(declaration);
}
}
private static void removeIfDeclared(Transformer transformer, String name) {
if (transformer.hasVariable(name)) {
transformer.removeVariable(name);
}
}
}
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.EnumMap;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
@@ -138,11 +139,11 @@ public class TransformPatcher {
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint));
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, Instancing.NONE));
}
public static Map<PatchShaderType, String> patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint, true));
public static Map<PatchShaderType, String> patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint, Instancing instancing) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, instancing));
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) {
@@ -1,26 +1,25 @@
package net.coderbot.iris.pipeline.transform.parameter;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class AttributeParameters extends Parameters {
public final boolean hasGeometry;
public final boolean hasTesselation;
public final InputAvailability inputs;
public final boolean scrollGlint;
public final boolean instanced;
public final Instancing instancing;
// WARNING: adding new fields requires updating hashCode and equals methods!
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint) {
this(patch, hasGeometry, inputs, scrollGlint, false);
}
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint, boolean instanced) {
public AttributeParameters(Patch patch, boolean hasGeometry, boolean hasTesselation, InputAvailability inputs, boolean scrollGlint, Instancing instancing) {
super(patch, null);
this.hasGeometry = hasGeometry;
this.hasTesselation = hasTesselation;
this.inputs = inputs;
this.scrollGlint = scrollGlint;
this.instanced = instanced;
this.instancing = instancing;
}
@Override
@@ -33,8 +32,9 @@ public class AttributeParameters extends Parameters {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + (hasTesselation ? 1231 : 1237);
result = prime * result + (scrollGlint ? 1231 : 1237);
result = prime * result + (instanced ? 1231 : 1237);
result = prime * result + instancing.ordinal();
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@@ -50,9 +50,11 @@ public class AttributeParameters extends Parameters {
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (hasTesselation != other.hasTesselation)
return false;
if (scrollGlint != other.scrollGlint)
return false;
if (instanced != other.instanced)
if (instancing != other.instancing)
return false;
if (inputs == null) {
if (other.inputs != null)