diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ExitStateCapture.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ExitStateCapture.java index 053670c21..ff64e1b26 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ExitStateCapture.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ExitStateCapture.java @@ -226,13 +226,10 @@ final class ExitStateCapture { void requireDrawState(boolean materialFromState) { if (!active()) return; - long fields = DRAW_INPUTS; - if (materialFromState) { - fields |= MATERIAL_INPUTS; - if (!context.blendMode.isEffectivelyEnabled()) fields &= ~(1L << BLEND_FUNC); - if (!context.alphaTest.isEffectivelyEnabled()) fields &= ~(1L << ALPHA_FUNC); - } - result.dependencies |= fields & ~result.writes; + long fields = (materialFromState ? DRAW_INPUTS | MATERIAL_INPUTS : DRAW_INPUTS) & ~(result.writes | result.dependencies); + if ((fields & (1L << BLEND_FUNC)) != 0 && !context.blendMode.isEffectivelyEnabled()) fields &= ~(1L << BLEND_FUNC); + if ((fields & (1L << ALPHA_FUNC)) != 0 && !context.alphaTest.isEffectivelyEnabled()) fields &= ~(1L << ALPHA_FUNC); + result.dependencies |= fields; if (textureInherited) result.dependencies |= 1L << TEXTURE_MATRIX; } @@ -304,7 +301,7 @@ final class ExitStateCapture { } void requireTextureFilter(int texture, boolean nearest) { - if (active() && filterTexture != 0 && texture == filterTexture && !nearest) reject(); + if (filterTexture != 0 && texture == filterTexture && !nearest && active()) reject(); } private boolean savedFilterDiffers() { @@ -425,7 +422,9 @@ final class ExitStateCapture { } void matrixChange(boolean absolute) { - if (active()) recordMatrixChange(context.matrixMode.getMode(), context.activeTextureUnit.getValue(), absolute); + if (result == null) return; + final int mode = context.matrixMode.getMode(); + if ((absolute || mode != GL11.GL_MODELVIEW) && active()) recordMatrixChange(mode, context.activeTextureUnit.getValue(), absolute); } void matrixChange(int mode, int unit, boolean absolute) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index f22384910..f7cd22218 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -165,8 +165,12 @@ public class GLStateManager { public static boolean canApplyExitState(ExitState result) { return ctx().exitCapture.canApply(result); } public static void applyExitState(ExitState result) { ctx().exitCapture.apply(result); } public static void cancelExitCapture() { ctx().exitCapture.cancel(); } - public static void suspendExitCapture() { ctx().exitCapture.suspend(); } - public static void resumeExitCapture() { ctx().exitCapture.resume(); } + public static boolean suspendExitCapture() { + if (!ExitStateCapture.anyOpen()) return false; + ctx().exitCapture.suspend(); + return true; + } + public static void resumeExitCapture(boolean suspended) { if (suspended) ctx().exitCapture.resume(); } public static boolean isExitCaptureActive() { return ExitStateCapture.anyOpen() && ctx().exitCapture.active(); } public static void requireExitDrawState(boolean materialFromState) { if (ExitStateCapture.anyOpen()) ctx().exitCapture.requireDrawState(materialFromState); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ExitState_GLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ExitState_GLTest.java index 66dd9bfe8..278819366 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ExitState_GLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_ExitState_GLTest.java @@ -351,7 +351,7 @@ class GLSM_ExitState_GLTest { void suspendedCallsAreNeitherRecordedNorRejected() { final ExitState state = new ExitState(); GLStateManager.beginExitCapture(state); - GLStateManager.suspendExitCapture(); + final boolean suspended = GLStateManager.suspendExitCapture(); try { assertFalse(GLStateManager.isExitCaptureActive()); GLStateManager.glIsEnabled(GL11.GL_CULL_FACE); @@ -363,7 +363,7 @@ class GLSM_ExitState_GLTest { BatchStateGuard.resume(); } } finally { - GLStateManager.resumeExitCapture(); + GLStateManager.resumeExitCapture(suspended); } BatchStateGuard.suspend(); try { @@ -391,11 +391,11 @@ class GLSM_ExitState_GLTest { GLStateManager.glColor4f(0.25F, 1, 1, 1); final ExitState state = new ExitState(); GLStateManager.beginExitCapture(state); - GLStateManager.suspendExitCapture(); + final boolean suspended = GLStateManager.suspendExitCapture(); try { GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT); } finally { - GLStateManager.resumeExitCapture(); + GLStateManager.resumeExitCapture(suspended); } GLStateManager.glColor4f(0, 0, 0, 1); GLStateManager.glPopAttrib(); @@ -413,11 +413,11 @@ class GLSM_ExitState_GLTest { GLStateManager.beginExitCapture(state); GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT); GLStateManager.glColor4f(0, 0, 0, 1); - GLStateManager.suspendExitCapture(); + final boolean suspended = GLStateManager.suspendExitCapture(); try { GLStateManager.glPopAttrib(); } finally { - GLStateManager.resumeExitCapture(); + GLStateManager.resumeExitCapture(suspended); } assertTrue(GLStateManager.finishExitCapture(state)); diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java index 88dffabcb..e27610f6b 100644 --- a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java @@ -179,6 +179,10 @@ public final class FfpFixture { } public static void assertPixelParity(String subject, int[] reference, int[] candidate, int size, int background, int minCoverageDivisor, int channelTolerance, IntFunction describe) { + assertPixelParity(subject, reference, candidate, size, background, minCoverageDivisor, channelTolerance, 0, describe); + } + + public static void assertPixelParity(String subject, int[] reference, int[] candidate, int size, int background, int minCoverageDivisor, int channelTolerance, int allowedMismatches, IntFunction describe) { int covered = 0; for (int pixel : reference) { if (pixel != background) covered++; @@ -196,7 +200,7 @@ public final class FfpFixture { } final int index = firstMismatch; final int differing = mismatches; - assertEquals(0, mismatches, () -> subject + " differ from baked quads in " + differing + " of " + reference.length + " pixels, first at (" + (index % size) + "," + (index / size) + "): reference " + describe.apply(reference[index]) + " instanced " + describe.apply(candidate[index])); + assertTrue(mismatches <= allowedMismatches, () -> subject + " differ from baked quads in " + differing + " of " + reference.length + " pixels, first at (" + (index % size) + "," + (index / size) + "): reference " + describe.apply(reference[index]) + " instanced " + describe.apply(candidate[index])); } private static boolean withinTolerance(int a, int b, int tolerance) { diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java index acbdd5359..623f91631 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -15,6 +15,7 @@ import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader; import com.gtnewhorizons.angelica.hudcaching.HUDCaching; import com.gtnewhorizons.angelica.rendering.tesr.BatchDrawDefaults; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -1251,6 +1252,7 @@ public class BatchingFontRenderer { if (string == null || string.length() == 0) { return anchorX + (enableShadow ? 1.0f : 0.0f); } + EntityShadowReplay.rejectForeignDraw(); final int color = buttonSectionActive ? DarkModeUtils.recolorButtonText(inputColor, buttonEnabledColor, buttonHoveredColor, buttonDisabledColor) : inputColor; diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 3a218a97a..0d366542f 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -167,6 +167,20 @@ public class AngelicaConfig { @Config.DefaultBoolean(true) public static boolean enableEntityTextureAtlas; + @Config.Comment("Replay entity draws recorded in the shader shadow pass in the main view instead of running each entity renderer again (experimental, requires entity batching)") + @Config.DefaultBoolean(false) + @Config.RequiresMcRestart + public static boolean enableEntityShadowReplay; + + @Config.Comment("Entity classes that run their renderer again in the main view instead of replaying shadow pass draws. Players are always excluded.") + @Config.DefaultStringList({ + "chylex.hee.entity.boss.EntityBossDragon", + "twilightforest.entity.passive.EntityTFMobileFirefly", + "gregtech.common.entity.EntityDrone" + }) + @Config.RequiresMcRestart + public static String[] entityShadowReplayExcludedClasses; + @Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.") @Config.DefaultBoolean(true) @Config.RequiresMcRestart @@ -548,6 +562,10 @@ public class AngelicaConfig { return enableEntityBatching && enableCubeInstancing; } + public static boolean entityShadowReplayEnabled() { + return enableEntityBatching && enableEntityShadowReplay; + } + public static boolean sdlGpuConfigured() { return renderBackend == RenderBackendChoice.SDL_GPU; } diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java index edf88b0c5..554cb1c2c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java @@ -67,8 +67,15 @@ public class IrisGLSMBridge { public static void installImmediateExtendedHandler() { GLSMHooks.immediateExtendedHandler = new ImmediateExtendedAttribs(); final CapturedRenderingState state = CapturedRenderingState.INSTANCE; - state.setEntityIdsListener(() -> GLStateManager.setEntityIds( - state.getCurrentRenderedEntity(), state.getCurrentRenderedBlockEntity(), state.getCurrentRenderedItem())); + state.setEntityIdsListener(() -> { + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + GLStateManager.setEntityIds( + state.getCurrentRenderedEntity(), state.getCurrentRenderedBlockEntity(), state.getCurrentRenderedItem()); + } finally { + GLStateManager.resumeExitCapture(suspended); + } + }); } public static void installPostTransformHook() { diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 17e03c4fc..dfef4004e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -207,6 +207,15 @@ public enum Mixins implements IMixins { ) ), + ANGELICA_ENTITY_SHADOW_REPLAY(new MixinBuilder("Replay entity draws recorded in the shader shadow pass in the main view instead of running each entity renderer again") + .setPhase(Phase.EARLY) + .setApplyIf(() -> AngelicaConfig.enableIris && AngelicaConfig.entityShadowReplayEnabled()) + .addClientMixins( + "angelica.entity.MixinBossStatus_EntityReplay", + "angelica.entity.MixinRenderGlobal_EntityReplay" + ) + ), + ANGELICA_CUBE_INSTANCING(new MixinBuilder("Capture cuboid parameters so model cubes can be drawn from a shared unit cube") .setPhase(Phase.EARLY) .setApplyIf(AngelicaConfig::cubeInstancingEnabled) diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/DeferredEntityOverlay.java b/src/main/java/com/gtnewhorizons/angelica/rendering/DeferredEntityOverlay.java index 40a47671b..6e32a402a 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/DeferredEntityOverlay.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/DeferredEntityOverlay.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import lombok.Getter; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.uniforms.CapturedRenderingState; @@ -8,6 +9,8 @@ import net.coderbot.iris.uniforms.EntityIdHelper; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.entity.RendererLivingEntity; import net.minecraft.entity.EntityLivingBase; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; @@ -37,6 +40,7 @@ public class DeferredEntityOverlay { private static final List pool = new ArrayList<>(INITIAL_CAPACITY); private static final FloatBuffer MATRIX_BUF = BufferUtils.createFloatBuffer(16); + private static final Matrix4f replayMatrix = new Matrix4f(); // Set by the shouldRenderPass inject, consumed by the doRender WrapOperation. @Getter @@ -68,6 +72,9 @@ public class DeferredEntityOverlay { public static void clearStaleOverlayFlag() { overlayPassActive = false; + pendingShouldRenderPass = null; + pendingRenderer = null; + pendingEntity = null; } /** @@ -76,21 +83,23 @@ public class DeferredEntityOverlay { */ public static void deferRender(float limbSwing, float limbSwingAmount, float ageInTicks, float headYaw, float headPitch, float scale) { - overlayPassActive = false; - DeferredEntry entry = acquireEntry(); entry.set(pendingShouldRenderPass, pendingRenderer, pendingEntity, pendingPartialTick, limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch, scale); - MATRIX_BUF.clear(); - GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, MATRIX_BUF); - MATRIX_BUF.get(entry.matrix); + GLStateManager.getModelViewMatrix().get(entry.matrix); deferred.add(entry); + EntityShadowReplay.recordDeferredOverlay(entry); - pendingShouldRenderPass = null; - pendingRenderer = null; - pendingEntity = null; + clearStaleOverlayFlag(); + } + + public static void queueReplay(DeferredEntry captured, Matrix4fc mainFromShadow) { + final DeferredEntry entry = acquireEntry(); + entry.set(captured); + replayMatrix.set(captured.matrix).mulLocal(mainFromShadow).get(entry.matrix); + deferred.add(entry); } private static DeferredEntry acquireEntry() { @@ -103,9 +112,7 @@ public class DeferredEntityOverlay { private static void recycle() { for (DeferredEntry entry : deferred) { - entry.shouldRenderPass = null; - entry.renderer = null; - entry.entity = null; + entry.clear(); pool.add(entry); } deferred.clear(); @@ -113,7 +120,7 @@ public class DeferredEntityOverlay { public static void clear() { recycle(); - overlayPassActive = false; + clearStaleOverlayFlag(); replaying = false; } @@ -138,7 +145,7 @@ public class DeferredEntityOverlay { // Restore the entity's lightmap coords int brightness = entity.getBrightnessForRender(entry.partialTick); - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, + GLStateManager.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, brightness % 65536, (float) brightness / 65536); // Restore the saved modelview matrix @@ -183,7 +190,7 @@ public class DeferredEntityOverlay { } } - private static class DeferredEntry { + public static final class DeferredEntry { final float[] matrix = new float[16]; ShouldRenderPassFn shouldRenderPass; RendererLivingEntity renderer; @@ -196,6 +203,22 @@ public class DeferredEntityOverlay { float headPitch; float scale; + public void copyFrom(DeferredEntry source) { + set(source); + System.arraycopy(source.matrix, 0, matrix, 0, matrix.length); + } + + public void clear() { + shouldRenderPass = null; + renderer = null; + entity = null; + } + + private void set(DeferredEntry source) { + set(source.shouldRenderPass, source.renderer, source.entity, source.partialTick, + source.limbSwing, source.limbSwingAmount, source.ageInTicks, source.headYaw, source.headPitch, source.scale); + } + void set(ShouldRenderPassFn shouldRenderPass, RendererLivingEntity renderer, EntityLivingBase entity, float partialTick, float limbSwing, float limbSwingAmount, float ageInTicks, diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/SkippedGlintBlock.java b/src/main/java/com/gtnewhorizons/angelica/rendering/SkippedGlintBlock.java index c200a2577..86a93897b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/SkippedGlintBlock.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/SkippedGlintBlock.java @@ -32,22 +32,23 @@ public final class SkippedGlintBlock { } private static void applyExitState(float red, float green, float blue, float alpha, int srcRgb, int dstRgb, int srcAlpha, int dstAlpha, boolean resetTextureMatrix, boolean restoreDepthMask) { + final boolean recording = GLStateManager.isExitCaptureActive(); final Color4 color = GLStateManager.getColor(); - if (color.getRed() != red || color.getGreen() != green || color.getBlue() != blue || color.getAlpha() != alpha) { + if (recording || color.getRed() != red || color.getGreen() != green || color.getBlue() != blue || color.getAlpha() != alpha) { GLStateManager.glColor4f(red, green, blue, alpha); } - if (resetTextureMatrix && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0))) { + if (resetTextureMatrix && (recording || !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)))) { GLStateManager.glMatrixMode(GL11.GL_TEXTURE); GLStateManager.glLoadIdentity(); } - if (GLStateManager.getMatrixMode().getMode() != GL11.GL_MODELVIEW) GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - if (restoreDepthMask && !GLStateManager.isEffectiveDepthMaskEnabled()) GLStateManager.glDepthMask(true); - if (!GLStateManager.getLightingState().isEnabled()) GLStateManager.glEnable(GL11.GL_LIGHTING); + if (recording || GLStateManager.getMatrixMode().getMode() != GL11.GL_MODELVIEW) GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + if (restoreDepthMask && (recording || !GLStateManager.isEffectiveDepthMaskEnabled())) GLStateManager.glDepthMask(true); + if (recording || !GLStateManager.getLightingState().isEnabled()) GLStateManager.glEnable(GL11.GL_LIGHTING); GLStateManager.getEffectiveBlendState(blend); - if (GLStateManager.getBlendState().isFuncUnknown() || blend.getSrcRgb() != srcRgb || blend.getDstRgb() != dstRgb || blend.getSrcAlpha() != srcAlpha || blend.getDstAlpha() != dstAlpha) { + if (recording || GLStateManager.getBlendState().isFuncUnknown() || blend.getSrcRgb() != srcRgb || blend.getDstRgb() != dstRgb || blend.getSrcAlpha() != srcAlpha || blend.getDstAlpha() != dstAlpha) { GLStateManager.tryBlendFuncSeparate(srcRgb, dstRgb, srcAlpha, dstAlpha); } - if (GLStateManager.isEffectiveBlendEnabled()) GLStateManager.glDisable(GL11.GL_BLEND); - if (GLStateManager.getDepthState().getFunc() != GL11.GL_LEQUAL) GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + if (recording || GLStateManager.isEffectiveBlendEnabled()) GLStateManager.glDisable(GL11.GL_BLEND); + if (recording || GLStateManager.getDepthState().getFunc() != GL11.GL_LEQUAL) GLStateManager.glDepthFunc(GL11.GL_LEQUAL); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/items/DroppedItemInstancer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/items/DroppedItemInstancer.java index 3cd0c0ab1..fec4eff21 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/items/DroppedItemInstancer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/items/DroppedItemInstancer.java @@ -13,6 +13,7 @@ import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; import com.gtnewhorizons.angelica.rendering.tesr.EntityMaterials; import com.gtnewhorizons.angelica.rendering.tesr.GlintCapture; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -149,6 +150,7 @@ public final class DroppedItemInstancer { } final boolean allowed = BatchEligibility.batchingAllowed(); if (allowed && ModelPartBatcher.INSTANCE.isShadowPass()) { + EntityShadowReplay.rejectShadowOnly(); BatchEligibility.onPartQueued(); return SKIP; } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java index 9f5e2876d..fa98c986c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java @@ -115,6 +115,7 @@ public final class BatchEligibility { static boolean insideRenderer() { return depth != 0; } static void onUncapturedState() { + EntityShadowReplay.rejectUncapturedState(); if (depth == 0) return; uncapturedState = true; allowed = false; @@ -125,6 +126,7 @@ public final class BatchEligibility { } static void onBail(ModelPartBatcher.BailReason reason) { + EntityShadowReplay.rejectBatcherBail(); if (depth == 0 || !allowed) return; if (reason == ModelPartBatcher.BailReason.INACTIVE) { allowed = false; @@ -138,6 +140,7 @@ public final class BatchEligibility { } public static void onPartFallback(long drawsBefore, long drawsNow) { + EntityShadowReplay.rejectPartFallback(); parts++; if (!allowed) { expectedDraws += drawsNow - drawsBefore; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java index 8e48df613..2abcdc64c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java @@ -44,6 +44,7 @@ public final class EntityMaterials { } static TesrMaterial fromCurrentState(boolean texIdentity) { + GLStateManager.requireExitDrawState(true); final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled(); final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha); final ColorMask colorMask = GLStateManager.getEffectiveColorMask(effectiveColorMask); @@ -58,6 +59,7 @@ public final class EntityMaterials { } public static TesrMaterial itemFromCurrentState(boolean unfilteredAtlas) { + GLStateManager.requireExitDrawState(true); final BlendState blend = GLStateManager.getEffectiveBlendState(effectiveBlend); final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha); return itemFromState(unfilteredAtlas, GLStateManager.isEffectiveBlendEnabled(), blend.getSrcRgb(), blend.getDstRgb(), diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityRenderCommands.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityRenderCommands.java new file mode 100644 index 000000000..a316cd633 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityRenderCommands.java @@ -0,0 +1,387 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.DeferredEntityOverlay; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay.Rejection; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceRange; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.coderbot.iris.layer.PassOverride; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector4fc; + +import java.util.Objects; + +import static com.gtnewhorizons.angelica.rendering.items.ItemGlint.canResetStencil; + +/** + * Ordered, pooled submissions captured before the main entity pass. + */ +final class EntityRenderCommands { + private final ObjectArrayList commands = new ObjectArrayList<>(); + private final Pool models = new Pool<>(Model::new, Model::clear); + private final Pool modelGlints = new Pool<>(ModelGlint::new, ModelGlint::clear); + private final Pool itemGlints = new Pool<>(ItemGlint::new, ItemGlint::clear); + private final Pool streams = new Pool<>(Stream::new, Stream::clear); + private final Pool overlays = new Pool<>(Overlay::new, Overlay::clear); + private final Pool ranges = new Pool<>(InstanceRange::new, InstanceRange::clear); + private final Matrix4f glintPose = new Matrix4f(); + long sharedParts, sharedRanges, streamEntries; + private int mergeStart; + + int size() { + return commands.size(); + } + + int split() { + mergeStart = size(); + return mergeStart; + } + + Model model(int recordStart, InstanceColumns source, RenderLayer layer, DrawInputs inputs, int entityId, boolean cubesInsideTexture, Matrix4fc modelView, Matrix4fc texMatrix) { + if (source != null && size() > recordStart && size() > mergeStart && commands.get(size() - 1) instanceof Model previous) { + if (previous.source == source && previous.sourceVersion == source.version && previous.end == source.size - 1 && previous.shadowLayer == layer && previous.inputs.matches(inputs) && previous.entityId == entityId + && previous.cubesInsideTexture == cubesInsideTexture && previous.glint == null && (texMatrix == null ? !previous.hasTextureMatrix : previous.hasTextureMatrix && previous.textureMatrix.equals(texMatrix))) { + previous.end = source.size; + return null; + } + } + final Model model = models.acquire(); + commands.add(model); + model.inputs.copyFrom(inputs); + model.entityId = entityId; + model.cubesInsideTexture = cubesInsideTexture; + model.hasTextureMatrix = texMatrix != null; + if (texMatrix != null) model.textureMatrix.set(texMatrix); + model.source = source; + model.shadowLayer = layer; + if (source == null) { + model.modelView.set(modelView); + } else { + model.sourceVersion = source.version; + model.start = source.size - 1; + model.end = source.size; + } + return model; + } + + ModelGlint modelGlint(int start, int end, DrawInputs inputs) { + for (int i = start; i < end; i++) { + if (!(commands.get(i) instanceof Model model) || model.cannotAddGlint()) return null; + } + final ModelGlint glint = modelGlints.acquire(); + commands.add(glint); + glint.inputs.copyFrom(inputs); + glint.base = (Model) commands.get(start); + Model previous = null; + for (int i = start; i < end; i++) { + final Model model = (Model) commands.get(i); + addGlint(model, glint, true); + if (previous != null) previous.nextGlintBase = model; + previous = model; + } + return glint; + } + + ItemGlint itemGlint(Matrix4fc modelView, DrawInputs inputs) { + if (!(commands.get(size() - 1) instanceof Model base) || base.cannotAddGlint() || base.drawsCubes() || base.sharedRangeChanged()) return null; + final Matrix4fc pose = base.source != null ? base.source.pose(base.end - 1, glintPose) : base.modelView; + if (!pose.equals(modelView)) return null; + final ItemGlint glint = itemGlints.acquire(); + commands.add(glint); + glint.inputs.copyFrom(inputs); + glint.base = base; + addGlint(base, glint, false); + return glint; + } + + private void addGlint(Model base, Glint glint, boolean reuseUpload) { + base.glint = glint; + base.replayed = ranges.acquire(); + base.replayed.reuseUpload = reuseUpload; + } + + void stream(Matrix4fc modelView, int[] vertices, int vertexCount, int entityId, DrawInputs inputs) { + final Stream stream = streams.acquire(); + commands.add(stream); + stream.inputs.copyFrom(inputs); + stream.modelView.set(modelView); + stream.entityId = entityId; + stream.capture(vertices, vertexCount); + } + + void overlay(DeferredEntityOverlay.DeferredEntry source) { + final Overlay overlay = overlays.acquire(); + commands.add(overlay); + // The shadow overlay queue is recycled before main-view entity + overlay.captured.copyFrom(source); + } + + Rejection validate(int start, int end) { + for (int i = start; i < end; i++) { + final Rejection reason = commands.get(i).validate(); + if (reason != null) return reason; + } + return null; + } + + void replay(int start, int end) { + for (int i = start; i < end; i++) { + final Command command = commands.get(i); + command.replay(); + if (Tracy.ENABLED) { + if (command instanceof Model model && model.source != null) { + sharedParts += model.end - model.start; + sharedRanges++; + } else if (command instanceof Stream) { + streamEntries++; + } + } + } + } + + void clear() { + commands.clear(); + models.clear(); + modelGlints.clear(); + itemGlints.clear(); + streams.clear(); + overlays.clear(); + ranges.clear(); + mergeStart = 0; + } + + void release() { + clear(); + models.release(); + modelGlints.release(); + itemGlints.release(); + streams.release(); + overlays.release(); + ranges.release(); + } + + abstract static class Command { + Rejection validate() { + return null; + } + + abstract void replay(); + } + + static final class DrawInputs { + ResourceLocation texture; + TesrMaterial material; + PassOverride pass; + int textureId, glintSlot, cull; + float offsetFactor, offsetUnits; + boolean offsetEnabled, lit, lightmap, afterGlint; + boolean inheritedOffsetEnable, inheritedOffsetValues, inheritedLighting; + + DrawInputs set(ResourceLocation texture, int textureId, TesrMaterial material, PassOverride pass, boolean offsetEnabled, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) { + this.texture = texture; + this.textureId = textureId; + this.material = material; + this.pass = pass; + this.offsetEnabled = offsetEnabled; + this.offsetFactor = offsetFactor; + this.offsetUnits = offsetUnits; + this.glintSlot = glintSlot; + this.cull = cull; + this.lit = lit; + this.lightmap = lightmap; + this.afterGlint = afterGlint; + return this; + } + + private boolean offsetValuesUsed() { + return !inheritedOffsetValues && (offsetEnabled || inheritedOffsetEnable); + } + + boolean matches(DrawInputs other) { + return textureId == other.textureId && Objects.equals(texture, other.texture) && material == other.material && pass == other.pass && (!offsetValuesUsed() || Float.floatToIntBits(offsetFactor) + == Float.floatToIntBits(other.offsetFactor) && Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)) && offsetEnabled == other.offsetEnabled && glintSlot == other.glintSlot && cull == other.cull + && lit == other.lit && lightmap == other.lightmap && afterGlint == other.afterGlint && inheritedOffsetEnable == other.inheritedOffsetEnable && inheritedOffsetValues == other.inheritedOffsetValues && inheritedLighting + == other.inheritedLighting; + } + + void copyFrom(DrawInputs other) { + set(other.texture, other.textureId, other.material, other.pass, other.offsetEnabled, other.offsetFactor, other.offsetUnits, other.glintSlot, other.cull, other.lit, other.lightmap, other.afterGlint); + inheritedOffsetEnable = other.inheritedOffsetEnable; + inheritedOffsetValues = other.inheritedOffsetValues; + inheritedLighting = other.inheritedLighting; + } + + void clear() { + texture = null; + material = null; + pass = null; + } + } + + static final class Instance { + TemplateBuffer template; + int light, color, overlay; + long entityInfo; + + void set(TemplateBuffer template, int light, int color, int overlay, long entityInfo) { + this.template = template; + this.light = light; + this.color = color; + this.overlay = overlay; + this.entityInfo = entityInfo; + } + } + + abstract static class Draw extends Command { + final DrawInputs inputs = new DrawInputs(); + int entityId; + + void clear() { + inputs.clear(); + } + } + + static final class Model extends Draw { + final Matrix4f modelView = new Matrix4f(); + final Matrix4f textureMatrix = new Matrix4f(); + final Instance instance = new Instance(); + InstanceColumns source; + long sourceVersion; + int start, end; + RenderLayer shadowLayer; + CubeParams[] cubes; + boolean cubesInsideTexture, hasTextureMatrix; + float scale; + Glint glint; + Model nextGlintBase; + InstanceRange replayed; + + boolean cannotAddGlint() { + final TesrMaterial material = inputs.material; + return material == null || !material.isStream() || material.shader() != null || glint != null; + } + + boolean drawsCubes() { + return source != null ? !source.cubes.isEmpty() : cubes != null; + } + + boolean sharedRangeChanged() { + return source != null && (source.version != sourceVersion || end > source.size); + } + + @Override + Rejection validate() { + if (sharedRangeChanged()) return Rejection.SHARED_RANGE_CHANGED; + if (glint != null && !ModelPartBatcher.INSTANCE.canInstanceBaseAndGlint(this, glint.inputs.lightmap)) return Rejection.NOT_READY; + return null; + } + + @Override + void replay() { + ModelPartBatcher.INSTANCE.replay(this); + } + + @Override + void clear() { + super.clear(); + source = null; + shadowLayer = null; + instance.template = null; + cubes = null; + glint = null; + nextGlintBase = null; + replayed = null; + } + } + + abstract static class Glint extends Draw { + Model base; + + @Override + Rejection validate() { + if (!ModelPartBatcher.INSTANCE.canReplayGlint(inputs.material)) return Rejection.NOT_READY; + return inputs.material == EntityMaterials.ITEM_GLINT && !canResetStencil() ? Rejection.UNCAPTURED_STATE : null; + } + + @Override + void clear() { + super.clear(); + base = null; + } + } + + static final class ModelGlint extends Glint { + @Override + void replay() { + ModelPartBatcher.INSTANCE.replay(this); + } + } + + static final class ItemGlint extends Glint { + final Instance instance = new Instance(); + + @Override + void replay() { + ModelPartBatcher.INSTANCE.replay(this); + } + + @Override + void clear() { + super.clear(); + instance.template = null; + } + } + + static final class Stream extends Draw { + final Matrix4f modelView = new Matrix4f(); + int[] vertices; + int vertexCount, entity, blockEntity, item; + float red, green, blue, alpha; + + void capture(int[] vertices, int vertexCount) { + final int length = vertexCount * ModelQuadUtil.VERTEX_SIZE; + if (this.vertices == null) { + this.vertices = new int[length]; + } else if (this.vertices.length < length) { + this.vertices = new int[Math.max(length, this.vertices.length << 1)]; + } + System.arraycopy(vertices, 0, this.vertices, 0, length); + this.vertexCount = vertexCount; + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + entity = state.getCurrentRenderedEntity(); + blockEntity = state.getCurrentRenderedBlockEntity(); + item = state.getCurrentRenderedItem(); + final Vector4fc color = state.getCurrentEntityColor(); + red = color.x(); + green = color.y(); + blue = color.z(); + alpha = color.w(); + } + + @Override + void replay() { + ModelPartBatcher.INSTANCE.replay(this); + } + } + + private static final class Overlay extends Command { + final DeferredEntityOverlay.DeferredEntry captured = new DeferredEntityOverlay.DeferredEntry(); + + @Override + void replay() { + DeferredEntityOverlay.queueReplay(captured, ModelPartBatcher.INSTANCE.replayTransform); + } + + void clear() { + captured.clear(); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplay.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplay.java new file mode 100644 index 000000000..d909ce4b7 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplay.java @@ -0,0 +1,409 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.config.SystemProperties; +import com.gtnewhorizons.angelica.glsm.ExitState; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.DeferredEntityOverlay; +import com.gtnewhorizons.angelica.rendering.tesr.EntityRenderCommands.DrawInputs; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns; +import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import lombok.Setter; +import net.coderbot.iris.pipeline.ShadowRenderer; +import net.minecraft.client.renderer.culling.Frustrum; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; +import net.minecraft.entity.boss.BossStatus; +import net.minecraft.entity.boss.IBossDisplayData; +import net.minecraft.entity.player.EntityPlayer; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +import java.util.Arrays; +import java.util.Objects; + +/** + * Records a shadow-pass entity call, then submits its models, fire, and deferred overlays in the main pass. + */ +public final class EntityShadowReplay { + private static final Tracy.ZoneId Z_REPLAY = Tracy.zoneId("entityReplay", Tracy.COLOR_CLIENT); + private static final long P_REPLAYED = Tracy.plotHandle("entityReplay.replayed"); + private static final long P_SHARED_PARTS = Tracy.plotHandle("entityReplay.sharedParts"); + private static final long P_SHARED_RANGES = Tracy.plotHandle("entityReplay.sharedRanges"); + private static final long P_STREAM_ENTRIES = Tracy.plotHandle("entityReplay.streamEntries"); + private static final long P_RECORDED = Tracy.plotHandle("entityReplay.recorded"); + private static final long P_OUTSIDE_MAIN_VIEW = Tracy.plotHandle("entityReplay.outsideMainView"); + private static final Rejection[] REJECTIONS = Rejection.values(); + private static final long[] rejected = new long[REJECTIONS.length]; + private static final Reference2ObjectOpenHashMap records = new Reference2ObjectOpenHashMap<>(); + private static final Reference2ObjectOpenHashMap, Boolean> excluded = new Reference2ObjectOpenHashMap<>(); + private static final Reference2ObjectOpenHashMap, Reference2IntOpenHashMap>> loggedRejections = new Reference2ObjectOpenHashMap<>(); + private static final Pool recordPool = new Pool<>(Record::new, Record::clear); + private static final EntityRenderCommands commands = new EntityRenderCommands(); + private static final Matrix4f shadowInverse = new Matrix4f(); + private static final Matrix4f mainFromShadow = new Matrix4f(); + private static Record recording; + @Setter private static Frustrum mainView; + private static Class lastType; + private static boolean lastExcluded; + private static long drawsAtStart, replayed, outsideMainView; + private static boolean shadowViewValid, shadowAvailable, mainReady, logRejections; + private static double shadowX, shadowY, shadowZ; + private static float shadowYaw, shadowPitch; + private static float capturedBossHealthScale; + private static int capturedBossBarTime; + private static String capturedBossName; + private static boolean capturedBossColorModifier; + + private EntityShadowReplay() { + } + + public static void beginFrame() { + if (Tracy.ENABLED) { + Tracy.plotInt(P_REPLAYED, replayed); + Tracy.plotInt(P_SHARED_PARTS, commands.sharedParts); + Tracy.plotInt(P_SHARED_RANGES, commands.sharedRanges); + Tracy.plotInt(P_STREAM_ENTRIES, commands.streamEntries); + Tracy.plotInt(P_RECORDED, recordPool.size()); + Tracy.plotInt(P_OUTSIDE_MAIN_VIEW, outsideMainView); + for (Rejection reason : REJECTIONS) Tracy.plotInt(reason.plot, rejected[reason.ordinal()]); + } + replayed = outsideMainView = 0; + commands.sharedParts = commands.sharedRanges = commands.streamEntries = 0; + Arrays.fill(rejected, 0); + resetRecords(); + mainView = null; + logRejections = SystemProperties.debugTooling(); + } + + private static void resetRecords() { + if (recording != null && recording.capturingState) GLStateManager.cancelExitCapture(); + records.clear(); + commands.clear(); + recordPool.clear(); + recording = null; + capturedBossName = null; + shadowViewValid = shadowAvailable = mainReady = false; + } + + static void beginPass(boolean shadow, int renderPass) { + if (shadow) { + resetRecords(); + shadowInverse.set(GLStateManager.getModelViewMatrix()).invert(); + shadowViewValid = shadowInverse.isFinite(); + shadowX = RenderManager.renderPosX; + shadowY = RenderManager.renderPosY; + shadowZ = RenderManager.renderPosZ; + shadowYaw = RenderManager.instance.playerViewY; + shadowPitch = RenderManager.instance.playerViewX; + } else { + mainReady = shadowAvailable && renderPass == 0; + if (mainReady) { + mainFromShadow.set(GLStateManager.getModelViewMatrix()).translate( + (float) (shadowX - RenderManager.renderPosX), (float) (shadowY - RenderManager.renderPosY), + (float) (shadowZ - RenderManager.renderPosZ)).mul(shadowInverse); + } + } + } + + public static boolean beginEntity(Entity entity, float partialTicks) { + if (recording != null) { + reject(Rejection.FOREIGN_DRAW); + return false; + } + if (!shadowViewValid || !ShadowRenderer.ACTIVE || !ModelPartBatcher.INSTANCE.entitiesActive()) return false; + shadowAvailable = true; + // replay() rejects these without a record + if (isExcluded(entity.getClass()) || entity.shouldRenderInPass(1)) return false; + if (!inMainView(entity)) { + outsideMainView++; + return false; + } + final Record record = recordPool.acquire(); + record.start = record.end = commands.size(); + record.entity = entity; + record.partialTicks = partialTicks; + record.hasBossStatus = false; + record.bossColorModifier = false; + record.rejection = null; + records.put(entity, record); + recording = record; + record.capturingState = true; + GLStateManager.beginExitCapture(record.exitState); + drawsAtStart = GLStateManager.drawCalls; + return true; + } + + public static void endEntity(boolean completed) { + if (recording == null) return; + if (recording.capturingState) { + recording.capturingState = false; + if (!GLStateManager.finishExitCapture(recording.exitState)) reject(Rejection.EXIT_STATE_UNSUPPORTED); + } + if (GLStateManager.drawCalls != drawsAtStart) reject(Rejection.FOREIGN_DRAW); + if (recording.renderer == null) reject(Rejection.UNSAFE_RENDERER); + if (!completed) reject(Rejection.RENDER_FAILED); + if (recording.entity instanceof IBossDisplayData && (!recording.hasBossStatus || bossStatusChanged())) { + reject(Rejection.UNCAPTURED_STATE); + } + recording.end = commands.size(); + if (recording.start == recording.end) reject(Rejection.EMPTY_RECORD); + if (recording.rejection == null) recording.texture.capture(); + recording = null; + capturedBossName = null; + } + + public static boolean beginRenderer(Render renderer, Entity entity, float partialTicks, byte batchState) { + if (recording == null) return false; + if (recording.renderer != null || recording.entity != entity) { + reject(Rejection.FOREIGN_DRAW); + return false; + } + recording.renderer = renderer; + if (recording.partialTicks != partialTicks) reject(Rejection.PARTIAL_TICKS_CHANGED); + if (batchState != BatchEligibility.SAFE) reject(Rejection.UNSAFE_RENDERER); + return true; + } + + public static void endRenderer(boolean completed, byte batchState) { + if (!completed) reject(Rejection.RENDER_FAILED); + if (batchState != BatchEligibility.SAFE) reject(Rejection.UNSAFE_RENDERER); + } + + private static boolean inMainView(Entity entity) { + return mainView == null || entity.isInRangeToRender3d(mainView.xPosition, mainView.yPosition, mainView.zPosition) + && (entity.ignoreFrustumCheck || mainView.isBoundingBoxInFrustum(entity.boundingBox)); + } + + static boolean isExcluded(Class type) { + if (type == lastType) return lastExcluded; + Boolean result = excluded.get(type); + if (result == null) { + result = EntityPlayer.class.isAssignableFrom(type); + for (Class parent = type; !result && parent != null; parent = parent.getSuperclass()) { + final String[] names = AngelicaConfig.entityShadowReplayExcludedClasses; + if (names != null) for (String name : names) { + if (parent.getName().equals(name)) { + result = true; + break; + } + } + } + excluded.put(type, result); + } + lastType = type; + lastExcluded = result; + return result; + } + + public static boolean replay(RenderManager manager, Entity entity, float partialTicks, int renderPass) { + if (!shadowAvailable || ShadowRenderer.ACTIVE) return false; + final Record record = records.get(entity); + if (record == null && !Tracy.ENABLED && !logRejections) return false; + Rejection reason = renderPass != 0 ? Rejection.RENDER_PASS + : record != null ? record.rejection + : isExcluded(entity.getClass()) ? Rejection.EXCLUDED + : entity.shouldRenderInPass(1) ? Rejection.RENDER_PASS : Rejection.NOT_IN_SHADOW_PASS; + if (reason == null) { + if (!mainReady || !ModelPartBatcher.INSTANCE.canReplayEntity()) reason = Rejection.NOT_READY; + else if (record.renderer != manager.getEntityRenderObject(entity)) reason = Rejection.RENDERER_CHANGED; + else if (record.partialTicks != partialTicks) reason = Rejection.PARTIAL_TICKS_CHANGED; + else if (shadowYaw != RenderManager.instance.playerViewY || shadowPitch != RenderManager.instance.playerViewX) reason = Rejection.VIEW_CHANGED; + else if (!GLStateManager.canApplyExitState(record.exitState)) reason = Rejection.ENTRY_STATE_CHANGED; + else if (GLStateManager.getPolygonState().getOffsetClamp() != 0) reason = Rejection.UNCAPTURED_STATE; + } + if (reason == null) { + reason = commands.validate(record.start, record.end); + } + if (reason != null) { + rejected[reason.ordinal()]++; + logRejection(entity.getClass(), record == null || record.renderer == null ? null : record.renderer.getClass(), reason); + return false; + } + replayed++; + if (Tracy.FINE_ZONES) Tracy.beginZone(Z_REPLAY); + try { + if (record.hasBossStatus) BossStatus.setBossStatus((IBossDisplayData) record.entity, record.bossColorModifier); + ModelPartBatcher.INSTANCE.beginReplay(mainFromShadow); + commands.replay(record.start, record.end); + GLStateManager.applyExitState(record.exitState); + record.texture.apply(); + } finally { + if (Tracy.FINE_ZONES) Tracy.endZone(); + } + return true; + } + + private static void logRejection(Class entity, Class renderer, Rejection reason) { + if (!logRejections) return; + Reference2IntOpenHashMap> reasons = loggedRejections.get(entity); + if (reasons == null) { + reasons = new Reference2IntOpenHashMap<>(); + loggedRejections.put(entity, reasons); + } + final int bit = 1 << reason.ordinal(); + final int logged = reasons.getInt(renderer); + if ((logged & bit) != 0) return; + reasons.put(renderer, logged | bit); + AngelicaMod.LOGGER.info("Entity shadow replay fallback: entity={} capturedRenderer={} reason={}: {}", + entity.getName(), renderer == null ? "" : renderer.getName(), reason.label, reason.description); + } + + static EntityRenderCommands.Model recordModel(InstanceColumns source, RenderLayer layer, DrawInputs inputs, int entityId, + boolean cubesInsideTexture, Matrix4fc modelView, Matrix4fc texMatrix) { + return captureInheritedState(inputs) + ? commands.model(recording.start, source, layer, inputs, entityId, cubesInsideTexture, modelView, texMatrix) : null; + } + + static void recordStream(Matrix4fc modelView, int[] vertices, int vertexCount, int groupId, DrawInputs inputs) { + if (captureInheritedState(inputs)) commands.stream(modelView, vertices, vertexCount, groupId, inputs); + } + + static EntityRenderCommands.ModelGlint recordArmorGlint(int start, int end, DrawInputs inputs) { + return captureInheritedState(inputs) && start >= recording.start && end > start && end <= commands.size() + ? commands.modelGlint(start, end, inputs) : null; + } + + static EntityRenderCommands.ItemGlint recordItemGlint(Matrix4fc modelView, DrawInputs inputs) { + return captureInheritedState(inputs) && commands.size() > recording.start ? commands.itemGlint(modelView, inputs) : null; + } + + private static boolean captureInheritedState(DrawInputs inputs) { + if (GLStateManager.getPolygonState().getOffsetClamp() != 0) reject(Rejection.UNCAPTURED_STATE); + if (!isRecording()) return false; + final int offsetWrites = GLStateManager.getExitPolygonOffsetWrites(); + inputs.inheritedOffsetEnable = (offsetWrites & ExitState.POLYGON_OFFSET_ENABLE_WRITTEN) == 0; + inputs.inheritedOffsetValues = (offsetWrites & ExitState.POLYGON_OFFSET_VALUES_WRITTEN) == 0; + inputs.inheritedLighting = !GLStateManager.isExitLightingWritten(); + return true; + } + + static boolean isRecording() { + return recording != null && recording.rejection == null; + } + + static int splitCommands() { + return isRecording() ? commands.split() : -1; + } + + public static void recordDeferredOverlay(DeferredEntityOverlay.DeferredEntry overlay) { + if (isRecording()) commands.overlay(overlay); + } + + public static void recordBossStatus(IBossDisplayData boss, boolean colorModifier) { + if (!isRecording()) return; + if (boss != recording.entity || recording.hasBossStatus) { + reject(Rejection.UNCAPTURED_STATE); + return; + } + recording.hasBossStatus = true; + recording.bossColorModifier = colorModifier; + capturedBossHealthScale = BossStatus.healthScale; + capturedBossBarTime = BossStatus.statusBarTime; + capturedBossName = BossStatus.bossName; + capturedBossColorModifier = BossStatus.hasColorModifier; + } + + private static boolean bossStatusChanged() { + return Float.floatToIntBits(capturedBossHealthScale) != Float.floatToIntBits(BossStatus.healthScale) + || capturedBossBarTime != BossStatus.statusBarTime + || !Objects.equals(capturedBossName, BossStatus.bossName) + || capturedBossColorModifier != BossStatus.hasColorModifier; + } + + private static void reject(Rejection reason) { + if (recording != null && recording.rejection == null) { + recording.rejection = reason; + if (recording.capturingState) { + GLStateManager.cancelExitCapture(); + recording.capturingState = false; + } + } + } + + public static void rejectForeignDraw() { + reject(Rejection.FOREIGN_DRAW); + } + + public static void rejectRenderFailed() { + reject(Rejection.RENDER_FAILED); + } + + public static void rejectShadowOnly() { + reject(Rejection.SHADOW_ONLY_SKIP); + } + + static void rejectUncapturedState() { + reject(Rejection.UNCAPTURED_STATE); + } + + static void rejectPartFallback() { + reject(Rejection.PART_FALLBACK); + } + + static void rejectBatcherBail() { + reject(Rejection.BATCHER_BAIL); + } + + public static void clear() { + resetRecords(); + mainView = null; + commands.release(); + recordPool.release(); + excluded.clear(); + lastType = null; + loggedRejections.clear(); + } + + enum Rejection { + EXCLUDED( "excluded", "Player or configured excluded class."), + FOREIGN_DRAW( "foreignDraw", "Uncaptured draw or nested entity rendering."), + SHADOW_ONLY_SKIP( "shadowOnlySkip", "Shadow rendering skipped work needed in the main view."), + RENDER_PASS( "renderPass", "Entity requires a render pass outside the supported pass 0."), + NOT_IN_SHADOW_PASS( "notInShadowPass", "No shadow record this frame; shadow range or culling can cause this!"), + UNSAFE_RENDERER( "unsafeRenderer", "Renderer is not marked safe for batching, or no renderer ran."), + EMPTY_RECORD( "emptyRecord", "No replayable rendering commands were captured."), + UNCAPTURED_STATE( "uncapturedState", "Unsupported render state or boss HUD side effects."), + PART_FALLBACK( "partFallback", "A model part used the live rendering path."), + BATCHER_BAIL( "batcherBail", "A draw could not use the model batcher."), + RENDER_FAILED( "renderFailed", "The captured renderer call did not complete successfully."), + NOT_READY( "notReady", "Main-pass batching is inactive or a required instanced shader variant is missing."), + RENDERER_CHANGED( "rendererChanged", "The main renderer differs from the captured renderer."), + PARTIAL_TICKS_CHANGED( "partialTicksChanged", "Animation time differs from the one the shadow pass recorded."), + VIEW_CHANGED( "viewChanged", "Camera angles changed between shadow and main views."), + EXIT_STATE_UNSUPPORTED( "exitStateUnsupported", "Renderer state includes an unsupported operation, state query, or unbalanced stack."), + ENTRY_STATE_CHANGED( "entryStateChanged", "Main renderer entry state differs from a captured dependency, or a texture was deleted."), + SHARED_RANGE_CHANGED( "sharedRangeChanged", "Captured instance storage was rebuilt or shortened."); + + final long plot; + final String label, description; + + Rejection(String name, String description) { + plot = Tracy.plotHandle("entityReplay." + name); + label = name; + this.description = description; + } + } + + static final class Record { + final ExitState exitState = new ExitState(); + final ModelPartBatcher.BoundTexture texture = new ModelPartBatcher.BoundTexture(); + int start, end; + Render renderer; + Entity entity; + float partialTicks; + boolean hasBossStatus, bossColorModifier, capturingState; + Rejection rejection; + + void clear() { + renderer = null; + entity = null; + texture.location = null; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlas.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlas.java index c19201592..2a5190e6c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlas.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlas.java @@ -247,9 +247,10 @@ public final class EntityTextureAtlas { private Page newPage() { if (pages.size() == MAX_PAGES) return null; final int previous = GLStateManager.getBoundTextureForServerState(); - final int texture = GLStateManager.glGenTextures(); + final int texture; BatchStateGuard.suspend(); try { + texture = GLStateManager.glGenTextures(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); @@ -269,15 +270,15 @@ public final class EntityTextureAtlas { } private void copy(int texture, Slot slot) { - if (readFbo == 0) { - readFbo = GLStateManager.glGenFramebuffers(); - drawFbo = GLStateManager.glGenFramebuffers(); - } final int previousRead = GLStateManager.getReadFramebuffer(); final int previousDraw = GLStateManager.getDrawFramebuffer(); - final boolean scissor = GLStateManager.glIsEnabled(GL11.GL_SCISSOR_TEST); + final boolean scissor = GLStateManager.getScissorTest().isEnabled(); BatchStateGuard.suspend(); try { + if (readFbo == 0) { + readFbo = GLStateManager.glGenFramebuffers(); + drawFbo = GLStateManager.glGenFramebuffers(); + } if (scissor) GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, readFbo); GLStateManager.attachTextureForReading(GL30.GL_COLOR_ATTACHMENT0, texture); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/GlintCapture.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/GlintCapture.java index 6d2286ef5..767532b9e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/GlintCapture.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/GlintCapture.java @@ -36,6 +36,7 @@ public final class GlintCapture { private boolean poseRestored; private int restoredGeneration; private boolean uniformLight; + private int replayStart = -1, replayEnd = -1; public void reset() { if (owner != null && owner.glintCapture == this) owner.glintCapture = null; @@ -51,6 +52,7 @@ public final class GlintCapture { base = false; trusted = false; poseRestored = false; + replayStart = replayEnd = -1; } boolean begin(RetainedTesrGroups groups) { @@ -79,6 +81,10 @@ public final class GlintCapture { return true; } + void beginShadowReplay() { + replayStart = EntityShadowReplay.splitCommands(); + } + /** For records queued without running model or mod code; the caller replays before any GL state changes. */ boolean beginTrusted(RetainedTesrGroups groups) { if (!open(groups)) return false; @@ -101,6 +107,7 @@ public final class GlintCapture { void invalidate() { valid = false; } void allowBase() { base = true; } boolean capturesBase() { return base && valid; } + boolean keepsBaseUpload() { return capturesBase() && replayStart < 0; } void record(RetainedTesrGroups.Group group, RetainedTesrGroups.InstanceColumns columns, RetainedTesrGroups.TexRun source, int start, int end, int instances) { if (!valid) return; @@ -144,6 +151,7 @@ public final class GlintCapture { valid &= GLStateManager.drawCalls == draws && used > 0; this.poseRestored = poseRestored; restoredGeneration = GLStateManager.getMvGeneration(); + if (replayStart >= 0) replayEnd = EntityShadowReplay.splitCommands(); } private boolean sameParentPose() { @@ -165,7 +173,7 @@ public final class GlintCapture { } for (int i = 0; i < used; i++) { final Range range = ranges.get(i); - range.group.replayRange(range.columns, range.source, range.start, range.end, range.instances, textureMatrix); + groups.replayRange(range.group, range.columns, range.source, range.start, range.end, range.instances, textureMatrix); } valid = false; return true; @@ -184,12 +192,23 @@ public final class GlintCapture { boolean queueBothLayers(ModelPartBatcher batcher, RetainedTesrGroups groups, ResourceLocation glintTexture) { if (!baseStillValid(groups) || !sameLightAndOverlay(batcher.currentOverlay()) || !batcher.prepareSkippedArmorGlint(glintTexture)) return false; + queueLayers(batcher); + return true; + } + + boolean recordBothLayers(ModelPartBatcher batcher, RetainedTesrGroups groups, ResourceLocation glintTexture) { + if (!baseStillValid(groups) || !sameLightAndOverlay(batcher.currentOverlay()) + || !batcher.recordArmorGlint(replayStart, replayEnd, glintTexture)) return false; + valid = false; + return true; + } + + void queueLayers(ModelPartBatcher batcher) { for (int i = 0; i < used; i++) { final Range range = ranges.get(i); batcher.queueArmorGlintLayers(range.columns, range.source, range.start, range.end); } valid = false; - return true; } private boolean baseStillValid(RetainedTesrGroups groups) { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java index 506c36202..8c86c7c56 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java @@ -35,6 +35,8 @@ import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.iris.Iris; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.layer.PassOverride; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; @@ -50,12 +52,14 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import org.joml.Matrix4f; +import org.joml.Matrix4fc; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import java.util.Arrays; import java.util.List; import java.util.Objects; +import java.util.function.ToLongFunction; public final class ModelPartBatcher { @@ -91,6 +95,8 @@ public final class ModelPartBatcher { private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource); private final RetainedTesrGroups entityGroups = new RetainedTesrGroups(entitySource); private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource); + private final RetainedTesrGroups shadowEntityGroups = new RetainedTesrGroups(bufferSource); + private final RetainedTesrGroups[] allGroups = {groups, entityGroups, shadowGroups, shadowEntityGroups}; private RetainedTesrGroups activeGroups = groups; private AngelicaBufferSource activeSource = bufferSource; private boolean entityTranslucentsHeld; @@ -99,6 +105,12 @@ public final class ModelPartBatcher { private final Matrix4f identity = new Matrix4f(); private final Matrix4f modelView = new Matrix4f(); private final Matrix4f texMatrixScratch = new Matrix4f(); + private final Matrix4f replayView = new Matrix4f(); + private final EntityRenderCommands.DrawInputs drawInputs = new EntityRenderCommands.DrawInputs(); + Matrix4fc replayTransform; + private boolean replayOffsetEnabled; + private float replayOffsetFactor, replayOffsetUnits; + private boolean loggedDroppedGlint; private int lastMvGeneration; private boolean mvCaptured; private int texGeneration; @@ -127,11 +139,17 @@ public final class ModelPartBatcher { public long statArmorLoopSkips() { return armorLoopSkips; } public long statArmorSectionSkips() { return armorSectionSkips; } public long statLiveFallbacks() { return liveFallbacks; } - public long statInstancedDraws() { return groups.instancedDraws + entityGroups.instancedDraws + shadowGroups.instancedDraws; } - public long statInstancedInstances() { return groups.instancedInstances + entityGroups.instancedInstances + shadowGroups.instancedInstances; } - public long statCubeInstances() { return groups.cubeInstances + entityGroups.cubeInstances + shadowGroups.cubeInstances; } - public long statRedrawnInstances() { return groups.redrawnInstances + entityGroups.redrawnInstances + shadowGroups.redrawnInstances; } - public long statTexMatrixRuns() { return groups.texMatrixRuns + entityGroups.texMatrixRuns + shadowGroups.texMatrixRuns; } + public long statInstancedDraws() { return sumGroups(g -> g.instancedDraws); } + public long statInstancedInstances() { return sumGroups(g -> g.instancedInstances); } + public long statCubeInstances() { return sumGroups(g -> g.cubeInstances); } + public long statRedrawnInstances() { return sumGroups(g -> g.redrawnInstances); } + public long statTexMatrixRuns() { return sumGroups(g -> g.texMatrixRuns); } + + private long sumGroups(ToLongFunction stat) { + long sum = 0; + for (RetainedTesrGroups group : allGroups) sum += stat.applyAsLong(group); + return sum; + } public long statBail(BailReason reason) { return bails[reason.ordinal()]; } public long statShadowQuads() { return shadows.statQuads(); } public long statShadowDraws() { return shadows.statDraws(); } @@ -220,6 +238,24 @@ public final class ModelPartBatcher { private static int lastBoundGlId = -1; private static int lastBoundGlintSlot = ShaderGlint.NO_TINT; + static final class BoundTexture { + ResourceLocation location; + int id, glintSlot; + + void capture() { + id = GLStateManager.getBoundTextureForServerState(0); + location = id == lastBoundGlId ? lastBoundLocation : null; + glintSlot = id == lastBoundGlId ? lastBoundGlintSlot : ShaderGlint.NO_TINT; + } + + void apply() { + if (GLStateManager.getBoundTextureForServerState(0) != id) return; + lastBoundLocation = location; + lastBoundGlId = id; + lastBoundGlintSlot = glintSlot; + } + } + private ModelPartBatcher() {} public static void onTextureSwap(int glId, int glintSlot) { @@ -258,17 +294,17 @@ public final class ModelPartBatcher { final long nowMs = System.currentTimeMillis(); mvCaptured = false; texCaptured = false; - activeGroups = shadow ? shadowGroups : entityPass ? entityGroups : groups; + final boolean replayEntities = mode == Mode.ENTITIES && AngelicaConfig.entityShadowReplayEnabled(); + activeGroups = shadow ? (replayEntities ? shadowEntityGroups : shadowGroups) : entityPass ? entityGroups : groups; activeSource = entityPass ? entitySource : bufferSource; activeSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY); activeSource.capturePassLighting(); BatchDrawDefaults.capturePassFramebuffer(); activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline); + if (replayEntities && shaderPipeline != null) EntityShadowReplay.beginPass(shadow, MinecraftForgeClient.getRenderPass()); if (nowMs - lastSweepMs >= SWEEP_INTERVAL_MS) { lastSweepMs = nowMs; - groups.sweep(nowMs); - entityGroups.sweep(nowMs); - shadowGroups.sweep(nowMs); + for (RetainedTesrGroups group : allGroups) group.sweep(nowMs); sweepTemplates(nowMs); } } @@ -402,8 +438,19 @@ public final class ModelPartBatcher { /** Skipped glint blocks queue each layer as its own instanced draw, so a shader pack only needs its pass program current. */ public boolean canQueueGlint() { - return active && instancedThisCycle && !shadow && BatchEligibility.batchingAllowed() && !GLStateManager.isRecordingDisplayList() - && GLStateManager.getActiveProgram() == (shaderPipeline != null ? shaderPipeline.getActivePassProgramId() : 0); + return !shadow && canBatchGlint(); + } + + private boolean cannotQueueOrRecordGlint() { + return shadow && (mode != Mode.ENTITIES || !EntityShadowReplay.isRecording()) || !canBatchGlint(); + } + + private boolean canBatchGlint() { + return active && instancedThisCycle && BatchEligibility.batchingAllowed() && !GLStateManager.isRecordingDisplayList() && passProgramBound(); + } + + private boolean passProgramBound() { + return GLStateManager.getActiveProgram() == (shaderPipeline != null ? shaderPipeline.getActivePassProgramId() : 0); } public boolean replayGlint(GlintCapture capture) { @@ -426,7 +473,25 @@ public final class ModelPartBatcher { } public boolean beginArmorCapture(GlintCapture capture) { - return canQueueGlint() && capture.beginBase(activeGroups, currentOverlay()); + if (cannotQueueOrRecordGlint() || !capture.beginBase(activeGroups, currentOverlay())) return false; + if (shadow) capture.beginShadowReplay(); + return true; + } + + boolean canReplayGlint(TesrMaterial material) { + return entityPassActive() && instancedThisCycle && activeGroups.glintCapture == null + && activeGroups.canCopyInstances(material); + } + + boolean canInstanceBaseAndGlint(EntityRenderCommands.Model base, boolean glintLightmap) { + final EntityRenderCommands.DrawInputs inputs = base.inputs; + if (!activeGroups.canCopyInstances(inputs.material)) return false; + if (shaderPipeline == null) return true; + final RenderCondition condition = inputs.pass.entityCondition(inputs.material.transparency() == TesrMaterial.Transparency.TRANSLUCENT); + if (condition == null) return false; + final Instancing kind = base.drawsCubes() ? Instancing.CUBE : Instancing.TEMPLATE; + return shaderPipeline.hasInstancedVariant(condition, InputAvailability.of(inputs.texture != null, inputs.lightmap), kind) + && shaderPipeline.hasInstancedVariant(RenderCondition.GLINT, InputAvailability.of(true, glintLightmap), kind); } public boolean reuseArmorBase(GlintCapture base, GlintCapture glint) { @@ -446,20 +511,29 @@ public final class ModelPartBatcher { } public boolean queueSkippedArmorGlint(GlintCapture base, ResourceLocation glintTexture) { - if (!canQueueGlint() || GLStateManager.getActiveTextureUnit() != 0 || !GLStateManager.getTextures().getTextureUnitStates(0).isEnabled() || !base.queueBothLayers(this, activeGroups, glintTexture)) return false; - armorBaseReuses++; - glintPassReuses++; - armorSectionSkips++; + if (cannotQueueOrRecordGlint() || GLStateManager.getActiveTextureUnit() != 0 || !GLStateManager.getTextures().getTextureUnitStates(0).isEnabled()) return false; + if (!(shadow ? base.recordBothLayers(this, activeGroups, glintTexture) : base.queueBothLayers(this, activeGroups, glintTexture))) return false; + if (!shadow) { + armorBaseReuses++; + glintPassReuses++; + armorSectionSkips++; + } BatchEligibility.onPartQueued(); return true; } public boolean queueSkippedItemGlint(TemplateBuffer template, TesrMaterial material) { - if (!canQueueGlint() || GLStateManager.getActiveTextureUnit() != 0 || !activeGroups.canCopyInstances(material) || !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0))) return false; - final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); - final PolygonState polygon = GLStateManager.getPolygonState(); - final int cullCode = DrawState.liveCull(material); - final RenderLayer layer = layerFor(ItemGlint.texture(), material, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, ShaderGlint.NO_TINT, cullCode, false, DrawState.liveLightmap()); + if (cannotQueueOrRecordGlint() || GLStateManager.getActiveTextureUnit() != 0 || !activeGroups.canCopyInstances(material) || !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0))) return false; + final EntityRenderCommands.DrawInputs inputs = glintInputs(ItemGlint.texture(), material, ShaderGlint.NO_TINT, false); + if (shadow) { + if (material == EntityMaterials.ITEM_GLINT && !ItemGlint.canResetStencil()) return false; + final EntityRenderCommands.ItemGlint entry = EntityShadowReplay.recordItemGlint(currentModelView(), inputs); + if (entry == null) return false; + GLStateManager.requireExitDrawState(false); + entry.instance.set(template, GLSMConfig.packedLastBrightness(), VANILLA_GLINT_COLOR, currentOverlay(), currentEntityInfo(0)); + return true; + } + final RenderLayer layer = layerFor(ItemGlint.texture(), inputs); activeGroups.queueGlintLayers(template, layer, material, currentModelView(), GLSMConfig.packedLastBrightness(), VANILLA_GLINT_COLOR, currentOverlay(), currentEntityInfo(0), ItemGlint.firstMatrix(), ItemGlint.secondMatrix()); parts++; @@ -467,6 +541,23 @@ public final class ModelPartBatcher { return true; } + boolean recordArmorGlint(int start, int end, ResourceLocation texture) { + if (EntityShadowReplay.recordArmorGlint(start, end, glintInputs(texture, EntityMaterials.GLINT, ShaderGlint.NO_TINT, false)) == null) return false; + GLStateManager.requireExitDrawState(false); + return true; + } + + private EntityRenderCommands.DrawInputs glintInputs(ResourceLocation texture, TesrMaterial material, int glintSlot, boolean lit) { + return liveInputs(texture, 0, material, PassOverride.NONE, glintSlot, DrawState.liveCull(material), lit, DrawState.liveLightmap(), false); + } + + private EntityRenderCommands.DrawInputs liveInputs(ResourceLocation texture, int textureId, TesrMaterial material, PassOverride pass, + int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) { + final PolygonState polygon = GLStateManager.getPolygonState(); + return drawInputs.set(texture, textureId, material, pass, GLStateManager.getPolygonOffsetFillState().isEnabled(), + polygon.getOffsetFactor(), polygon.getOffsetUnits(), glintSlot, cull, lit, lightmap, afterGlint); + } + private Matrix4f currentModelView() { final int mvGen = GLStateManager.getMvGeneration(); if (!mvCaptured || mvGen != lastMvGeneration) { @@ -500,10 +591,7 @@ public final class ModelPartBatcher { } private void setArmorGlint(ResourceLocation texture, int glintSlot, boolean lit, Matrix4f textureMatrix, int color) { - final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); - final PolygonState polygon = GLStateManager.getPolygonState(); - final int cullCode = DrawState.liveCull(EntityMaterials.GLINT); - armorGlintLayer = layerFor(texture, EntityMaterials.GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, glintSlot, cullCode, lit, DrawState.liveLightmap()); + armorGlintLayer = layerFor(texture, glintInputs(texture, EntityMaterials.GLINT, glintSlot, lit)); armorGlintTexture.set(textureMatrix); armorGlintColor = color; armorGlintLight = GLSMConfig.packedLastBrightness(); @@ -528,6 +616,10 @@ public final class ModelPartBatcher { return entitiesActive() && !shadow; } + boolean canReplayEntity() { + return entityPassActive() && passProgramBound(); + } + public boolean entitiesActive() { return active && mode == Mode.ENTITIES; } @@ -536,6 +628,10 @@ public final class ModelPartBatcher { return active && shadow; } + boolean recordsEntitySubmissions(RetainedTesrGroups groups) { + return active && shadow && mode == Mode.ENTITIES && activeGroups == groups; + } + public static boolean recordShadow(World world, Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, float shadowSize) { return INSTANCE.shadows.record(world, entity, x, y, z, shadowAlpha, partialTicks, shadowSize); } @@ -568,6 +664,7 @@ public final class ModelPartBatcher { return true; } if (shadow && isDepthEqualDecalState()) { + EntityShadowReplay.rejectShadowOnly(); return true; } return queueTemplate(entry.template, entry.cubes, entry.cubesInsideTexture, scale, null, false); @@ -619,17 +716,14 @@ public final class ModelPartBatcher { return false; } + GLStateManager.requireExitDrawState(false); final Matrix4f texMatrix = texture != null && !unitTexIdentity() ? texMatrixScratch : null; final PassOverride pass = shaderPipeline != null ? PassOverride.capture() : PassOverride.NONE; - final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); - final PolygonState polygon = GLStateManager.getPolygonState(); - final float offsetFactor = offset ? polygon.getOffsetFactor() : 0.0f; - final float offsetUnits = offset ? polygon.getOffsetUnits() : 0.0f; final int glintSlot = material.special().isGlint() ? lastBoundGlintSlot : ShaderGlint.NO_TINT; - final int cullCode = DrawState.liveCull(material); - final boolean lit = DrawState.liveLit(material); + final EntityRenderCommands.DrawInputs inputs = liveInputs(texture, lastBoundGlId, material, pass, glintSlot, + DrawState.liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap(), afterGlint); final EntityTextureAtlas.Slot atlasSlot = texMatrix == null && cubesInsideTexture ? atlasSlotFor(material) : null; - final RenderLayer layer = layerFor(atlasSlot != null ? Objects.requireNonNull(atlasSlot.page).location : texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, DrawState.liveLightmap(), afterGlint); + final RenderLayer layer = layerFor(atlasSlot != null ? Objects.requireNonNull(atlasSlot.page).location : texture, inputs); // Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); final Color4 color = GLStateManager.getColor(); @@ -637,18 +731,110 @@ public final class ModelPartBatcher { final int overlayABGR = currentOverlay(); final long entityInfo = currentEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); final int packedLight = GLSMConfig.packedLastBrightness(); - activeGroups.queue(0L, template, cubes, scale, layer, material, currentModelView(), packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix, atlasSlot); + final Matrix4f modelView = currentModelView(); + activeGroups.queueAndRecord(template, cubes, scale, layer, modelView, packedLight, colorABGR, overlayABGR, entityInfo, + entityId, texMatrix, atlasSlot, cubesInsideTexture, inputs); parts++; return true; } private EntityTextureAtlas.Slot atlasSlotFor(TesrMaterial material) { + return atlasSlotFor(material, lastBoundGlId); + } + + private EntityTextureAtlas.Slot atlasSlotFor(TesrMaterial material, int textureId) { if (!AngelicaConfig.enableEntityTextureAtlas) return null; // Glint, overlay and custom shaders sample their own textures if (material.special() != TesrMaterial.SpecialRender.NONE || material.shader() != null || material.isUnfilteredAtlas() || material == EntityMaterials.OVERLAY) return null; if (!activeGroups.instancesCubes(material)) return null; if (shaderPipeline != null && !shaderPipeline.hasInstancedVariant(Instancing.CUBE)) return null; - return EntityTextureAtlas.INSTANCE.slotFor(lastBoundGlId, shaderPipeline != null); + return EntityTextureAtlas.INSTANCE.slotFor(textureId, shaderPipeline != null); + } + + void beginReplay(Matrix4fc mainFromShadow) { + replayTransform = mainFromShadow; + final PolygonState polygon = GLStateManager.getPolygonState(); + replayOffsetEnabled = GLStateManager.getPolygonOffsetFillState().isEnabled(); + replayOffsetFactor = polygon.getOffsetFactor(); + replayOffsetUnits = polygon.getOffsetUnits(); + } + + private RenderLayer replayLayer(EntityRenderCommands.Draw entry, EntityTextureAtlas.Slot slot) { + final EntityRenderCommands.DrawInputs inputs = entry.inputs; + final boolean enabled = inputs.inheritedOffsetEnable ? replayOffsetEnabled : inputs.offsetEnabled; + final float factor = inputs.inheritedOffsetValues ? replayOffsetFactor : inputs.offsetFactor; + final float units = inputs.inheritedOffsetValues ? replayOffsetUnits : inputs.offsetUnits; + final boolean lit = inputs.inheritedLighting ? DrawState.liveLit(inputs.material) : inputs.lit; + return layerFor(slot != null ? Objects.requireNonNull(slot.page).location : inputs.texture, + inputs.material, inputs.pass, enabled, factor, units, inputs.glintSlot, inputs.cull, lit, inputs.lightmap, inputs.afterGlint); + } + + void replay(EntityRenderCommands.Model entry) { + final RetainedTesrGroups.InstanceRange replayed = entry.glint != null ? entry.replayed : null; + final TesrMaterial material = entry.inputs.material; + // begin() may have recycled the shadow pass's atlas region. + // A reused base upload must keep the original UVs for the glint texture. + final EntityTextureAtlas.Slot slot = (replayed == null || !replayed.reuseUpload) && !entry.hasTextureMatrix && entry.cubesInsideTexture + ? atlasSlotFor(material, entry.inputs.textureId) : null; + final RenderLayer layer = replayLayer(entry, slot); + final Matrix4f texMatrix = entry.hasTextureMatrix ? entry.textureMatrix : null; + if (entry.source != null) { + activeGroups.replayInstances(entry.source, entry.start, entry.end, layer, material, entry.entityId, + replayTransform, texMatrix, slot, replayed); + parts += entry.end - entry.start; + } else { + replayTransform.mul(entry.modelView, replayView); + final EntityRenderCommands.Instance instance = entry.instance; + activeGroups.queueReplay(instance.template, entry.cubes, entry.scale, layer, material, replayView, + instance.light, instance.color, instance.overlay, instance.entityInfo, entry.entityId, texMatrix, slot, replayed); + parts++; + } + } + + void replay(EntityRenderCommands.ModelGlint entry) { + final RenderLayer layer = replayLayer(entry, null); + for (EntityRenderCommands.Model base = entry.base; base != null; base = base.nextGlintBase) { + final RetainedTesrGroups.InstanceRange range = base.replayed; + if (glintBaseMissing(range)) continue; + activeGroups.referenceGlintLayers(range.columns, range.run, range.start, range.end, layer, entry.inputs.material, + VANILLA_GLINT_COLOR, GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix()); + parts += range.end - range.start; + } + } + + void replay(EntityRenderCommands.ItemGlint entry) { + final RetainedTesrGroups.InstanceRange base = entry.base.replayed; + if (glintBaseMissing(base)) return; + final RenderLayer layer = replayLayer(entry, null); + base.columns.pose(base.end - 1, replayView); + final EntityRenderCommands.Instance instance = entry.instance; + activeGroups.queueGlintLayers(instance.template, layer, entry.inputs.material, replayView, + instance.light, instance.color, instance.overlay, instance.entityInfo, ItemGlint.firstMatrix(), ItemGlint.secondMatrix()); + parts++; + } + + private boolean glintBaseMissing(RetainedTesrGroups.InstanceRange base) { + if (base.columns != null) return false; + if (!loggedDroppedGlint) { + loggedDroppedGlint = true; + AngelicaMod.LOGGER.warn("Entity shadow replay dropped a glint render because its base was not drawn instanced"); + } + return true; + } + + void replay(EntityRenderCommands.Stream entry) { + final RenderLayer layer = replayLayer(entry, null); + replayTransform.mul(entry.modelView, replayView); + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + state.pushEntityState(); + try { + state.setCurrentEntityAndItem(entry.entity, entry.item); + state.setCurrentBlockEntity(entry.blockEntity); + state.setCurrentEntityColor(entry.red, entry.green, entry.blue, entry.alpha); + activeGroups.streamVertices(layer, entry.entityId, entry.vertices, entry.vertexCount, replayView); + } finally { + state.popEntityState(); + } } private enum TessellatorRoute { DRAW_NOW, DRAW_NOW_EXPECTED, QUEUE } @@ -684,23 +870,27 @@ public final class ModelPartBatcher { if (!entityFire && (mode != Mode.BLOCK_ENTITIES || !BatchEligibility.insideRenderer())) return TessellatorRoute.DRAW_NOW; if (!tess.isDrawing || tess.drawMode != GL11.GL_QUADS || tess.vertexCount == 0 || (tess.vertexCount & 3) != 0) return TessellatorRoute.DRAW_NOW; if (shaderPipeline != null && TessellatorEntityIds.hasIdChanges(tess)) return TessellatorRoute.DRAW_NOW; - if (DisplayListManager.isRecording() || !GLStateManager.glIsEnabled(GL11.GL_DEPTH_TEST) || !unitTexIdentity()) return TessellatorRoute.DRAW_NOW; - if (GLStateManager.getActiveProgram() != (shaderPipeline != null ? shaderPipeline.getActivePassProgramId() : 0)) return TessellatorRoute.DRAW_NOW; + if (DisplayListManager.isRecording() || !GLStateManager.getDepthTest().isEnabled() || !unitTexIdentity()) return TessellatorRoute.DRAW_NOW; + if (!passProgramBound()) return TessellatorRoute.DRAW_NOW; final TesrMaterial material = EntityMaterials.fromCurrentState(true); if (material == null || material == EntityMaterials.OVERLAY) return TessellatorRoute.DRAW_NOW; if (lastBoundLocation == null || GLStateManager.getBoundTextureForServerState() != lastBoundGlId) return TessellatorRoute.DRAW_NOW; if (!entityFire && !BatchEligibility.batchingAllowed()) return TessellatorRoute.DRAW_NOW_EXPECTED; + GLStateManager.requireExitDrawState(false); final PassOverride pass = shaderPipeline != null ? PassOverride.capture() : PassOverride.NONE; - final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); - final PolygonState polygon = GLStateManager.getPolygonState(); - final int cullCode = DrawState.liveCull(material); - final RenderLayer layer = layerFor(lastBoundLocation, material, pass, offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f, - ShaderGlint.NO_TINT, cullCode, DrawState.liveLit(material), DrawState.liveLightmap()); + final EntityRenderCommands.DrawInputs inputs = liveInputs(lastBoundLocation, lastBoundGlId, material, pass, ShaderGlint.NO_TINT, + DrawState.liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap(), false); + final RenderLayer layer = layerFor(lastBoundLocation, inputs); // Flames carry entity_flame, which some packs may voxelize as a light source in the shadow pass final int groupId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); TessellatorStreamingDrawer.fillMissingAttributes(tess); - activeGroups.streamVertices(layer, groupId, tess.rawBuffer, tess.vertexCount, currentModelView()); + final Matrix4f modelView = currentModelView(); + if (entityFire) { + activeGroups.streamAndRecord(layer, groupId, tess.rawBuffer, tess.vertexCount, modelView, inputs); + } else { + activeGroups.streamVertices(layer, groupId, tess.rawBuffer, tess.vertexCount, modelView); + } return TessellatorRoute.QUEUE; } @@ -793,8 +983,13 @@ public final class ModelPartBatcher { entry.cubesInsideTexture = CubeParams.allInsideTexture(cubes); } - private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean lightmap) { - return layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, false); + private RenderLayer layerFor(ResourceLocation texture, EntityRenderCommands.DrawInputs inputs) { + return layerFor(texture, inputs.material, inputs.pass, inputs.offsetEnabled, inputs.offsetFactor, inputs.offsetUnits, + inputs.glintSlot, inputs.cull, inputs.lit, inputs.lightmap, inputs.afterGlint); + } + + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, boolean offsetEnabled, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean lightmap, boolean afterGlint) { + return layerFor(texture, material, pass, offsetEnabled ? offsetFactor : 0, offsetEnabled ? offsetUnits : 0, glintSlot, cullCode, lit, lightmap, afterGlint); } private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean lightmap, boolean afterGlint) { @@ -827,11 +1022,10 @@ public final class ModelPartBatcher { } public void clear() { + if (AngelicaConfig.entityShadowReplayEnabled()) EntityShadowReplay.clear(); entityFireDepth = 0; shadows.reset(); - groups.clear(); - entityGroups.clear(); - shadowGroups.clear(); + for (RetainedTesrGroups group : allGroups) group.clear(); templates.clear(); entitySource.discard(); bufferSource.discard(); @@ -852,7 +1046,7 @@ public final class ModelPartBatcher { } public String getDebugString() { - final String line = String.format("Parts: %d grp, inst %d, live %d", groups.groupCount() + entityGroups.groupCount() + shadowGroups.groupCount(), parts - lastParts, liveFallbacks - lastLiveFallbacks); + final String line = String.format("Parts: %d grp, inst %d, live %d", sumGroups(RetainedTesrGroups::groupCount), parts - lastParts, liveFallbacks - lastLiveFallbacks); lastParts = parts; lastLiveFallbacks = liveFallbacks; return line; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/Pool.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/Pool.java new file mode 100644 index 000000000..484d738f7 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/Pool.java @@ -0,0 +1,36 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** Reuses per-frame objects. */ +final class Pool { + private final ObjectArrayList entries = new ObjectArrayList<>(); + private final Supplier factory; + private final Consumer reset; + private int used; + + Pool(Supplier factory, Consumer reset) { + this.factory = factory; + this.reset = reset; + } + + T acquire() { + if (used == entries.size()) entries.add(factory.get()); + return entries.get(used++); + } + + int size() { return used; } + + void clear() { + for (int i = 0; i < used; i++) reset.accept(entries.get(i)); + used = 0; + } + + void release() { + clear(); + entries.clear(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java index 9f751a208..4497acf8c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java @@ -48,6 +48,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { private final Matrix4f baseMV = new Matrix4f(); private final Matrix4f baseMVInv = new Matrix4f(); private final Matrix4f scratchMat = new Matrix4f(); + private final Matrix4f replayModelView = new Matrix4f(); private final Vector3f scratchVec = new Vector3f(); private final Matrix4f drawMV = new Matrix4f(); private final Matrix4f savedMV = new Matrix4f(); @@ -95,6 +96,31 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { final IntArrayList uploadCounts = new IntArrayList(); } + static final class InstanceRange { + InstanceColumns columns; + TexRun run; + int start, end; + boolean reuseUpload; + + void set(InstanceColumns columns, TexRun run, int start, int end) { + this.columns = columns; + this.run = run; + this.start = start; + this.end = end; + } + + void reset() { + columns = null; + run = null; + start = end = 0; + } + + void clear() { + reset(); + reuseUpload = false; + } + } + static final class InstanceColumns { final ObjectArrayList templates = new ObjectArrayList<>(); final ObjectArrayList cubes = new ObjectArrayList<>(); @@ -109,17 +135,20 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { float[] matrices = new float[16 * 64]; int size; int referencedParts; + long version; boolean hasInstances() { return size > 0 || referencedParts > 0; } + private void reserveMatrices(int count) { + final int need = (size + count) * 16; + if (need > matrices.length) matrices = Arrays.copyOf(matrices, Math.max(need, matrices.length << 1)); + } + void add(TemplateBuffer templateOrNull, Matrix4fc mv, int light, int color, int overlay, long info) { - final int base = size * 16; - if (base + 16 > matrices.length) { - matrices = Arrays.copyOf(matrices, matrices.length << 1); - } - mv.get(matrices, base); + reserveMatrices(1); + mv.get(matrices, size * 16); if (templateOrNull != null) templates.add(templateOrNull); lights.add(light); colors.add(color); @@ -136,6 +165,10 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { return run.source != null ? null : atlasSlot(i); } + Matrix4f pose(int i, Matrix4f dest) { + return dest.set(matrices, i * 16); + } + void addCubes(TemplateBuffer templateOrNull, CubeParams[] cubeParams, float scale, Matrix4fc mv, int light, int color, int overlay, long info, EntityTextureAtlas.Slot atlasSlot) { cubes.add(cubeParams); atlasSlots.add(atlasSlot); @@ -146,17 +179,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { void appendRange(InstanceColumns src, int start, int end, int light, int color, int overlay) { final int n = end - start; - final int need = (size + n) * 16; - if (need > matrices.length) { - matrices = Arrays.copyOf(matrices, Math.max(need, matrices.length << 1)); - } + reserveMatrices(n); System.arraycopy(src.matrices, start * 16, matrices, size * 16, n * 16); if (src.templates.size() == src.size) { for (int i = start; i < end; i++) templates.add(src.templates.get(i)); } if (src.cubes.size() == src.size) { for (int i = start; i < end; i++) cubes.add(src.cubes.get(i)); - atlasSlots.size(atlasSlots.size() + n); + atlasSlots.size(size + n); scales.addElements(scales.size(), src.scales.elements(), start, n); } fill(lights, n, light); @@ -166,6 +196,52 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { size += n; } + void appendReplayRange(InstanceColumns src, int start, int end, Matrix4fc transform, EntityTextureAtlas.Slot atlasSlot) { + final int n = end - start; + reserveMatrices(n); + // Modelview matrices are affine, so only the 3x4 upper part needs multiplying. + // Also, JOML would copy each matrix into a Matrix4f and back out, so this is faster to do by hand + final float t00 = transform.m00(), t01 = transform.m01(), t02 = transform.m02(); + final float t10 = transform.m10(), t11 = transform.m11(), t12 = transform.m12(); + final float t20 = transform.m20(), t21 = transform.m21(), t22 = transform.m22(); + final float t30 = transform.m30(), t31 = transform.m31(), t32 = transform.m32(); + final float[] s = src.matrices; + final float[] d = matrices; + for (int in = start * 16, out = size * 16, stop = end * 16; in < stop; in += 16, out += 16) { + for (int c = 0; c < 12; c += 4) { + final float x = s[in + c], y = s[in + c + 1], z = s[in + c + 2]; + d[out + c] = t00 * x + t10 * y + t20 * z; + d[out + c + 1] = t01 * x + t11 * y + t21 * z; + d[out + c + 2] = t02 * x + t12 * y + t22 * z; + d[out + c + 3] = 0.0f; + } + final float x = s[in + 12], y = s[in + 13], z = s[in + 14]; + d[out + 12] = t00 * x + t10 * y + t20 * z + t30; + d[out + 13] = t01 * x + t11 * y + t21 * z + t31; + d[out + 14] = t02 * x + t12 * y + t22 * z + t32; + d[out + 15] = 1.0f; + } + appendObjects(templates, src.templates, start, n); + lights.addElements(lights.size(), src.lights.elements(), start, n); + colors.addElements(colors.size(), src.colors.elements(), start, n); + overlays.addElements(overlays.size(), src.overlays.elements(), start, n); + infos.addElements(infos.size(), src.infos.elements(), start, n); + if (!src.cubes.isEmpty()) { + appendObjects(cubes, src.cubes, start, n); + scales.addElements(scales.size(), src.scales.elements(), start, n); + atlasSlots.size(size + n); + if (atlasSlot != null) { + Arrays.fill(atlasSlots.elements(), size, size + n, atlasSlot); + anyAtlasSlot = true; + } + } + size += n; + } + + private static void appendObjects(ObjectArrayList dst, ObjectArrayList src, int start, int count) { + dst.addElements(dst.size(), src.elements(), start, count); + } + private static void fill(IntArrayList list, int n, int value) { final int from = list.size(); list.size(from + n); @@ -173,6 +249,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void clear() { + version++; templates.clear(); cubes.clear(); atlasSlots.clear(); @@ -464,11 +541,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { return head; } - void replayRange(InstanceColumns cols, TexRun original, int start, int end, int instances, Matrix4f matrix) { - replayRange(cols, original, start, end, instances, matrix, false); - } - - void replayRange(InstanceColumns cols, TexRun original, int start, int end, int instances, Matrix4f matrix, boolean stableMatrix) { + private void replayRange(InstanceColumns cols, TexRun original, int start, int end, int instances, Matrix4f matrix, boolean stableMatrix) { TexRun head = null; for (int i = cols.runs.size() - 1; i >= 0; i--) { final TexRun candidate = cols.runs.get(i); @@ -680,6 +753,17 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void streamVertices(RenderLayer layer, int id, int[] packed, int vertexCount, Matrix4fc mv) { + EntityShadowReplay.rejectForeignDraw(); + storeVertices(layer, id, packed, vertexCount, mv); + } + + void streamAndRecord(RenderLayer layer, int id, int[] packed, int vertexCount, Matrix4fc mv, EntityRenderCommands.DrawInputs inputs) { + final boolean record = recordsEntitySubmission(inputs); + storeVertices(layer, id, packed, vertexCount, mv); + if (record) EntityShadowReplay.recordStream(mv, packed, vertexCount, id, inputs); + } + + private void storeVertices(RenderLayer layer, int id, int[] packed, int vertexCount, Matrix4fc mv) { if (glintCapture != null) glintCapture.invalidate(); source.getBuffer(layer, id).addPackedVertices(packed, vertexCount, mv, scratchVec); streamedInstances++; @@ -694,6 +778,42 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void queue(long scope, TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot) { + EntityShadowReplay.rejectForeignDraw(); + storeModel(scope, template, cubes, scale, layer, material, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, id, texMatrix, atlasSlot, null); + } + + void queueAndRecord(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, Matrix4f currentMV, + int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix, + EntityTextureAtlas.Slot atlasSlot, boolean cubesInsideTexture, EntityRenderCommands.DrawInputs inputs) { + final boolean record = recordsEntitySubmission(inputs); + final InstanceColumns captured = storeModel(0, template, cubes, scale, layer, inputs.material, currentMV, packedLight, + colorABGR, overlayABGR, entityInfo, id, texMatrix, atlasSlot, null); + if (!record) return; + // Replay copies templates by index, so a range can only be shared when every instance has one. + final InstanceColumns source = captured != null && captured.templates.size() == captured.size ? captured : null; + final EntityRenderCommands.Model entry = EntityShadowReplay.recordModel(source, layer, inputs, id, cubesInsideTexture, currentMV, texMatrix); + if (entry != null && source == null) { + entry.instance.set(template, packedLight, colorABGR, overlayABGR, entityInfo); + entry.cubes = cubes; + entry.scale = scale; + } + } + + private boolean recordsEntitySubmission(EntityRenderCommands.DrawInputs inputs) { + if (!EntityShadowReplay.isRecording()) return false; + if (!ModelPartBatcher.INSTANCE.recordsEntitySubmissions(this)) { + EntityShadowReplay.rejectForeignDraw(); + return false; + } + GLStateManager.requireExitTextureFilter(inputs.textureId, inputs.material.isUnfilteredAtlas()); + return true; + } + + private boolean keepsBaseUpload(InstanceRange replayed) { + return replayed != null && replayed.reuseUpload || glintCapture != null && glintCapture.keepsBaseUpload(); + } + + private InstanceColumns storeModel(long scope, TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot, InstanceRange replayed) { final Group group = groupFor(layer, material, id); touch(group, layer); if (group.couplable) linkDepthScope(group, scope); @@ -704,7 +824,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { if (group.probe != null && group.probe.probing && (instancedPath || segments)) { probe(group, template, currentMV, packedLight, colorABGR, texMatrix); } - final boolean capturingBase = glintCapture != null && glintCapture.capturesBase(); + final boolean capturingBase = keepsBaseUpload(replayed); if (instancedPath && cubes != null && material.shader() == null) { final TexRun run = group.openOrExtendRun(group.cubeColumns, texMatrix, false, capturingBase && group.opaque); group.cubeColumns.addCubes(deferred != null ? template : null, cubes, scale, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, atlasSlot); @@ -712,7 +832,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { run.parts++; run.instances += cubes.length; if (glintCapture != null) glintCapture.record(group, group.cubeColumns, run, group.cubeColumns.size - 1, group.cubeColumns.size, cubes.length); - return; + if (replayed != null) replayed.set(group.cubeColumns, run, group.cubeColumns.size - 1, group.cubeColumns.size); + return deferred != null ? group.cubeColumns : null; } if (instancedPath) { final TexRun run = group.openOrExtendRun(group.templateColumns, texMatrix, false, capturingBase && group.opaque); @@ -721,13 +842,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { run.parts++; run.instances++; if (glintCapture != null) glintCapture.record(group, group.templateColumns, run, group.templateColumns.size - 1, group.templateColumns.size, 1); - return; + if (replayed != null) replayed.set(group.templateColumns, run, group.templateColumns.size - 1, group.templateColumns.size); + return group.templateColumns; } if (group.stream && glintCapture != null) glintCapture.invalidate(); if (segments) { source.getBuffer(layer, id).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); streamedInstances++; - return; + return null; } if (!group.stream) { final DepthEqualSet set = activeDepthEqualSet(group); @@ -747,6 +869,62 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { if (!group.dirty && !group.snapshot.matches(index, template, cols.matrices, index * 16, packedLight, colorABGR, bakedTexMatrix)) { group.dirty = true; } + return null; + } + + void replayInstances(InstanceColumns src, int start, int end, RenderLayer layer, TesrMaterial material, int id, + Matrix4fc transform, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot, InstanceRange replayed) { + if (replayed != null) replayed.reset(); + final boolean cubes = !src.cubes.isEmpty(); + final Group group = streamsInstanced(material) && (!cubes || material.shader() == null) ? groupFor(layer, material, id) : null; + if (group != null) touch(group, layer); + if (group != null && drawsInstanced(group) && (group.probe == null || !group.probe.probing)) { + group.queuedThisFrame = true; + final InstanceColumns dst = cubes ? group.cubeColumns : group.templateColumns; + final TexRun run = group.openOrExtendRun(dst, texMatrix, false, keepsBaseUpload(replayed) && group.opaque); + final int first = dst.size; + dst.appendReplayRange(src, start, end, transform, atlasSlot); + run.last.end = dst.size; + run.parts += end - start; + final int instances = instanceCount(src, start, end, cubes); + run.instances += instances; + if (glintCapture != null) glintCapture.record(group, dst, run, first, dst.size, instances); + if (replayed != null) replayed.set(dst, run, first, dst.size); + } else { + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + state.pushEntityState(); + try { + for (int i = start; i < end; i++) { + transform.mul(src.pose(i, replayModelView), replayModelView); + storeReplay(src.templates.get(i), cubes ? src.cubes.get(i) : null, cubes ? src.scales.getFloat(i) : 1, + layer, material, replayModelView, src.lights.getInt(i), src.colors.getInt(i), src.overlays.getInt(i), + src.infos.getLong(i), id, texMatrix, atlasSlot, null); + } + } finally { + state.popEntityState(); + } + } + } + + void queueReplay(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, + Matrix4f modelView, int light, int color, int overlay, long entityInfo, int id, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot, InstanceRange replayed) { + if (replayed != null) replayed.reset(); + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + state.pushEntityState(); + try { + storeReplay(template, cubes, scale, layer, material, modelView, light, color, overlay, entityInfo, id, texMatrix, atlasSlot, replayed); + } finally { + state.popEntityState(); + } + } + + private void storeReplay(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, + Matrix4f modelView, int light, int color, int overlay, long entityInfo, int id, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot, InstanceRange replayed) { + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + state.setCurrentEntityAndItem(InstancedAttribs.unpackId(entityInfo, 0), InstancedAttribs.unpackId(entityInfo, 32)); + state.setCurrentBlockEntity(InstancedAttribs.unpackId(entityInfo, 16)); + AngelicaBufferSource.setEntityColor(overlay); + storeModel(0, template, cubes, scale, layer, material, modelView, light, color, overlay, entityInfo, id, texMatrix, atlasSlot, replayed); } private void linkDepthScope(Group group, long scope) { @@ -888,6 +1066,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void copyInstances(InstanceColumns src, int start, int end, RenderLayer layer, TesrMaterial material, int packedLight, int colorABGR, int overlayABGR, Matrix4f texMatrix) { + EntityShadowReplay.rejectForeignDraw(); final Group group = groupFor(layer, material, 0); touch(group, layer); final boolean cubes = !src.cubes.isEmpty(); @@ -907,6 +1086,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void referenceInstances(InstanceColumns src, int start, int end, RenderLayer layer, TesrMaterial material, int colorABGR, Matrix4f texMatrix) { + EntityShadowReplay.rejectForeignDraw(); final Group group = groupFor(layer, material, 0); touch(group, layer); final boolean cubes = !src.cubes.isEmpty(); @@ -921,6 +1101,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void referenceGlintLayers(InstanceColumns src, TexRun sourceRun, int start, int end, RenderLayer layer, TesrMaterial material, int colorABGR, Matrix4f first, Matrix4f second) { + EntityShadowReplay.rejectForeignDraw(); final Group group = groupFor(layer, material, 0); touch(group, layer); final boolean cubes = !src.cubes.isEmpty(); @@ -935,6 +1116,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void queueGlintLayers(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, Matrix4f first, Matrix4f second) { + EntityShadowReplay.rejectForeignDraw(); final Group group = groupFor(layer, material, 0); touch(group, layer); final InstanceColumns dst = group.templateColumns; @@ -947,6 +1129,11 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { group.replayRange(dst, run, index, index + 1, 1, second, true); } + void replayRange(Group group, InstanceColumns columns, TexRun original, int start, int end, int instances, Matrix4f matrix) { + EntityShadowReplay.rejectForeignDraw(); + group.replayRange(columns, original, start, end, instances, matrix, false); + } + private static int instanceCount(InstanceColumns src, int start, int end, boolean cubes) { if (!cubes) return end - start; int instances = 0; @@ -1439,6 +1626,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { void clear() { for (final ObjectArrayList list : byLayer.values()) { for (int i = 0, n = list.size(); i < n; i++) { + list.get(i).clearInstances(); list.get(i).mesh.delete(); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java index b18d06e5e..01d5d91ec 100644 --- a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java +++ b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java @@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.GlintColorHandler; import com.gtnewhorizons.angelica.iris.IrisDisplayListState; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import it.unimi.dsi.fastutil.ints.Int2IntLinkedOpenHashMap; import net.coderbot.iris.pipeline.ShadowRenderer; import net.irisshaders.iris.api.v0.IrisApi; @@ -58,6 +59,7 @@ public final class ShaderGlint { private ShaderGlint() {} public static void beginGlint() { + if (ShadowRenderer.ACTIVE) EntityShadowReplay.rejectShadowOnly(); IrisDisplayListState.recordGlintSpan(true); // If a glint span is already active, keep the outer span's saved state and @@ -120,7 +122,12 @@ public final class ShaderGlint { } public static void bindTintedGlint(int slot) { - if (slot < 0 || ShadowRenderer.ACTIVE || !IrisApi.getInstance().isShaderPackInUse()) return; + if (slot < 0) return; + if (ShadowRenderer.ACTIVE) { + EntityShadowReplay.rejectShadowOnly(); + return; + } + if (!IrisApi.getInstance().isShaderPackInUse()) return; final ITextureObject mask = Minecraft.getMinecraft().getTextureManager().getTexture(GLINT_MASK); if (mask == null || GLStateManager.getBoundTextureForServerState() != mask.getGlTextureId()) return; GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, slotTextures[slot]); diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java index 7e5a73da3..88ee2ce74 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java @@ -205,17 +205,13 @@ public class AngelicaBufferSource implements Groupable { private void restoreIrisState() { if (!irisStateSaved) return; - CapturedRenderingState.INSTANCE.popCurrentEntityColor(); - CapturedRenderingState.INSTANCE.popCurrentBlockEntity(); - CapturedRenderingState.INSTANCE.popCurrentEntityAndItem(); + CapturedRenderingState.INSTANCE.popEntityState(); irisStateSaved = false; } private void saveIrisState() { if (irisStateSaved) return; - CapturedRenderingState.INSTANCE.pushCurrentEntityAndItem(); - CapturedRenderingState.INSTANCE.pushCurrentBlockEntity(); - CapturedRenderingState.INSTANCE.pushCurrentEntityColor(); + CapturedRenderingState.INSTANCE.pushEntityState(); irisStateSaved = true; } diff --git a/src/main/java/net/coderbot/iris/gl/program/Program.java b/src/main/java/net/coderbot/iris/gl/program/Program.java index 7e4f3d807..3302d58c7 100644 --- a/src/main/java/net/coderbot/iris/gl/program/Program.java +++ b/src/main/java/net/coderbot/iris/gl/program/Program.java @@ -42,12 +42,17 @@ public final class Program extends GlResource { } public void use() { - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); - bindManaged(getGlId()); + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); + bindManaged(getGlId()); - uniforms.update(); - samplers.update(); - images.update(); + uniforms.update(); + samplers.update(); + images.update(); + } finally { + GLStateManager.resumeExitCapture(suspended); + } } static void bindManaged(int program) { @@ -61,9 +66,14 @@ public final class Program extends GlResource { } public static void unbind() { - ProgramUniforms.clearActiveUniforms(); - ProgramSamplers.clearActiveSamplers(); - GLStateManager.glUseProgram(0); + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + ProgramUniforms.clearActiveUniforms(); + ProgramSamplers.clearActiveSamplers(); + GLStateManager.glUseProgram(0); + } finally { + GLStateManager.resumeExitCapture(suspended); + } } @Override diff --git a/src/main/java/net/coderbot/iris/layer/PassOverride.java b/src/main/java/net/coderbot/iris/layer/PassOverride.java index 10285d543..1216e3177 100644 --- a/src/main/java/net/coderbot/iris/layer/PassOverride.java +++ b/src/main/java/net/coderbot/iris/layer/PassOverride.java @@ -1,5 +1,6 @@ package net.coderbot.iris.layer; +import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.pipeline.WorldRenderingPhase; @@ -60,6 +61,11 @@ public final class PassOverride { return phase == WorldRenderingPhase.ENTITIES; } + public RenderCondition entityCondition(boolean defaultTranslucent) { + if (special != null || phase != null && phase != WorldRenderingPhase.ENTITIES) return null; + return (translucent != null ? translucent : defaultTranslucent) ? RenderCondition.ENTITIES_TRANSLUCENT : RenderCondition.ENTITIES; + } + public String nameSuffix() { if (special == null && translucent == null && phase == null) { return ""; diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 627fb2042..822090bb6 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -1437,10 +1437,24 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R void rebindProgram() { if (program != null) program.use(); - DeferredWorldRenderingPipeline.this.customUniforms.push(this); + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + DeferredWorldRenderingPipeline.this.customUniforms.push(this); + } finally { + GLStateManager.resumeExitCapture(suspended); + } } private void useNow() { + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + applyState(); + } finally { + GLStateManager.resumeExitCapture(suspended); + } + } + + private void applyState() { DepthColorStorage.unlockDepthColor(); if (isBeforeTranslucent) { @@ -1485,14 +1499,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } public void stopUsing() { - DepthColorStorage.unlockDepthColor(); + final boolean suspended = GLStateManager.suspendExitCapture(); + try { + DepthColorStorage.unlockDepthColor(); - if (alphaTestOverride != null) { - AlphaTestOverride.restore(); - } + if (alphaTestOverride != null) { + AlphaTestOverride.restore(); + } - if (blendModeOverride != null || (bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty())) { - BlendModeOverride.restore(); + if (blendModeOverride != null || (bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty())) { + BlendModeOverride.restore(); + } + } finally { + GLStateManager.resumeExitCapture(suspended); } } @@ -1604,6 +1623,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return current != null && current.instancedVariant(kind) != null; } + public boolean hasInstancedVariant(RenderCondition condition, InputAvailability availability, Instancing kind) { + final Pass pass = table.match(condition, availability); + return pass != null && pass.instancedVariant(kind) != null; + } + @Override public void bindInstancedVariant(Instancing kind) { activeInstancing = kind; @@ -2496,25 +2520,34 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void onBindTexture(int id) { if (shouldBindPBR && isRenderingWorld) { - final PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); - currentNormalTexture = pbrHolder.getNormalTexture().getGlTextureId(); - currentSpecularTexture = pbrHolder.getSpecularTexture().getGlTextureId(); - - BatchStateGuard.suspend(); + final boolean suspended = GLStateManager.suspendExitCapture(); try { - final TextureFormat textureFormat = TextureFormatLoader.getFormat(); - if (textureFormat != null) { - textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); - textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); - } - - PBRTextureManager.notifyPBRTexturesChanged(); + updatePbrTextures(id); } finally { - BatchStateGuard.resume(); + GLStateManager.resumeExitCapture(suspended); } } } + private void updatePbrTextures(int id) { + final PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); + currentNormalTexture = pbrHolder.getNormalTexture().getGlTextureId(); + currentSpecularTexture = pbrHolder.getSpecularTexture().getGlTextureId(); + + BatchStateGuard.suspend(); + try { + final TextureFormat textureFormat = TextureFormatLoader.getFormat(); + if (textureFormat != null) { + textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); + textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); + } + + PBRTextureManager.notifyPBRTexturesChanged(); + } finally { + BatchStateGuard.resume(); + } + } + private static CompletableFuture> submitCompositeTransform(ProgramSource source, TextureStage stage, Object2ObjectMap, String> textureMap) { return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite( diff --git a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java index 1418651b2..266653cc9 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java @@ -9,6 +9,7 @@ import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.profiling.RenderClassTimings; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws; import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; @@ -590,9 +591,12 @@ public class ShadowRenderer { } for (Entity entity : renderedEntitiesList) { final long start = Tracy.ENABLED ? System.nanoTime() : 0L; + final boolean recording = AngelicaConfig.entityShadowReplayEnabled() && EntityShadowReplay.beginEntity(entity, tickDelta); + boolean completed = false; try { - RenderManager.instance.renderEntitySimple(entity, tickDelta); + completed = RenderManager.instance.renderEntitySimple(entity, tickDelta); } finally { + if (recording) EntityShadowReplay.endEntity(completed); if (Tracy.ENABLED) RenderClassTimings.SHADOW_ENTITY.add(entity.getClass(), System.nanoTime() - start); } } diff --git a/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java b/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java index 25b10c0fd..4bafe8094 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java +++ b/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java @@ -161,6 +161,18 @@ public class CapturedRenderingState { applyCurrentEntityColor(r, g, b, a); } + public void pushEntityState() { + pushCurrentEntityAndItem(); + pushCurrentBlockEntity(); + pushCurrentEntityColor(); + } + + public void popEntityState() { + popCurrentEntityColor(); + popCurrentBlockEntity(); + popCurrentEntityAndItem(); + } + private void applyCurrentEntityColor(float r, float g, float b, float a) { if (currentEntityColor.equals(r, g, b, a)) return; this.currentEntityColor.set(r, g, b, a); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java index fe8f44463..a231b8fc4 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java @@ -1,8 +1,10 @@ package com.gtnewhorizons.angelica.mixins.early.angelica; +import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.hooks.FrameHooks; import com.gtnewhorizons.angelica.rendering.GlintClock; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -27,8 +29,9 @@ public class MixinMinecraft_FrameHook { } @Inject(method = "runGameLoop", at = @At("HEAD")) - private void angelica$beginGlintFrame(CallbackInfo ci) { + private void angelica$beginRenderFrame(CallbackInfo ci) { GlintClock.beginFrame(Minecraft.getSystemTime()); + if (AngelicaConfig.entityShadowReplayEnabled()) EntityShadowReplay.beginFrame(); } @Inject(method = "func_147120_f"/*resetSize*/, at = @At("HEAD")) diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinBossStatus_EntityReplay.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinBossStatus_EntityReplay.java new file mode 100644 index 000000000..56028a899 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinBossStatus_EntityReplay.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; +import net.minecraft.entity.boss.BossStatus; +import net.minecraft.entity.boss.IBossDisplayData; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(BossStatus.class) +public class MixinBossStatus_EntityReplay { + @Surround(method = "setBossStatus") + private static void angelica$observeBossStatus() { + } + + @Surround.Return + private static void angelica$recordBossStatus(IBossDisplayData boss, boolean colorModifier) { + EntityShadowReplay.recordBossStatus(boss, colorModifier); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityReplay.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityReplay.java new file mode 100644 index 000000000..b837ceb14 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderGlobal_EntityReplay.java @@ -0,0 +1,28 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; +import net.minecraft.client.renderer.RenderGlobal; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; +import net.minecraftforge.client.MinecraftForgeClient; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Slice; + +@Mixin(value = RenderGlobal.class, priority = 900) // Lower priority due to Tracy +public class MixinRenderGlobal_EntityReplay { + @Surround(method = "renderEntities", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z"), + slice = @Slice( + from = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=entities"), + to = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", args = "ldc=blockentities"))) + private void angelica$replayEntity(RenderManager manager, Entity entity, float partialTicks) { + @Surround.Skip final boolean replayed = EntityShadowReplay.replay(manager, entity, partialTicks, MinecraftForgeClient.getRenderPass()); + } + + @Surround.Skipped + private boolean angelica$entityReplayed() { + return true; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderManager_BatchEligibility.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderManager_BatchEligibility.java index a1b6096fc..1571869d9 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderManager_BatchEligibility.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderManager_BatchEligibility.java @@ -1,8 +1,10 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.entity; +import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.IBatchEligibility; import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; @@ -17,11 +19,15 @@ public class MixinRenderManager_BatchEligibility { private void angelica$observeDoRender(Render render, Entity entity, double x, double y, double z, float yaw, float partialTicks) { final IBatchEligibility holder = (IBatchEligibility) render; final byte state = holder.angelica$batchState(); + final boolean recording = AngelicaConfig.entityShadowReplayEnabled() && EntityShadowReplay.beginRenderer(render, entity, partialTicks, state); BatchEligibility.begin(state, GLStateManager.drawCalls); + boolean completed = false; try { render.doRender(entity, x, y, z, yaw, partialTicks); + completed = true; } finally { final byte next = BatchEligibility.end(state, GLStateManager.drawCalls); + if (recording) EntityShadowReplay.endRenderer(completed, next); if (next != state) { holder.angelica$setBatchState(next); BatchEligibility.onStateChange(render, next); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_NameTagDraws.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_NameTagDraws.java index f4ac7de25..b4e36d542 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_NameTagDraws.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_NameTagDraws.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.entity; import com.gtnewhorizons.angelica.experimental.surround.Surround; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import net.minecraft.client.renderer.entity.Render; import org.spongepowered.asm.mixin.Mixin; @@ -12,6 +13,7 @@ public abstract class MixinRender_NameTagDraws { @Surround(method = "func_147906_a") private void angelica$countNameTagDraws() { + EntityShadowReplay.rejectForeignDraw(); BatchEligibility.beginExpectedDraws(GLStateManager.drawCalls); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java index 4576b7b4c..bcfb7dbfe 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java @@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.helpers.RendererLivingEntityHelper; import com.gtnewhorizons.angelica.rendering.GlintClock; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import com.gtnewhorizons.angelica.rendering.tesr.GlintCapture; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; @@ -142,6 +143,7 @@ public abstract class MixinRendererLivingEntity_GlintClock { @Inject(method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lorg/apache/logging/log4j/Logger;error(Ljava/lang/String;Ljava/lang/Throwable;)V", remap = false)) private void angelica$closeAfterFailedRender(CallbackInfo ci) { + EntityShadowReplay.rejectRenderFailed(); if (angelica$capturingBase) { angelica$capturingBase = false; GLStateManager.glPopMatrix(); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java index 58d10be36..3d3e2655f 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java @@ -1,9 +1,11 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; import com.gtnewhorizons.angelica.compat.mojang.Camera; +import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.experimental.surround.Surround; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; +import com.gtnewhorizons.angelica.rendering.tesr.EntityShadowReplay; import com.llamalad7.mixinextras.sugar.Local; import jss.notfine.core.SettingsManager; import net.coderbot.iris.Iris; @@ -88,6 +90,7 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe if (renderer != null) { renderer.setShadowPassPlayerViewport(((ViewportProvider) playerFrustum).sodium$createViewport()); } + if (AngelicaConfig.entityShadowReplayEnabled()) EntityShadowReplay.setMainView(playerFrustum); Iris.getPipelineManager().getPipelineNullable().renderShadows((EntityRenderer) (Object) this, Camera.INSTANCE); } diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplayGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplayGLTest.java new file mode 100644 index 000000000..df275e8f0 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowReplayGLTest.java @@ -0,0 +1,1696 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.StateSet; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.rendering.DeferredEntityOverlay; +import com.gtnewhorizons.angelica.rendering.GlintClock; +import com.gtnewhorizons.angelica.rendering.SkippedGlintBlock; +import com.gtnewhorizons.angelica.rendering.items.ItemGlint; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.BufferSegment; +import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder; +import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition; +import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.layer.PassOverride; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.pipeline.ShadowRenderer; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.coderbot.iris.uniforms.CapturedStateScope; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.client.renderer.entity.RenderCreeper; +import net.minecraft.client.renderer.entity.RenderDragon; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.client.renderer.entity.RenderWither; +import net.minecraft.client.renderer.entity.RendererLivingEntity; +import net.minecraft.entity.DataWatcher; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.SharedMonsterAttributes; +import net.minecraft.entity.ai.attributes.IAttributeInstance; +import net.minecraft.entity.boss.BossStatus; +import net.minecraft.entity.boss.EntityDragon; +import net.minecraft.entity.boss.EntityWither; +import net.minecraft.entity.boss.IBossDisplayData; +import net.minecraft.entity.monster.EntityCreeper; +import net.minecraft.entity.monster.EntityZombie; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; + +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.cubes; +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.onlyGroup; +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.template; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +@GLCoreTest +class EntityShadowReplayGLTest { + private static final float TICK_DELTA = 0.25f; + private final Entity entity = mock(Entity.class); + private final Render renderer = mock(Render.class); + private final RenderManager manager = mock(RenderManager.class); + private final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE; + private final Matrix4f shadowView = new Matrix4f().rotateXYZ(0.6f, -0.7f, 0.2f).translate(4, -2, 5); + private final Matrix4f mainView = new Matrix4f().rotateXYZ(-0.1f, 0.8f, 0); + private final Matrix4f model = new Matrix4f().translation(3, 2, -6).rotateY(0.7f).scale(0.5f); + private final Matrix4f captureEntry = new Matrix4f(); + private boolean captureOpen, capturePoseOpen; + private RetainedTesrGroups target; + private long previousGlintTime; + private boolean previousBatching, previousReplay, previousAtlas, previousShadow; + private String[] previousExcluded; + + private static void applyGlintExit(String kind) { + switch (kind) { + case "armor" -> SkippedGlintBlock.applyArmorExitState(); + case "held" -> SkippedGlintBlock.applyHeldItemExitState(); + case "dropped" -> SkippedGlintBlock.applyDroppedItemExitState(); + default -> throw new AssertionError(kind); + } + } + + private static ObjectArrayList glintBases() { + final ObjectArrayList bases = new ObjectArrayList<>(); + for (EntityRenderCommands.Command command : commands()) { + if (command instanceof EntityRenderCommands.Model model && model.glint != null) bases.add(model); + } + assertFalse(bases.isEmpty()); + return bases; + } + + private static void assertGlintLayers(RetainedTesrGroups.Group glint, Matrix4f first, Matrix4f second, + TemplateBuffer[] templates, Matrix4f[] matrices, long info, int overlay) { + assertGlintLayers(glint, first, second, templates, matrices, info, overlay, true); + } + + private static void assertGlintLayers(RetainedTesrGroups.Group glint, Matrix4f first, Matrix4f second, + TemplateBuffer[] templates, Matrix4f[] matrices, long info, int overlay, boolean ordered) { + final RetainedTesrGroups.InstanceColumns columns = glint.templateColumns.hasInstances() ? glint.templateColumns : glint.cubeColumns; + final int color = AngelicaBufferSource.packAbgr(0.5f * 0.76f, 0.25f * 0.76f, 0.8f * 0.76f, 1); + for (Matrix4f textureMatrix : new Matrix4f[]{first, second}) { + int matched = 0; + final boolean[] seen = new boolean[templates.length]; + for (RetainedTesrGroups.TexRun head : columns.runs) { + assertTrue(first.equals(head.matrix, 0) || second.equals(head.matrix, 0), "unexpected glint layer"); + if (!textureMatrix.equals(head.matrix, 0)) continue; + final RetainedTesrGroups.InstanceColumns source = head.source != null ? head.source : columns; + for (RetainedTesrGroups.TexRun run = head; run != null; run = run.next) { + for (int i = run.start; i < run.end; i++) { + assertTrue(matched < templates.length, "glint must not include uncaptured body parts"); + final int expected = ordered ? matched : Arrays.asList(templates).indexOf(source.templates.get(i)); + assertTrue(expected >= 0, "glint must only include the captured parts"); + assertFalse(seen[expected], "a glint layer must not repeat a captured part"); + seen[expected] = true; + assertSame(templates[expected], source.templates.get(i)); + assertTrue(matrices[expected].equals(new Matrix4f().set(source.matrices, i * 16), 0.00001f)); + assertEquals(info, source.infos.getLong(i)); + assertEquals(overlay, source.overlays.getInt(i)); + assertEquals(color, head.source != null ? head.color : source.colors.getInt(i)); + matched++; + } + } + } + assertEquals(templates.length, matched, "both glint layers must cover every captured armor/item part"); + } + } + + private static void assertGlintMatchesBase(RetainedTesrGroups.Group glint, RetainedTesrGroups.InstanceColumns base) { + final RetainedTesrGroups.TexRun head = glint.templateColumns.runs.getFirst(); + final RetainedTesrGroups.InstanceColumns source = head.source != null ? head.source : glint.templateColumns; + int part = 0; + for (RetainedTesrGroups.TexRun run = head; run != null; run = run.next) { + for (int i = run.start; i < run.end; i++) { + assertArrayEquals(Arrays.copyOfRange(base.matrices, part * 16, (part + 1) * 16), + Arrays.copyOfRange(source.matrices, i * 16, (i + 1) * 16), + "depth-equal item glint must use the exact replayed base matrix"); + part++; + } + } + assertEquals(base.size, part); + } + + private static BufferSegment onlyStreamSegment(RetainedTesrGroups groups) { + final AngelicaBufferSource source = Reflect.get(groups, "source"); + final SegmentedBufferBuilder[] builders = Reflect.get(source, "builders"); + final var segments = Arrays.stream(builders).flatMap(builder -> builder.getSegments().stream()).toList(); + assertEquals(1, segments.size()); + return segments.getFirst(); + } + + private static long rejections(EntityShadowReplay.Rejection reason) { + final long[] rejected = Reflect.getStatic(EntityShadowReplay.class, "rejected"); + return rejected[reason.ordinal()]; + } + + private static ObjectArrayList commands() { + final EntityRenderCommands commands = Reflect.getStatic(EntityShadowReplay.class, "commands"); + return Reflect.get(commands, "commands"); + } + + private static EntityWither wither(String name, float health, double maxHealth) { + return boss(EntityWither.class, name, health, maxHealth); + } + + private static T boss(Class type, String name, float health, double maxHealth) { + final T boss = IBossDisplayData.class.isAssignableFrom(type) ? mock(type) + : mock(type, withSettings().extraInterfaces(IBossDisplayData.class)); + final DataWatcher watcher = mock(DataWatcher.class); + when(watcher.getWatchableObjectFloat(6)).thenReturn(health); + Reflect.set(boss, "dataWatcher", watcher); + final IAttributeInstance maximum = mock(IAttributeInstance.class); + when(maximum.getAttributeValue()).thenReturn(maxHealth); + when(boss.getEntityAttribute(SharedMonsterAttributes.maxHealth)).thenReturn(maximum); + when(boss.func_145748_c_()).thenReturn(new ChatComponentText(name)); + return boss; + } + + private static void observeBossStatus(IBossDisplayData boss, boolean colorModifier) { + BossStatus.setBossStatus(boss, colorModifier); + EntityShadowReplay.recordBossStatus(boss, colorModifier); + } + + private static void assertBossStatus(IBossDisplayData boss, boolean colorModifier) { + assertEquals(boss.getHealth() / boss.getMaxHealth(), BossStatus.healthScale); + assertEquals(100, BossStatus.statusBarTime); + assertEquals(boss.func_145748_c_().getFormattedText(), BossStatus.bossName); + assertEquals(colorModifier, BossStatus.hasColorModifier); + } + + private static void resetBossStatus() { + BossStatus.healthScale = -0.25f; + BossStatus.statusBarTime = 7; + BossStatus.bossName = "unchanged"; + BossStatus.hasColorModifier = false; + } + + private static void assertUnchangedBossStatus() { + assertEquals(-0.25f, BossStatus.healthScale); + assertEquals(7, BossStatus.statusBarTime); + assertEquals("unchanged", BossStatus.bossName); + assertFalse(BossStatus.hasColorModifier); + } + + private static void withBossStatus(Runnable action) { + final float health = BossStatus.healthScale; + final int time = BossStatus.statusBarTime; + final String name = BossStatus.bossName; + final boolean color = BossStatus.hasColorModifier; + try { + action.run(); + } finally { + BossStatus.healthScale = health; + BossStatus.statusBarTime = time; + BossStatus.bossName = name; + BossStatus.hasColorModifier = color; + } + } + + private static void assertAura(Object actual, DeferredEntityOverlay.ShouldRenderPassFn callback, + RendererLivingEntity renderer, EntityLivingBase entity, float[] args, Matrix4f matrix) { + assertSame(callback, Reflect.get(actual, "shouldRenderPass")); + assertSame(renderer, Reflect.get(actual, "renderer")); + assertSame(entity, Reflect.get(actual, "entity")); + final String[] fields = {"partialTick", "limbSwing", "limbSwingAmount", "ageInTicks", "headYaw", "headPitch", "scale"}; + for (int i = 0; i < fields.length; i++) assertEquals(args[i], (float) Reflect.get(actual, fields[i]), fields[i]); + final float[] actualMatrix = Reflect.get(actual, "matrix"); + assertTrue(matrix.equals(new Matrix4f().set(actualMatrix), 0.00001f), "deferred aura must use the main camera"); + } + + private static void withDeferredOverlays(Runnable action) { + final String[] contextFields = {"overlayPassActive", "replaying", "pendingShouldRenderPass", "pendingRenderer", "pendingEntity", "pendingPartialTick"}; + final Object[] previousContext = Arrays.stream(contextFields).map(name -> Reflect.getStatic(DeferredEntityOverlay.class, name)).toArray(); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertTrue(deferred.isEmpty()); + try { + action.run(); + } finally { + DeferredEntityOverlay.clear(); + for (int i = 0; i < contextFields.length; i++) Reflect.setStatic(DeferredEntityOverlay.class, contextFields[i], previousContext[i]); + } + } + + @BeforeEach + void setUp() { + previousBatching = AngelicaConfig.enableEntityBatching; + previousReplay = AngelicaConfig.enableEntityShadowReplay; + previousAtlas = AngelicaConfig.enableEntityTextureAtlas; + previousExcluded = AngelicaConfig.entityShadowReplayExcludedClasses; + previousShadow = ShadowRenderer.ACTIVE; + previousGlintTime = GlintClock.millis(); + AngelicaConfig.enableEntityBatching = true; + AngelicaConfig.enableEntityShadowReplay = true; + AngelicaConfig.enableEntityTextureAtlas = false; + AngelicaConfig.entityShadowReplayExcludedClasses = new String[0]; + when(manager.getEntityRenderObject(entity)).thenReturn(renderer); + EntityShadowReplay.clear(); + EntityShadowReplay.beginFrame(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.enableTexture(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.setTextureMatrix(0, new Matrix4f()); + GLStateManager.glColor4f(1, 1, 1, 1); + GLStateManager.setOverlayColor(0, 0, 0, 0); + GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(true); + ModelPartBatcher.onTextureBind(new ResourceLocation("angelica", "test/replay"), 0); + RenderManager.renderPosX = 1000000.25; + RenderManager.renderPosY = 7.74; + RenderManager.renderPosZ = -1000000.5; + RenderManager.instance.playerViewX = 6; + RenderManager.instance.playerViewY = 0; + Reflect.set(batcher, "active", true); + Reflect.set(batcher, "mode", ModelPartBatcher.Mode.ENTITIES); + Reflect.set(batcher, "shadow", true); + final AngelicaBufferSource source = new AngelicaBufferSource(); + source.setIdKind(AngelicaBufferSource.GroupIdKind.ENTITY); + target = new RetainedTesrGroups(source); + target.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(new InstanceRing()), + new RetainedTesrTestSupport.CountingPipeline(true, true)); + Reflect.set(batcher, "activeGroups", target); + GLStateManager.setModelViewMatrix(shadowView); + GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glPolygonOffset(1, 1); + ShadowRenderer.ACTIVE = true; + EntityShadowReplay.beginPass(true, 0); + } + + @AfterEach + void tearDown() { + EntityShadowReplay.clear(); + closeCapturePose(); + ShadowRenderer.ACTIVE = previousShadow; + GlintClock.beginFrame(previousGlintTime); + batcher.clear(); + AngelicaConfig.enableEntityBatching = previousBatching; + AngelicaConfig.enableEntityShadowReplay = previousReplay; + AngelicaConfig.enableEntityTextureAtlas = previousAtlas; + AngelicaConfig.entityShadowReplayExcludedClasses = previousExcluded; + } + + private void beginCapture(Entity captured) { + captureEntry.set(GLStateManager.getModelViewMatrix()); + captureOpen = !EntityShadowReplay.isExcluded(captured.getClass()) && !captured.shouldRenderInPass(1); + assertEquals(captureOpen, EntityShadowReplay.beginEntity(captured, TICK_DELTA)); + } + + private void setCapturePose(Matrix4f pose) { + closeCapturePose(); + GLStateManager.glPushMatrix(); + capturePoseOpen = true; + GLStateManager.applyMultMatrix(pose); + } + + private void closeCapturePose() { + if (!capturePoseOpen) return; + GLStateManager.glPopMatrix(); + capturePoseOpen = false; + } + + private void finishCapture(boolean completed) { + closeCapturePose(); + if (captureOpen) EntityShadowReplay.endEntity(completed); + captureOpen = false; + } + + private void capture() { + beginCapture(entity); + assertEquals(captureOpen, EntityShadowReplay.beginRenderer(renderer, entity, TICK_DELTA, BatchEligibility.SAFE)); + GLStateManager.glColor4f(1, 1, 1, 1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + setCapturePose(model); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + } + + private void endCapture() { + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + finishCapture(true); + } + + private void endCaptureAndStartMainPass() { + endCapture(); + mainPass(); + } + + private void mainPass() { + if (Reflect.getStatic(EntityShadowReplay.class, "recording") != null) finishCapture(true); + closeCapturePose(); + captureOpen = false; + DeferredEntityOverlay.clear(); + ShadowRenderer.ACTIVE = false; + Reflect.set(batcher, "shadow", false); + RenderManager.renderPosX -= 0.5; + RenderManager.renderPosY -= 0.12; + RenderManager.renderPosZ += 0.25; + GLStateManager.setModelViewMatrix(mainView); + GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glPolygonOffset(0, 0); + target = new RetainedTesrGroups(new AngelicaBufferSource()); + final AngelicaBufferSource source = Reflect.get(target, "source"); + source.setIdKind(AngelicaBufferSource.GroupIdKind.ENTITY); + target.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(new InstanceRing()), + new RetainedTesrTestSupport.CountingPipeline(true, true)); + Reflect.set(batcher, "activeGroups", target); + EntityShadowReplay.beginPass(false, 0); + } + + @Test + void replayUsesTheMainCameraAndInheritsMainEntryState() { + GLStateManager.glShadeModel(GL11.GL_SMOOTH); + capture(); + endCaptureAndStartMainPass(); + GLStateManager.glShadeModel(GL11.GL_FLAT); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.Group group = onlyGroup(target); + final Matrix4f expected = new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f).mul(model); + final Matrix4f actual = new Matrix4f().set(group.templateColumns.matrices); + assertTrue(expected.equals(actual, 0.00001f), "replay must use the main camera with the measured renderPos difference"); + assertEquals(0, group.layer.getState().getOffsetFactor()); + assertEquals(0, group.layer.getState().getOffsetUnits()); + assertTrue(group.layer.getState().isLightmap()); + assertEquals(GL11.GL_FLAT, GLStateManager.getShadeModelState().getValue()); + } + + @ParameterizedTest + @ValueSource(strings = {"inherited", "explicitNoOp", "popped"}) + void bodyLightingUsesMainInheritanceWhileGlintRemainsUnlit(String kind) { + prepareGlintCapture(); + GLStateManager.glDisable(GL11.GL_LIGHTING); + final GlintCapture armor = new GlintCapture(); + captureGlint(entity, renderer, () -> { + if (kind.equals("explicitNoOp")) { + GLStateManager.glDisable(GL11.GL_LIGHTING); + } else if (kind.equals("popped")) { + GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT); + GLStateManager.glEnable(GL11.GL_LIGHTING); + GLStateManager.glPopAttrib(); + } + setCapturePose(model); + assertTrue(batcher.beginArmorCapture(armor)); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + armor.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(armor, ItemGlint.texture())); + }); + assertFalse(onlyMaterialGroup(EntityMaterials.CUTOUT).layer.getState().isLit()); + mainPass(); + GLStateManager.glEnable(GL11.GL_LIGHTING); + + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final boolean inherited = !kind.equals("explicitNoOp"); + assertEquals(inherited, onlyMaterialGroup(EntityMaterials.CUTOUT).layer.getState().isLit()); + assertFalse(onlyMaterialGroup(EntityMaterials.GLINT).layer.getState().isLit()); + assertEquals(inherited, GLStateManager.getLightingState().isEnabled(), + "untouched or restored lighting must preserve main entry state; an explicit no-op disable must still apply"); + } + + @ParameterizedTest + @ValueSource(strings = {"enabled", "explicitNoOp", "scoped", "afterPop"}) + void lightmapEntryChangesOnlyRejectSubmissionsThatInheritThem(String kind) { + final boolean scoped = kind.equals("scoped") || kind.equals("afterPop"); + final boolean inheritedDraw = kind.equals("afterPop"); + final boolean enabled = !kind.equals("explicitNoOp"); + final var lightmap = GLStateManager.getTextures().getTextureUnitStates(1); + lightmap.setEnabled(false); + beginCapture(entity); + assertTrue(EntityShadowReplay.beginRenderer(renderer, entity, TICK_DELTA, BatchEligibility.SAFE)); + setCapturePose(model); + if (scoped) GLStateManager.glPushAttrib(GL11.GL_TEXTURE_BIT); + try { + lightmap.setEnabled(enabled); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + } finally { + if (scoped) GLStateManager.glPopAttrib(); + } + if (inheritedDraw) assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + endCaptureAndStartMainPass(); + lightmap.setEnabled(true); + + assertEquals(!inheritedDraw, EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + if (inheritedDraw) { + assertEquals(0, target.groupCount(), "an inherited draw must reject before the earlier explicit draw is queued"); + assertEquals(1, rejections(EntityShadowReplay.Rejection.ENTRY_STATE_CHANGED)); + assertTrue(lightmap.isEnabled()); + } else { + final RetainedTesrGroups.Group group = onlyGroup(target); + assertEquals(1, group.templateColumns.size); + assertEquals(enabled, group.layer.getState().isLightmap()); + assertEquals(scoped || enabled, lightmap.isEnabled(), + "a scoped override preserves main entry state; an explicit no-op still writes the exit state"); + } + } + + @Test + void unbalancedRendererMatrixRejectsBeforeMainGeometryIsQueued() { + capture(); + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + EntityShadowReplay.endEntity(true); + mainPass(); + + assertFalse(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(0, target.groupCount()); + assertEquals(1, rejections(EntityShadowReplay.Rejection.EXIT_STATE_UNSUPPORTED)); + assertTrue(mainView.equals(GLStateManager.getModelViewMatrix(), 0)); + } + + @ParameterizedTest + @ValueSource(strings = {"armor", "held", "dropped"}) + void skippedGlintExitWritesStillApplyWhenTheyWereNoOpsDuringCapture(String kind) { + applyGlintExit(kind); + beginCapture(entity); + assertTrue(EntityShadowReplay.beginRenderer(renderer, entity, TICK_DELTA, BatchEligibility.SAFE)); + applyGlintExit(kind); + setCapturePose(model); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + applyGlintExit(kind); + endCaptureAndStartMainPass(); + + GLStateManager.glColor4f(0.2f, 0.3f, 0.4f, 0.5f); + GLStateManager.glEnable(GL11.GL_BLEND); + GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ZERO, GL11.GL_ONE); + GLStateManager.glDisable(GL11.GL_LIGHTING); + GLStateManager.glDepthFunc(GL11.GL_LESS); + GLStateManager.glDepthMask(false); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.63f); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + + final boolean armor = kind.equals("armor"); + final boolean held = kind.equals("held"); + assertEquals(armor ? 1 : 0.5f * 0.76f, GLStateManager.getColor().getRed()); + assertEquals(armor ? 1 : 0.25f * 0.76f, GLStateManager.getColor().getGreen()); + assertEquals(armor ? 1 : 0.8f * 0.76f, GLStateManager.getColor().getBlue()); + assertEquals(1, GLStateManager.getColor().getAlpha()); + assertFalse(GLStateManager.isEffectiveBlendEnabled()); + assertTrue(GLStateManager.getLightingState().isEnabled()); + assertEquals(GL11.GL_LEQUAL, GLStateManager.getDepthState().getFunc()); + assertEquals(armor, GLStateManager.isEffectiveDepthMaskEnabled()); + assertEquals(GL11.GL_SRC_COLOR, GLStateManager.getBlendState().getSrcRgb()); + assertEquals(GL11.GL_ONE, GLStateManager.getBlendState().getDstRgb()); + assertEquals(held ? GL11.GL_ONE : GL11.GL_SRC_COLOR, GLStateManager.getBlendState().getSrcAlpha()); + assertEquals(held ? GL11.GL_ZERO : GL11.GL_ONE, GLStateManager.getBlendState().getDstAlpha()); + assertEquals(0.63f, GLStateManager.getAlphaState().getReference(), "an untouched exit field must retain the main entry value"); + assertTrue(mainView.equals(GLStateManager.getModelViewMatrix(), 0)); + } + + @Test + void followingLiveModelInheritsTheFinalTextureBoundAfterCapturedGeometry() { + final ResourceLocation finalTexture = new ResourceLocation("angelica", "test/final_binding"); + final ResourceLocation liveTexture = new ResourceLocation("angelica", "test/preceding_live_binding"); + final int capturedId = GLStateManager.glGenTextures(); + final int liveId = GLStateManager.glGenTextures(); + try { + capture(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, capturedId); + ModelPartBatcher.onTextureBind(finalTexture, capturedId); + endCaptureAndStartMainPass(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, liveId); + ModelPartBatcher.onTextureBind(liveTexture, liveId); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(capturedId, GLStateManager.getBoundTextureForServerState(0)); + + final TemplateBuffer following = template(); + assertTrue(batcher.queueTemplate(following, EntityMaterials.CUTOUT), "the next live renderer must inherit matching texture metadata"); + final var layers = RetainedTesrTestSupport.byLayer(target); + assertEquals(2, layers.size()); + boolean found = false; + for (var entry : layers.entrySet()) { + assertNotEquals(liveTexture, entry.getKey().getTextureId()); + if (finalTexture.equals(entry.getKey().getTextureId())) { + found = true; + assertEquals(1, entry.getValue().size()); + assertEquals(List.of(following), entry.getValue().getFirst().templateColumns.templates); + } + } + assertTrue(found, "the final texture can differ from every captured geometry command's texture"); + } finally { + GLStateManager.glDeleteTextures(capturedId); + GLStateManager.glDeleteTextures(liveId); + } + } + + @ParameterizedTest + @ValueSource(strings = {"explicitNoOp", "enableOnly", "valuesOnly", "explicit", "inherited", "popped"}) + void polygonOffsetAndTextureMatrixKeepOnlyTheWritesTheCaptureMade(String operation) { + final Matrix4f texture = new Matrix4f().translation(0.2f, 0.3f, 0); + if (operation.equals("enableOnly") || operation.equals("valuesOnly")) { + GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + } + beginCapture(entity); + assertTrue(EntityShadowReplay.beginRenderer(renderer, entity, TICK_DELTA, BatchEligibility.SAFE)); + switch (operation) { + case "explicitNoOp" -> { + GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glPolygonOffset(1, 1); + } + case "enableOnly" -> GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + case "valuesOnly" -> GLStateManager.glPolygonOffset(-2, -3); + case "explicit" -> { + GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glPolygonOffset(-2, -3); + GLStateManager.setTextureMatrix(0, texture); + } + case "popped" -> { + GLStateManager.glPushAttrib(GL11.GL_POLYGON_BIT | GL11.GL_ENABLE_BIT); + GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glPolygonOffset(7, 8); + GLStateManager.glPopAttrib(); + } + default -> { + } + } + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + endCaptureAndStartMainPass(); + GLStateManager.setTextureMatrix(0, new Matrix4f()); + GLStateManager.glPolygonOffset(-4, -5); + if (!operation.equals("explicitNoOp") && !operation.equals("enableOnly")) { + GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + } + + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.Group group = onlyGroup(target); + final boolean values = operation.equals("valuesOnly") || operation.equals("explicit"); + assertEquals(operation.equals("explicitNoOp") ? 1 : values ? -2 : -4, group.layer.getState().getOffsetFactor()); + assertEquals(operation.equals("explicitNoOp") ? 1 : values ? -3 : -5, group.layer.getState().getOffsetUnits()); + assertEquals(operation.equals("explicit"), texture.equals(group.templateColumns.runs.getFirst().matrix, 0)); + } + + @Test + void sharedRangePreservesChangingPartDataWithoutChangingShadowInstances() { + capture(); + final RetainedTesrGroups.Group shadow = onlyGroup(target); + final TemplateBuffer second = template(); + final Matrix4f secondModel = new Matrix4f(model).translate(2, 3, 4); + setCapturePose(secondModel); + GLStateManager.glColor4f(0.25f, 0.5f, 0.75f, 1); + GLStateManager.setOverlayColor(1, 0, 0, 0.5f); + assertTrue(batcher.queueTemplate(second, EntityMaterials.CUTOUT)); + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + final ObjectArrayList entries = commands(); + assertEquals(1, entries.size()); + final EntityRenderCommands.Model captured = (EntityRenderCommands.Model) entries.getFirst(); + assertSame(shadow.templateColumns, captured.source); + assertEquals(2, captured.end - captured.start); + final float[] original = shadow.templateColumns.matrices.clone(); + GLStateManager.setOverlayColor(0, 0, 0, 0); + mainPass(); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.InstanceColumns actual = onlyGroup(target).templateColumns; + assertEquals(2, actual.size); + assertSame(second, actual.templates.get(1)); + assertEquals(shadow.templateColumns.colors, actual.colors); + assertEquals(shadow.templateColumns.lights, actual.lights); + assertEquals(shadow.templateColumns.infos, actual.infos); + assertEquals(0, actual.overlays.getInt(0)); + assertEquals(AngelicaBufferSource.packAbgr(1, 0, 0, 0.5f), actual.overlays.getInt(1)); + final Matrix4f expected = new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f).mul(secondModel); + assertTrue(expected.equals(new Matrix4f().set(actual.matrices, 16), 0.00001f)); + assertTrue(new Matrix4f().set(original).equals(new Matrix4f().set(shadow.templateColumns.matrices), 0)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void acceptedModelsSharingAnAtlasPageKeepTheirOriginalTextures(boolean sameTextureId) { + final ResourceLocation firstTexture = new ResourceLocation("angelica", "test/first_original"); + final ResourceLocation secondTexture = new ResourceLocation("angelica", "test/second_original"); + final ResourceLocation atlasTexture = new ResourceLocation("angelica", "test/shared_atlas"); + final EntityTextureAtlas.Page page = new EntityTextureAtlas.Page(atlasTexture, 0); + final EntityTextureAtlas.Slot firstSlot = new EntityTextureAtlas.Slot(page, 0, 0, 64, 32); + final EntityTextureAtlas.Slot secondSlot = new EntityTextureAtlas.Slot(page, 66, 0, 64, 32); + final RenderLayer layer = RenderLayer.tesr(atlasTexture, EntityMaterials.CUTOUT, PassOverride.NONE, + 1, 1, -1, DrawState.CULL_BACK, false, true); + final CubeParams[] cube = cubes(1); + final TemplateBuffer geometry = template(); + final Matrix4f pose = new Matrix4f(shadowView).mul(model); + beginCapture(entity); + assertTrue(EntityShadowReplay.beginRenderer(renderer, entity, TICK_DELTA, BatchEligibility.SAFE)); + target.queueAndRecord(geometry, cube, 1, layer, pose, 0x00F000F0, -1, 0, 0L, 0, null, firstSlot, true, + new EntityRenderCommands.DrawInputs().set(firstTexture, 17, EntityMaterials.CUTOUT, PassOverride.NONE, true, 1, 1, -1, + DrawState.CULL_BACK, false, true, false)); + pose.translate(2, 0, 0); + target.queueAndRecord(geometry, cube, 1, layer, pose, 0x00F000F0, -1, 0, 0L, 0, null, secondSlot, true, + new EntityRenderCommands.DrawInputs().set(secondTexture, sameTextureId ? 17 : 18, EntityMaterials.CUTOUT, PassOverride.NONE, + true, 1, 1, -1, DrawState.CULL_BACK, false, true, false)); + final RetainedTesrGroups.InstanceColumns shadow = onlyGroup(target).cubeColumns; + assertEquals(2, shadow.size); + assertSame(firstSlot, shadow.atlasSlot(0)); + assertSame(secondSlot, shadow.atlasSlot(1)); + endCaptureAndStartMainPass(); + + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final var mainLayers = RetainedTesrTestSupport.byLayer(target); + assertEquals(2, mainLayers.size(), "distinct source textures sharing one shadow page must not merge"); + final var textures = mainLayers.keySet().stream().map(RenderLayer::getTextureId).toList(); + assertTrue(textures.contains(firstTexture)); + assertTrue(textures.contains(secondTexture)); + for (var groups : mainLayers.values()) { + assertEquals(1, groups.size()); + assertEquals(1, groups.getFirst().cubeColumns.size); + assertNull(groups.getFirst().cubeColumns.atlasSlot(0), "main submission must not retain the shadow atlas slot"); + } + assertSame(firstSlot, shadow.atlasSlot(0)); + assertSame(secondSlot, shadow.atlasSlot(1)); + } + + @Test + void rebuiltSourceRejectsAllRangesBeforeAnyReplayIsQueued() { + capture(); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.TRANSLUCENT)); + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + final ObjectArrayList entries = commands(); + assertEquals(2, entries.size()); + final RetainedTesrGroups.InstanceColumns source = ((EntityRenderCommands.Model) entries.get(1)).source; + mainPass(); + source.clear(); + assertFalse(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(0, target.groupCount()); + } + + @Test + void sharedRangeFallsBackWhenMainPassCannotInstance() { + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + try (CapturedStateScope ignored = new CapturedStateScope()) { + Reflect.set(batcher, "shaderPipeline", mock(DeferredWorldRenderingPipeline.class)); + state.setCurrentEntityAndItem(71, 23); + state.setCurrentBlockEntity(19); + state.setCurrentEntityColor(0.25f, 0.5f, 0.75f, 1); + capture(); + endCaptureAndStartMainPass(); + target.beginPass(new Matrix4f(), 0, 0, 0); + state.setCurrentEntityAndItem(89, 29); + state.setCurrentBlockEntity(31); + state.setCurrentEntityColor(1, 0, 0, 0.5f); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(1, target.streamedInstances); + final BufferSegment actual = onlyStreamSegment(target); + assertEquals(71, actual.getEntityId()); + assertEquals(19, actual.getRenderedBlockEntityId()); + assertEquals(23, actual.getItemId()); + assertEquals(AngelicaBufferSource.packAbgr(0.25f, 0.5f, 0.75f, 1), actual.getEntityColor()); + assertEquals(89, state.getCurrentRenderedEntity()); + assertEquals(31, state.getCurrentRenderedBlockEntity()); + assertEquals(29, state.getCurrentRenderedItem()); + assertTrue(state.getCurrentEntityColor().equals(1, 0, 0, 0.5f)); + } + } + + @Test + void armorGlintReplaysOnlyItsBaseAfterCaptureReuseAndReversedEntityOrder() { + prepareGlintCapture(); + final ResourceLocation glintTexture = new ResourceLocation("angelica", "test/armor_glint"); + final Entity other = mock(Entity.class); + final TemplateBuffer body = template(), firstArmor = template(), secondArmor = template(), otherArmor = template(); + final Matrix4f firstPose = new Matrix4f(model).translate(0.25f, 0.5f, -0.75f); + final Matrix4f secondPose = new Matrix4f(model).rotateX(0.3f).translate(-0.5f, 1.25f, 0.75f); + final Matrix4f otherPose = new Matrix4f(model).translate(5, 2, -3).rotateZ(0.4f); + final GlintCapture capture = new GlintCapture(); + final long drawsBefore = GLStateManager.drawCalls; + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.queueTemplate(body, EntityMaterials.CUTOUT)); + assertTrue(batcher.beginArmorCapture(capture)); + setCapturePose(firstPose); + assertTrue(batcher.queueTemplate(firstArmor, EntityMaterials.CUTOUT)); + setCapturePose(secondPose); + assertTrue(batcher.queueTemplate(secondArmor, EntityMaterials.CUTOUT)); + setCapturePose(model); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, glintTexture)); + }); + captureGlint(other, renderer, () -> { + setCapturePose(otherPose); + assertTrue(batcher.beginArmorCapture(capture)); + assertTrue(batcher.queueTemplate(otherArmor, EntityMaterials.CUTOUT)); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, glintTexture)); + }); + capture.reset(); + assertEquals(4, onlyGroup(target).templateColumns.size, "the shadow pass must only queue base geometry"); + mainPass(); + final Matrix4f callerMatrix = new Matrix4f(GLStateManager.getModelViewMatrix()); + assertTrue(EntityShadowReplay.replay(manager, other, TICK_DELTA, 0)); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(List.of(otherArmor, body, firstArmor, secondArmor), onlyMaterialGroup(EntityMaterials.CUTOUT).templateColumns.templates); + final RetainedTesrGroups.Group glint = onlyMaterialGroup(EntityMaterials.GLINT); + assertEquals(glintTexture, glint.layer.getTextureId()); + assertGlintLayers(glint, GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix(), + new TemplateBuffer[]{otherArmor, firstArmor, secondArmor}, + new Matrix4f[]{mainPose(otherPose), mainPose(firstPose), mainPose(secondPose)}, 0L, 0); + assertEquals(0, glint.layer.getState().getOffsetFactor()); + assertEquals(0, glint.layer.getState().getOffsetUnits()); + assertEquals(drawsBefore, GLStateManager.drawCalls, "capture and replay must leave draws to the batch flush"); + assertTrue(callerMatrix.equals(GLStateManager.getModelViewMatrix(), 0)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void armorCubeGlintTracksActualMainRangesAndReleasesTheirDependencies(boolean sourceNull) { + prepareGlintCapture(); + if (sourceNull) target.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(new InstanceRing())); + final TemplateBuffer first = template(), second = template(), unrelated = template(); + final CubeParams[] cube = cubes(1); + final Matrix4f secondPose = new Matrix4f(model).translate(0.33f, -0.41f, 0.57f).rotateY(0.23f); + final GlintCapture capture = new GlintCapture(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.beginArmorCapture(capture)); + queueCubes(first, cube); + setCapturePose(secondPose); + queueCubes(second, cube); + setCapturePose(model); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, ItemGlint.texture())); + }); + final ObjectArrayList bases = glintBases(); + for (EntityRenderCommands.Model base : bases) assertEquals(sourceNull, base.source == null); + final EntityRenderCommands.Glint capturedGlint = bases.getFirst().glint; + mainPass(); + GLStateManager.setModelViewMatrix(mainPose(new Matrix4f(model).translate(-3, 0, 0))); + queueCubes(unrelated, cube); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.InstanceColumns mainBase = onlyMaterialGroup(EntityMaterials.CUTOUT).cubeColumns; + assertEquals(List.of(unrelated, first, second), mainBase.templates); + final ObjectArrayList ranges = new ObjectArrayList<>(); + int next = 1; + for (EntityRenderCommands.Model base : bases) { + final RetainedTesrGroups.InstanceRange range = base.replayed; + ranges.add(range); + assertSame(mainBase, range.columns); + assertEquals(next, range.start); + assertTrue(range.end > range.start); + assertTrue(range.reuseUpload); + assertTrue(range.run.glintBase, "armor uploads must stay separate from ordinary opaque parts"); + next = range.end; + } + assertEquals(3, next); + final RetainedTesrGroups.Group glint = onlyMaterialGroup(EntityMaterials.GLINT); + assertGlintLayers(glint, GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix(), + new TemplateBuffer[]{first, second}, new Matrix4f[]{mainPose(model), mainPose(secondPose)}, 0, 0); + EntityShadowReplay.beginFrame(); + assertTrue(commands().isEmpty()); + assertNull(capturedGlint.base); + for (EntityRenderCommands.Model base : bases) { + assertNull(base.source); + assertNull(base.glint); + assertNull(base.nextGlintBase); + assertNull(base.replayed); + } + for (RetainedTesrGroups.InstanceRange range : ranges) { + assertNull(range.columns); + assertNull(range.run); + assertFalse(range.reuseUpload); + } + assertGlintLayers(glint, GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix(), + new TemplateBuffer[]{first, second}, new Matrix4f[]{mainPose(model), mainPose(secondPose)}, 0, 0); + } + + @Test + void armorGlintFollowsBaseRangesSplitAcrossTexturesAndMaterials() { + prepareGlintCapture(); + final ResourceLocation firstTexture = new ResourceLocation("angelica", "test/armor_first"); + final ResourceLocation secondTexture = new ResourceLocation("angelica", "test/armor_second"); + final TemplateBuffer first = template(), second = template(), third = template(); + final Matrix4f secondPose = new Matrix4f(model).translate(1.5f, 0.25f, -0.5f); + final Matrix4f thirdPose = new Matrix4f(model).rotateZ(0.47f).translate(-0.25f, 0.75f, 1.25f); + final GlintCapture capture = new GlintCapture(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.beginArmorCapture(capture)); + ModelPartBatcher.onTextureBind(firstTexture, 0); + assertTrue(batcher.queueTemplate(first, EntityMaterials.CUTOUT)); + setCapturePose(secondPose); + ModelPartBatcher.onTextureBind(secondTexture, 0); + assertTrue(batcher.queueTemplate(second, EntityMaterials.SOLID)); + setCapturePose(thirdPose); + ModelPartBatcher.onTextureBind(firstTexture, 0); + assertTrue(batcher.queueTemplate(third, EntityMaterials.CUTOUT)); + setCapturePose(model); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, ItemGlint.texture())); + }); + mainPass(); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(firstTexture, onlyMaterialGroup(EntityMaterials.CUTOUT).layer.getTextureId()); + assertEquals(secondTexture, onlyMaterialGroup(EntityMaterials.SOLID).layer.getTextureId()); + final ObjectArrayList bases = glintBases(); + for (EntityRenderCommands.Model base : bases) { + assertTrue(base.replayed.reuseUpload); + assertTrue(base.replayed.run.glintBase); + } + assertGlintLayers(onlyMaterialGroup(EntityMaterials.GLINT), GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix(), + new TemplateBuffer[]{first, second, third}, new Matrix4f[]{mainPose(model), mainPose(secondPose), mainPose(thirdPose)}, 0, 0, false); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void itemGlintUsesOnlyTheLastInstanceOfACoalescedBaseRange(boolean dropped) { + prepareGlintCapture(); + final TemplateBuffer first = template(), second = template(), enchanted = template(), unrelated = template(); + final Matrix4f secondPose = new Matrix4f(model).translate(0.21f, 0.43f, -0.65f); + final Matrix4f enchantedPose = new Matrix4f(model).rotateY(0.37f).translate(-0.17f, 0.39f, 0.61f); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.queueTemplate(first, EntityMaterials.DROPPED_ITEM_CUTOUT)); + setCapturePose(secondPose); + assertTrue(batcher.queueTemplate(second, EntityMaterials.DROPPED_ITEM_CUTOUT)); + setCapturePose(enchantedPose); + assertTrue(batcher.queueTemplate(enchanted, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(queueItemGlint(enchanted, dropped)); + }); + final EntityRenderCommands.Model captured = glintBases().getFirst(); + assertEquals(3, captured.end - captured.start, "the shadow base must exercise the coalesced range path"); + mainPass(); + assertTrue(batcher.queueTemplate(unrelated, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.InstanceColumns base = onlyMaterialGroup(EntityMaterials.DROPPED_ITEM_CUTOUT).templateColumns; + assertEquals(List.of(unrelated, first, second, enchanted), base.templates); + assertSame(base, captured.replayed.columns); + assertEquals(1, captured.replayed.start); + assertEquals(4, captured.replayed.end); + assertFalse(captured.replayed.reuseUpload); + assertFalse(captured.replayed.run.glintBase); + final RetainedTesrGroups.Group glint = onlyMaterialGroup(dropped ? EntityMaterials.GLINT : EntityMaterials.ITEM_GLINT); + assertGlintLayers(glint, ItemGlint.firstMatrix(), ItemGlint.secondMatrix(), + new TemplateBuffer[]{enchanted}, new Matrix4f[]{mainPose(enchantedPose)}, 0, 0); + assertArrayEquals(Arrays.copyOfRange(base.matrices, 3 * 16, 4 * 16), Arrays.copyOf(glint.templateColumns.matrices, 16)); + } + + private void queueCubes(TemplateBuffer template, CubeParams[] cubes) { + assertTrue(Reflect.invoke(batcher, "queueTemplate", + new Class[]{TemplateBuffer.class, CubeParams[].class, boolean.class, float.class, TesrMaterial.class, boolean.class}, + template, cubes, true, 1.0f, EntityMaterials.CUTOUT, false)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void itemGlintReplaysCapturedInputsAndKeepsTheLaterItemLayerAfterGlint(boolean dropped) { + prepareGlintCapture(); + final TesrMaterial glintMaterial = dropped ? EntityMaterials.GLINT : EntityMaterials.ITEM_GLINT; + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + try (CapturedStateScope ignored = new CapturedStateScope()) { + useGlintPipeline(RenderCondition.ENTITIES); + state.setCurrentEntityAndItem(71, 23); + state.setCurrentBlockEntity(19); + state.setCurrentEntityColor(0.25f, 0.5f, 0.75f, 1); + final int overlay = AngelicaBufferSource.packAbgr(0.25f, 0.5f, 0.75f, 1); + final TemplateBuffer item = template(), laterLayer = template(); + final Matrix4f pose = new Matrix4f(model).rotateXYZ(0.17f, -0.29f, 0.41f).translate(0.37f, -0.63f, 1.19f); + final long drawsBefore = GLStateManager.drawCalls; + captureGlint(entity, renderer, () -> { + setCapturePose(pose); + assertTrue(batcher.queueTemplate(item, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(queueItemGlint(item, dropped)); + assertTrue(batcher.queueTemplate(laterLayer, EntityMaterials.DROPPED_ITEM_CUTOUT, true)); + }); + assertTrue(materialGroups(glintMaterial).isEmpty(), "item glint must not enter the shadow queue"); + mainPass(); + state.setCurrentEntityAndItem(89, 29); + state.setCurrentBlockEntity(31); + state.setCurrentEntityColor(1, 0, 0, 0.5f); + final Matrix4f callerMatrix = new Matrix4f(GLStateManager.getModelViewMatrix()); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final RetainedTesrGroups.Group glint = onlyMaterialGroup(glintMaterial); + assertEquals(ItemGlint.texture(), glint.layer.getTextureId()); + assertGlintLayers(glint, ItemGlint.firstMatrix(), ItemGlint.secondMatrix(), + new TemplateBuffer[]{item}, new Matrix4f[]{mainPose(pose)}, InstancedAttribs.packEntityInfo(71, 19, 0), overlay); + final ObjectArrayList baseGroups = materialGroups(EntityMaterials.DROPPED_ITEM_CUTOUT); + assertEquals(2, baseGroups.size()); + for (RetainedTesrGroups.Group group : baseGroups) { + assertEquals(1, group.templateColumns.size); + assertEquals(InstancedAttribs.packEntityInfo(71, 19, 23), group.templateColumns.infos.getLong(0)); + if (group.layer.getTransparencyType() == TransparencyType.AFTER_GLINT) { + assertSame(laterLayer, group.templateColumns.templates.getFirst()); + } else { + assertEquals(TransparencyType.OPAQUE, group.layer.getTransparencyType()); + assertSame(item, group.templateColumns.templates.getFirst()); + assertGlintMatchesBase(glint, group.templateColumns); + } + } + assertEquals(drawsBefore, GLStateManager.drawCalls); + assertTrue(callerMatrix.equals(GLStateManager.getModelViewMatrix(), 0)); + assertTrue(new Matrix4f().equals(GLStateManager.getTextures().getTextureUnitMatrix(0), 0)); + assertEquals(89, state.getCurrentRenderedEntity()); + assertEquals(31, state.getCurrentRenderedBlockEntity()); + assertEquals(29, state.getCurrentRenderedItem()); + assertTrue(state.getCurrentEntityColor().equals(1, 0, 0, 0.5f)); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2, 3, 4}) + void droppedStackGlintKeepsEachCopyPoseWhenEntitiesReplayInReverseOrder(int copies) { + prepareGlintCapture(); + GLStateManager.glEnable(GL11.GL_STENCIL_TEST); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 3, 0xFF); + final Entity other = mock(Entity.class); + final TemplateBuffer[] items = {template(), template()}; + final Matrix4f[][] poses = new Matrix4f[2][copies]; + final long drawsBefore = GLStateManager.drawCalls; + for (int entityIndex = 0; entityIndex < 2; entityIndex++) { + final int index = entityIndex; + captureGlint(index == 0 ? entity : other, renderer, () -> { + for (int copy = 0; copy < copies; copy++) { + final Matrix4f pose = new Matrix4f(model).translate(index * 4.3f + copy * 0.17f, copy * -0.13f, index * 1.7f + copy * 0.09f) + .rotateXYZ(0.11f * copy, -0.23f * index, 0.07f * (copy + 1)); + poses[index][copy] = pose; + setCapturePose(pose); + assertTrue(batcher.queueTemplate(items[index], EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(batcher.queueSkippedItemGlint(items[index], EntityMaterials.GLINT)); + } + }); + } + assertEquals(copies * 2, onlyGroup(target).templateColumns.size); + mainPass(); + assertTrue(EntityShadowReplay.replay(manager, other, TICK_DELTA, 0)); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + final TemplateBuffer[] expectedTemplates = new TemplateBuffer[copies * 2]; + final Matrix4f[] expectedPoses = new Matrix4f[copies * 2]; + for (int i = 0; i < expectedTemplates.length; i++) { + final int index = 1 - i / copies; + expectedTemplates[i] = items[index]; + expectedPoses[i] = mainPose(poses[index][i % copies]); + } + final RetainedTesrGroups.Group base = onlyMaterialGroup(EntityMaterials.DROPPED_ITEM_CUTOUT); + assertEquals(Arrays.asList(expectedTemplates), base.templateColumns.templates); + final RetainedTesrGroups.Group glint = onlyMaterialGroup(EntityMaterials.GLINT); + assertGlintLayers(glint, ItemGlint.firstMatrix(), ItemGlint.secondMatrix(), expectedTemplates, expectedPoses, 0, 0); + assertGlintMatchesBase(glint, base.templateColumns); + assertTrue(materialGroups(EntityMaterials.ITEM_GLINT).isEmpty(), "dropped copies must not use held-item stencil deduplication"); + assertEquals(GL11.GL_EQUAL, GLStateManager.getStencilState().getFuncFront()); + assertEquals(drawsBefore, GLStateManager.drawCalls); + } + + @Test + void droppedGlintEntryReusedForArmorDoesNotKeepTheItemTemplateOrLayers() { + prepareGlintCapture(); + final TemplateBuffer item = template(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.queueTemplate(item, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(batcher.queueSkippedItemGlint(item, EntityMaterials.GLINT)); + }); + EntityShadowReplay.beginFrame(); + GLStateManager.setModelViewMatrix(shadowView); + EntityShadowReplay.beginPass(true, 0); + final TemplateBuffer first = template(), second = template(); + final Matrix4f secondPose = new Matrix4f(model).translate(0.31f, 0.47f, -0.59f); + final GlintCapture capture = new GlintCapture(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.beginArmorCapture(capture)); + assertTrue(batcher.queueTemplate(first, EntityMaterials.CUTOUT)); + setCapturePose(secondPose); + assertTrue(batcher.queueTemplate(second, EntityMaterials.CUTOUT)); + setCapturePose(model); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, ItemGlint.texture())); + }); + mainPass(); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertGlintLayers(onlyMaterialGroup(EntityMaterials.GLINT), GlintClock.firstArmorMatrix(), GlintClock.secondArmorMatrix(), + new TemplateBuffer[]{first, second}, new Matrix4f[]{mainPose(model), mainPose(secondPose)}, 0, 0); + assertTrue(materialGroups(EntityMaterials.DROPPED_ITEM_CUTOUT).isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = {"stale", "instancing", "bodyVariant", "glintVariant", "stencil", "failed", + "dropped:stale", "dropped:bodyVariant", "dropped:glintVariant"}) + void unavailableOrInvalidGlintRejectsBeforeAnyReplayIsQueued(String reason) { + prepareGlintCapture(); + final boolean dropped = reason.startsWith("dropped:"); + final String failure = dropped ? reason.substring("dropped:".length()) : reason; + if (failure.equals("bodyVariant") || failure.equals("glintVariant")) { + final DeferredWorldRenderingPipeline pipeline = useGlintPipeline(RenderCondition.ENTITIES); + final RenderCondition missing = failure.equals("bodyVariant") ? RenderCondition.ENTITIES : RenderCondition.GLINT; + when(pipeline.hasInstancedVariant(missing, InputAvailability.BOTH, Instancing.TEMPLATE)).thenReturn(false); + } + final GlintCapture capture = new GlintCapture(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + if (dropped || failure.equals("stencil")) { + final TemplateBuffer item = template(); + assertTrue(batcher.queueTemplate(item, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(queueItemGlint(item, dropped)); + } else { + assertTrue(batcher.beginArmorCapture(capture)); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, ItemGlint.texture())); + } + assertTrue(batcher.queueTemplate(template(), EntityMaterials.TRANSLUCENT)); + if (failure.equals("failed")) EntityShadowReplay.rejectRenderFailed(); + }); + final RetainedTesrGroups.InstanceColumns laterSource = onlyMaterialGroup(EntityMaterials.TRANSLUCENT).templateColumns; + mainPass(); + switch (failure) { + case "stale" -> laterSource.clear(); + case "instancing" -> target.beginPass(new Matrix4f(), 0, 0, 0); + case "stencil" -> { + GLStateManager.glEnable(GL11.GL_STENCIL_TEST); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 3, 0xFF); + } + } + assertFalse(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(0, target.groupCount()); + assertEquals(0, target.streamedInstances); + final EntityShadowReplay.Rejection expected = switch (failure) { + case "stale" -> EntityShadowReplay.Rejection.SHARED_RANGE_CHANGED; + case "stencil" -> EntityShadowReplay.Rejection.UNCAPTURED_STATE; + case "failed" -> EntityShadowReplay.Rejection.RENDER_FAILED; + default -> EntityShadowReplay.Rejection.NOT_READY; + }; + assertEquals(1, rejections(expected)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void glintPreflightUsesCapturedTranslucencyInsteadOfMaterialOrMainDeclaration(boolean translucent) { + prepareGlintCapture(); + useGlintPipeline(translucent ? RenderCondition.ENTITIES_TRANSLUCENT : RenderCondition.ENTITIES); + final TesrMaterial material = translucent ? EntityMaterials.DROPPED_ITEM_CUTOUT : EntityMaterials.DROPPED_ITEM_TRANSLUCENT; + final TemplateBuffer item = template(); + final Boolean beforeCapture = GbufferPrograms.beginTranslucencyDeclaration(translucent); + try { + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.queueTemplate(item, material)); + assertTrue(batcher.queueSkippedItemGlint(item, EntityMaterials.ITEM_GLINT)); + }); + } finally { + GbufferPrograms.endTranslucencyDeclaration(beforeCapture); + } + mainPass(); + final Boolean beforeReplay = GbufferPrograms.beginTranslucencyDeclaration(!translucent); + try { + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertSame(item, onlyMaterialGroup(material).templateColumns.templates.getFirst()); + assertEquals(2, onlyMaterialGroup(EntityMaterials.ITEM_GLINT).templateColumns.runs.size()); + assertEquals(!translucent, GbufferPrograms.getDeclaredTranslucency()); + } finally { + GbufferPrograms.endTranslucencyDeclaration(beforeReplay); + } + } + + @Test + void glintEntryPoolReuseDoesNotAddGlintOrRequireInstancingOnTheNextFrame() { + prepareGlintCapture(); + final GlintCapture capture = new GlintCapture(); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + assertTrue(batcher.beginArmorCapture(capture)); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, ItemGlint.texture())); + final TemplateBuffer held = template(); + assertTrue(batcher.queueTemplate(held, EntityMaterials.DROPPED_ITEM_CUTOUT)); + assertTrue(batcher.queueSkippedItemGlint(held, EntityMaterials.ITEM_GLINT)); + }); + EntityShadowReplay.beginFrame(); + GLStateManager.setModelViewMatrix(shadowView); + EntityShadowReplay.beginPass(true, 0); + captureGlint(entity, renderer, () -> { + setCapturePose(model); + for (TesrMaterial material : new TesrMaterial[]{EntityMaterials.CUTOUT, EntityMaterials.SOLID, + EntityMaterials.TRANSLUCENT, EntityMaterials.ADDITIVE}) { + assertTrue(batcher.queueTemplate(template(), material)); + } + }); + mainPass(); + target.beginPass(new Matrix4f(), 0, 0, 0); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(4, target.streamedInstances); + assertEquals(4, target.groupCount()); + assertTrue(materialGroups(EntityMaterials.GLINT).isEmpty()); + assertTrue(materialGroups(EntityMaterials.ITEM_GLINT).isEmpty()); + } + + private DeferredWorldRenderingPipeline useGlintPipeline(RenderCondition body) { + final DeferredWorldRenderingPipeline pipeline = mock(DeferredWorldRenderingPipeline.class); + when(pipeline.hasInstancedVariant(body, InputAvailability.BOTH, Instancing.TEMPLATE)).thenReturn(true); + when(pipeline.hasInstancedVariant(RenderCondition.GLINT, InputAvailability.BOTH, Instancing.TEMPLATE)).thenReturn(true); + Reflect.set(batcher, "shaderPipeline", pipeline); + return pipeline; + } + + private boolean queueItemGlint(TemplateBuffer item, boolean dropped) { + return batcher.queueSkippedItemGlint(item, dropped ? EntityMaterials.GLINT : EntityMaterials.ITEM_GLINT); + } + + private void prepareGlintCapture() { + Reflect.set(batcher, "instancedThisCycle", true); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glDisable(GL11.GL_STENCIL_TEST); + GlintClock.beginFrame(123456789L); + } + + private void captureGlint(Entity captured, Render render, Runnable queue) { + when(manager.getEntityRenderObject(captured)).thenReturn(render); + beginCapture(captured); + assertTrue(EntityShadowReplay.beginRenderer(render, captured, TICK_DELTA, BatchEligibility.SAFE)); + assertTrue(BatchEligibility.begin(BatchEligibility.SAFE, GLStateManager.drawCalls)); + boolean completed = false; + try { + queue.run(); + completed = true; + } finally { + EntityShadowReplay.endRenderer(completed, BatchEligibility.end(BatchEligibility.SAFE, GLStateManager.drawCalls)); + finishCapture(completed); + } + } + + private Matrix4f mainPose(Matrix4f pose) { + return new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f).mul(pose); + } + + private ObjectArrayList materialGroups(TesrMaterial material) { + final ObjectArrayList matches = new ObjectArrayList<>(); + for (ObjectArrayList groups : RetainedTesrTestSupport.byLayer(target).values()) { + for (RetainedTesrGroups.Group group : groups) if (group.material == material) matches.add(group); + } + return matches; + } + + private RetainedTesrGroups.Group onlyMaterialGroup(TesrMaterial material) { + final ObjectArrayList matches = materialGroups(material); + assertEquals(1, matches.size()); + return matches.getFirst(); + } + + @ParameterizedTest + @ValueSource(strings = {"foreign", "expected", "bail", "shadowOnly", "failed", "caught", "nested", "nextFrame", "passOne", "camera", "lightmap", "partialTicks", "renderer", "afterRenderer", "outerFailed", "nestedEntity"}) + void incompleteOrChangedRecordsNeverQueuePartialGeometry(String reason) { + capture(); + switch (reason) { + case "foreign" -> GLStateManager.drawCalls++; + case "expected" -> { + BatchEligibility.begin(BatchEligibility.SAFE, GLStateManager.drawCalls); + BatchEligibility.beginExpectedDraws(GLStateManager.drawCalls); + GLStateManager.drawCalls++; + BatchEligibility.endExpectedDraws(GLStateManager.drawCalls); + BatchEligibility.end(BatchEligibility.SAFE, GLStateManager.drawCalls); + } + case "bail" -> BatchEligibility.onBail(ModelPartBatcher.BailReason.TEXTURE); + case "shadowOnly" -> EntityShadowReplay.rejectShadowOnly(); + case "caught" -> EntityShadowReplay.rejectRenderFailed(); + case "nested" -> assertFalse(EntityShadowReplay.beginRenderer(renderer, mock(Entity.class), TICK_DELTA, BatchEligibility.SAFE)); + case "nestedEntity" -> assertFalse(EntityShadowReplay.beginEntity(mock(Entity.class), TICK_DELTA)); + } + EntityShadowReplay.endRenderer(!reason.equals("failed"), BatchEligibility.SAFE); + if (reason.equals("afterRenderer")) GLStateManager.drawCalls++; + if (reason.equals("outerFailed")) finishCapture(false); + if (reason.equals("nextFrame")) EntityShadowReplay.beginFrame(); + mainPass(); + switch (reason) { + case "camera" -> RenderManager.instance.playerViewY = 0.2f; + case "lightmap" -> GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(false); + case "renderer" -> when(manager.getEntityRenderObject(entity)).thenReturn(mock(Render.class)); + } + assertFalse(EntityShadowReplay.replay(manager, entity, reason.equals("partialTicks") ? 0.5f : TICK_DELTA, reason.equals("passOne") ? 1 : 0)); + assertEquals(0, target.groupCount()); + if (reason.equals("lightmap")) assertEquals(1, rejections(EntityShadowReplay.Rejection.ENTRY_STATE_CHANGED)); + } + + @ParameterizedTest + @ValueSource(strings = {"queue", "copyRange", "referenceRange", "stream"}) + void uncapturedAcceptedSubmissionsKeepShadowGeometryButRejectTheWholeReplay(String operation) { + withBossStatus(() -> withDeferredOverlays(() -> { + final EntityWither boss = wither("Captured boss", 100, 300); + final RenderWither bossRenderer = mock(RenderWither.class); + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + captureLiving(boss, bossRenderer); + observeBossStatus(boss, false); + queueAura(callback, bossRenderer, boss, new float[]{TICK_DELTA, 1, 2, 3, 4, 5, 0.0625f}, + new Matrix4f(shadowView).mul(model)); + final RetainedTesrGroups.Group shadow = onlyGroup(target); + final RetainedTesrGroups.InstanceColumns columns = shadow.templateColumns; + final TemplateBuffer extra = template(); + final Matrix4f pose = new Matrix4f(shadowView).mul(model).translate(2, 0, 0); + final long draws = GLStateManager.drawCalls; + switch (operation) { + case "queue" -> target.queue(0, extra, shadow.layer, EntityMaterials.CUTOUT, pose, 0, -1, 0, 0L, 0, null); + case "copyRange" -> target.copyInstances(columns, 0, 1, shadow.layer, EntityMaterials.CUTOUT, + 0, -1, 0, null); + case "referenceRange" -> target.referenceInstances(columns, 0, 1, shadow.layer, EntityMaterials.CUTOUT, + -1, new Matrix4f()); + case "stream" -> target.streamVertices(shadow.layer, 0, extra.data, extra.vertexCount, pose); + default -> throw new AssertionError(operation); + } + if (operation.equals("stream")) { + assertEquals(extra.vertexCount, onlyStreamSegment(target).getVertexCount()); + assertEquals(1, columns.size); + } else if (operation.equals("referenceRange")) { + assertEquals(1, columns.referencedParts); + assertEquals(1, columns.size); + } else { + assertEquals(2, columns.size, "unrecorded submission must still reach shadow storage"); + } + assertEquals(draws, GLStateManager.drawCalls, "rejection must not force an immediate shadow draw"); + endCaptureAndStartMainPass(); + resetBossStatus(); + + assertFalse(EntityShadowReplay.replay(manager, boss, TICK_DELTA, 0)); + assertEquals(0, target.groupCount()); + assertEquals(0, target.streamedInstances); + assertUnchangedBossStatus(); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertTrue(deferred.isEmpty()); + verifyNoInteractions(callback, bossRenderer); + })); + } + + @Test + void fireReplayCopiesVerticesAndRestoresShaderInputsForTheNextEntity() { + capture(); + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + final CapturedRenderingState state = CapturedRenderingState.INSTANCE; + Reflect.set(batcher, "shaderPipeline", mock(DeferredWorldRenderingPipeline.class)); + state.pushCurrentEntityAndItem(); + state.pushCurrentBlockEntity(); + state.pushCurrentEntityColor(); + try { + state.setCurrentEntityAndItem(71, 23); + state.setCurrentBlockEntity(19); + state.setCurrentEntityColor(0.25f, 0.5f, 0.75f, 1); + final TemplateBuffer quad = template(); + final int[] vertices = quad.data.clone(); + queueFire(vertices, quad.vertexCount); + final BufferSegment shadowSegment = onlyStreamSegment(target); + final ByteBuffer shadowBuffer = Reflect.get(shadowSegment.getOwner(), "buffer"); + final int positionOffset = 0; + final float shadowVertexX = shadowBuffer.getFloat(positionOffset); + final float shadowVertexY = shadowBuffer.getFloat(positionOffset + 4); + final float shadowVertexZ = shadowBuffer.getFloat(positionOffset + 8); + Arrays.fill(vertices, 0); + assertEquals(1, target.streamedInstances); + state.setCurrentEntityAndItem(89, 29); + state.setCurrentBlockEntity(31); + state.setCurrentEntityColor(1, 0, 0, 0.5f); + mainPass(); + assertTrue(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + assertEquals(1, target.streamedInstances); + assertEquals(89, state.getCurrentRenderedEntity()); + assertEquals(29, state.getCurrentRenderedItem()); + assertEquals(31, state.getCurrentRenderedBlockEntity()); + assertTrue(state.getCurrentEntityColor().equals(1, 0, 0, 0.5f)); + final BufferSegment actual = onlyStreamSegment(target); + assertEquals(shadowSegment.getVertexCount(), actual.getVertexCount()); + assertEquals(shadowSegment.getBlockEntityId(), actual.getBlockEntityId()); + assertEquals(71, actual.getEntityId()); + assertEquals(19, actual.getRenderedBlockEntityId()); + assertEquals(23, actual.getItemId()); + assertEquals(shadowSegment.getEntityColor(), actual.getEntityColor()); + assertEquals(0, actual.getRenderType().getState().getOffsetFactor()); + assertEquals(shadowSegment.getRenderType().getState().isLightmap(), actual.getRenderType().getState().isLightmap()); + final var expected = new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f).mul(new Matrix4f(shadowView).invert()) + .transformPosition(shadowVertexX, shadowVertexY, shadowVertexZ, new Vector3f()); + final ByteBuffer actualBuffer = Reflect.get(actual.getOwner(), "buffer"); + assertEquals(expected.x, actualBuffer.getFloat(positionOffset), 0.00001f); + assertEquals(expected.y, actualBuffer.getFloat(positionOffset + 4), 0.00001f); + assertEquals(expected.z, actualBuffer.getFloat(positionOffset + 8), 0.00001f); + } finally { + state.popCurrentEntityColor(); + state.popCurrentBlockEntity(); + state.popCurrentEntityAndItem(); + } + } + + private void queueFire(int[] vertices, int vertexCount) { + GLStateManager.glEnable(GL11.GL_DEPTH_TEST); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + GLStateManager.glColorMask(true, true, true, true); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + final Tessellator tess = mock(Tessellator.class); + tess.isDrawing = true; + tess.drawMode = GL11.GL_QUADS; + tess.rawBuffer = vertices; + tess.vertexCount = vertexCount; + tess.rawBufferIndex = tess.rawBuffer.length; + final long draws = GLStateManager.drawCalls; + batcher.beginEntityFire(); + try { + ModelPartBatcher.drawTessellator(tess); + } finally { + batcher.endEntityFire(); + } + assertEquals(draws, GLStateManager.drawCalls); + } + + @Test + void bossReplaysUpdateTheBossBarInMainEntityOrder() { + withBossStatus(() -> { + final EntityWither first = wither("First", 45, 300); + final EntityDragon second = boss(EntityDragon.class, "Second", 180, 300); + final EntityLivingBase third = boss(EntityLivingBase.class, "Custom boss", 25, 100); + final EntityWither live = wither("Live", 80, 200); + final RenderWither witherRenderer = mock(RenderWither.class); + final RenderDragon dragonRenderer = mock(RenderDragon.class); + final RendererLivingEntity customRenderer = mock(RendererLivingEntity.class); + captureLiving(first, witherRenderer); + observeBossStatus(first, true); + endCapture(); + captureLiving(second, dragonRenderer); + observeBossStatus(second, false); + endCapture(); + captureLiving(third, customRenderer); + observeBossStatus((IBossDisplayData) third, false); + endCaptureAndStartMainPass(); + + final DataWatcher watcher = Reflect.get(second, "dataWatcher"); + when(watcher.getWatchableObjectFloat(6)).thenReturn(210f); + when(second.func_145748_c_()).thenReturn(new ChatComponentText("Renamed second")); + resetBossStatus(); + assertTrue(EntityShadowReplay.replay(manager, second, TICK_DELTA, 0)); + assertBossStatus(second, false); + BossStatus.setBossStatus(live, true); + assertBossStatus(live, true); + BossStatus.statusBarTime = 1; + assertTrue(EntityShadowReplay.replay(manager, first, TICK_DELTA, 0)); + assertBossStatus(first, true); + assertTrue(EntityShadowReplay.replay(manager, third, TICK_DELTA, 0)); + assertBossStatus((IBossDisplayData) third, false); + assertEquals(3, onlyGroup(target).templateColumns.size); + verifyNoInteractions(witherRenderer, dragonRenderer, customRenderer); + }); + } + + @Test + void bossUpdateAloneDoesNotMakeACanceledEntityReplayable() { + withBossStatus(() -> { + final EntityLivingBase boss = boss(EntityLivingBase.class, "Canceled", 150, 300); + when(manager.getEntityRenderObject(boss)).thenReturn(renderer); + beginCapture(boss); + assertTrue(EntityShadowReplay.beginRenderer(renderer, boss, TICK_DELTA, BatchEligibility.SAFE)); + observeBossStatus((IBossDisplayData) boss, true); + endCaptureAndStartMainPass(); + resetBossStatus(); + + assertFalse(EntityShadowReplay.replay(manager, boss, TICK_DELTA, 0)); + assertUnchangedBossStatus(); + assertEquals(0, target.groupCount()); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "foreign", "multiple", "nonBoss", "dragonEyes", "program", "excluded", + "edited:health", "edited:time", "edited:name", "edited:color"}) + void rejectedBossRecordsChangeNeitherTheHudNorTheQueues(String reason) { + withBossStatus(() -> withDeferredOverlays(() -> { + final EntityLivingBase boss = reason.equals("dragonEyes") + ? boss(EntityDragon.class, "Dragon", 150, 300) + : boss(EntityLivingBase.class, "Rejected", 150, 300); + final EntityLivingBase rendered = reason.equals("nonBoss") ? mock(EntityCreeper.class) : boss; + final RendererLivingEntity livingRenderer = mock(RendererLivingEntity.class); + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + if (reason.equals("excluded")) AngelicaConfig.entityShadowReplayExcludedClasses = new String[]{EntityLivingBase.class.getName()}; + captureLiving(rendered, livingRenderer); + if (!reason.equals("missing")) { + observeBossStatus(reason.equals("foreign") ? wither("Foreign", 25, 300) : (IBossDisplayData) boss, false); + } + if (reason.equals("multiple")) observeBossStatus((IBossDisplayData) boss, true); + switch (reason) { + case "edited:health" -> BossStatus.healthScale = 0.75f; + case "edited:time" -> BossStatus.statusBarTime = -1; + case "edited:name" -> BossStatus.bossName = "Custom boss name"; + case "edited:color" -> BossStatus.hasColorModifier = true; + default -> { + } + } + queueAura(callback, livingRenderer, rendered, new float[]{TICK_DELTA, 1, 2, 3, 4, 5, 0.0625f}, + new Matrix4f(shadowView).mul(model)); + if (reason.equals("dragonEyes")) { + final int depth = GLStateManager.pushState(StateSet.BATCH); + try { + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glEnable(GL11.GL_BLEND); + GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + GLStateManager.glDepthFunc(GL11.GL_EQUAL); + GLStateManager.glDepthMask(true); + assertFalse(batcher.queueTemplate(template(), null)); + } finally { + GLStateManager.popStateTo(depth); + } + } + endCaptureAndStartMainPass(); + if (reason.equals("program")) { + final DeferredWorldRenderingPipeline pipeline = mock(DeferredWorldRenderingPipeline.class); + when(pipeline.getActivePassProgramId()).thenReturn(GLStateManager.getActiveProgram() + 1); + Reflect.set(batcher, "shaderPipeline", pipeline); + assertTrue(batcher.entityPassActive(), "program ownership must not disable the active pass's fallback flushing"); + } + resetBossStatus(); + assertFalse(EntityShadowReplay.replay(manager, rendered, TICK_DELTA, 0)); + assertUnchangedBossStatus(); + assertEquals(0, target.groupCount()); + assertEquals(0, target.streamedInstances); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertTrue(deferred.isEmpty()); + verifyNoInteractions(callback, livingRenderer); + if (reason.equals("program")) assertEquals(1, rejections(EntityShadowReplay.Rejection.NOT_READY)); + })); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void reusedRecordsDoNotInheritAnEarlierBossUpdate(boolean nextIsBoss) { + withBossStatus(() -> { + final EntityWither first = wither("Previous", 100, 300); + final RenderWither witherRenderer = mock(RenderWither.class); + captureLiving(first, witherRenderer); + observeBossStatus(first, true); + endCapture(); + EntityShadowReplay.beginFrame(); + GLStateManager.setModelViewMatrix(shadowView); + EntityShadowReplay.beginPass(true, 0); + final Entity next; + if (nextIsBoss) { + next = boss(EntityLivingBase.class, "Missing update", 200, 300); + captureLiving((EntityLivingBase) next, witherRenderer); + } else { + next = entity; + capture(); + } + endCaptureAndStartMainPass(); + resetBossStatus(); + assertEquals(!nextIsBoss, EntityShadowReplay.replay(manager, next, TICK_DELTA, 0)); + assertUnchangedBossStatus(); + assertFalse(EntityShadowReplay.replay(manager, first, TICK_DELTA, 0)); + assertUnchangedBossStatus(); + assertEquals(nextIsBoss ? 0 : 1, target.groupCount()); + }); + } + + @Test + void deferredAurasSurviveRecyclingAndFollowMainEntityOrder() { + withDeferredOverlays(() -> { + final EntityCreeper first = mock(EntityCreeper.class); + final EntityCreeper second = mock(EntityCreeper.class); + final EntityCreeper live = mock(EntityCreeper.class); + final RenderCreeper creeperRenderer = mock(RenderCreeper.class); + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + final var liveCallback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + final float[] firstArgs = {0.25f, 1, 2, 3, 4, 5, 0.0625f}; + final float[] secondArgs = {0.75f, 6, 7, 8, 9, 10, 0.125f}; + final float[] liveArgs = {0.5f, 11, 12, 13, 14, 15, 0.25f}; + final Matrix4f firstAura = new Matrix4f(model).translate(1, 2, 3).scale(1.1f); + final Matrix4f secondAura = new Matrix4f(model).rotateZ(0.3f).translate(4, 5, 6); + final Matrix4f liveAura = new Matrix4f(mainView).translate(-1, -2, -3); + captureLiving(first, creeperRenderer); + queueAura(callback, creeperRenderer, first, firstArgs, new Matrix4f(shadowView).mul(firstAura)); + endCapture(); + captureLiving(second, creeperRenderer); + queueAura(callback, creeperRenderer, second, secondArgs, new Matrix4f(shadowView).mul(secondAura)); + endCapture(); + + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertEquals(2, deferred.size()); + final Object recycled = deferred.get(1); + mainPass(); + queueAura(liveCallback, creeperRenderer, live, liveArgs, liveAura); + assertSame(recycled, deferred.getFirst(), "the live aura must overwrite a recycled shadow queue entry"); + final long draws = GLStateManager.drawCalls; + assertTrue(EntityShadowReplay.replay(manager, second, TICK_DELTA, 0)); + assertTrue(EntityShadowReplay.replay(manager, first, TICK_DELTA, 0)); + assertEquals(2, onlyGroup(target).templateColumns.size, "both bodies must still replay"); + assertEquals(3, deferred.size(), "replay must enqueue both captured auras after the live main aura"); + assertEquals(draws, GLStateManager.drawCalls, "replay must leave aura drawing to the deferred phase"); + verifyNoInteractions(callback, liveCallback, creeperRenderer); + assertTrue(liveAura.equals(GLStateManager.getModelViewMatrix(), 0)); + + EntityShadowReplay.beginFrame(); + assertAura(deferred.get(0), liveCallback, creeperRenderer, live, liveArgs, liveAura); + final Matrix4f mainOrigin = new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f); + assertAura(deferred.get(1), callback, creeperRenderer, second, secondArgs, new Matrix4f(mainOrigin).mul(secondAura)); + assertAura(deferred.get(2), callback, creeperRenderer, first, firstArgs, new Matrix4f(mainOrigin).mul(firstAura)); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ordinaryAndMarkedOnlyEntitiesDoNotReplayAnAura(boolean markOnly) { + withDeferredOverlays(() -> { + final EntityCreeper creeper = mock(EntityCreeper.class); + final RenderCreeper creeperRenderer = mock(RenderCreeper.class); + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + captureLiving(creeper, creeperRenderer); + queueAura(callback, creeperRenderer, creeper, new float[]{TICK_DELTA, 1, 2, 3, 4, 5, 0.0625f}, + new Matrix4f(shadowView).mul(model)); + endCapture(); + EntityShadowReplay.beginFrame(); + GLStateManager.setModelViewMatrix(shadowView); + EntityShadowReplay.beginPass(true, 0); + captureLiving(creeper, creeperRenderer); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.TRANSLUCENT)); + if (markOnly) DeferredEntityOverlay.markOverlayPass(callback, creeperRenderer, creeper, TICK_DELTA); + DeferredEntityOverlay.clearStaleOverlayFlag(); + endCaptureAndStartMainPass(); + final long draws = GLStateManager.drawCalls; + assertTrue(EntityShadowReplay.replay(manager, creeper, TICK_DELTA, 0)); + assertEquals(2, target.groupCount(), "the previous aura entry must be reusable as a model range"); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertTrue(deferred.isEmpty()); + assertEquals(draws, GLStateManager.drawCalls); + verifyNoInteractions(callback, creeperRenderer); + }); + } + + @Test + void invalidRangeAfterAnAuraRejectsTheWholeReplay() { + withDeferredOverlays(() -> { + final EntityCreeper creeper = mock(EntityCreeper.class); + final RenderCreeper creeperRenderer = mock(RenderCreeper.class); + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + captureLiving(creeper, creeperRenderer); + queueAura(callback, creeperRenderer, creeper, new float[]{TICK_DELTA, 1, 2, 3, 4, 5, 0.0625f}, + new Matrix4f(shadowView).mul(model)); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.TRANSLUCENT)); + endCapture(); + final ObjectArrayList entries = commands(); + final RetainedTesrGroups.InstanceColumns source = ((EntityRenderCommands.Model) entries.getLast()).source; + mainPass(); + source.clear(); + assertFalse(EntityShadowReplay.replay(manager, creeper, TICK_DELTA, 0)); + assertEquals(0, target.groupCount()); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertTrue(deferred.isEmpty(), "the aura before a stale model range must not be enqueued"); + verifyNoInteractions(callback, creeperRenderer); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"armored", "unarmored", "stale"}) + void witherBodyReplaysWhileArmorKeepsItsDeferredPhase(String armor) { + withBossStatus(() -> withDeferredOverlays(() -> { + final EntityWither wither = wither("Armored", 100, 300); + final RenderWither witherRenderer = mock(RenderWither.class); + final ModelBase armorModel = mock(ModelBase.class); + witherRenderer.renderPassModel = armorModel; + final var callback = mock(DeferredEntityOverlay.ShouldRenderPassFn.class); + when(callback.invoke(wither, 1, TICK_DELTA)).thenReturn(1); + captureLiving(wither, witherRenderer); + observeBossStatus(wither, true); + final Matrix4f armorModelView = new Matrix4f(model).translate(0, -0.01f, 0).scale(1.1f); + setCapturePose(armorModelView); + if (!armor.equals("unarmored")) DeferredEntityOverlay.markOverlayPass(callback, witherRenderer, wither, TICK_DELTA); + if (armor.equals("armored")) DeferredEntityOverlay.deferRender(1, 2, 3, 4, 5, 0.0625f); + DeferredEntityOverlay.clearStaleOverlayFlag(); + endCaptureAndStartMainPass(); + resetBossStatus(); + final long draws = GLStateManager.drawCalls; + assertTrue(EntityShadowReplay.replay(manager, wither, TICK_DELTA, 0)); + assertBossStatus(wither, true); + assertEquals(1, onlyGroup(target).templateColumns.size); + assertEquals(draws, GLStateManager.drawCalls); + final List deferred = Reflect.getStatic(DeferredEntityOverlay.class, "deferred"); + assertEquals(armor.equals("armored") ? 1 : 0, deferred.size()); + verifyNoInteractions(callback, armorModel, witherRenderer); + if (armor.equals("armored")) { + final Matrix4f expected = new Matrix4f(mainView).translate(0.5f, 0.12f, -0.25f).mul(armorModelView); + assertAura(deferred.getFirst(), callback, witherRenderer, wither, + new float[]{TICK_DELTA, 1, 2, 3, 4, 5, 0.0625f}, expected); + } + try (CapturedStateScope ignored = new CapturedStateScope()) { + DeferredEntityOverlay.renderAll(); + } + if (armor.equals("armored")) { + final var order = inOrder(callback, armorModel); + order.verify(callback).invoke(wither, 1, TICK_DELTA); + order.verify(armorModel).setLivingAnimations(wither, 1, 2, TICK_DELTA); + order.verify(armorModel).render(wither, 1, 2, 3, 4, 5, 0.0625f); + order.verify(callback).invoke(wither, 2, TICK_DELTA); + verifyNoMoreInteractions(callback, armorModel); + } else { + verifyNoInteractions(callback, armorModel); + } + assertTrue(deferred.isEmpty()); + assertFalse(DeferredEntityOverlay.isOverlayPassActive()); + assertFalse(DeferredEntityOverlay.isReplaying()); + assertTrue(mainView.equals(GLStateManager.getModelViewMatrix(), 0)); + assertBossStatus(wither, true); + })); + } + + private void captureLiving(EntityLivingBase living, RendererLivingEntity livingRenderer) { + when(manager.getEntityRenderObject(living)).thenReturn(livingRenderer); + beginCapture(living); + assertEquals(captureOpen, EntityShadowReplay.beginRenderer(livingRenderer, living, TICK_DELTA, BatchEligibility.SAFE)); + setCapturePose(model); + assertTrue(batcher.queueTemplate(template(), EntityMaterials.CUTOUT)); + } + + private void queueAura(DeferredEntityOverlay.ShouldRenderPassFn callback, RendererLivingEntity renderer, + EntityLivingBase entity, float[] args, Matrix4f matrix) { + if (captureOpen) setCapturePose(new Matrix4f(captureEntry).invert().mul(matrix)); + else GLStateManager.setModelViewMatrix(matrix); + DeferredEntityOverlay.markOverlayPass(callback, renderer, entity, args[0]); + DeferredEntityOverlay.deferRender(args[1], args[2], args[3], args[4], args[5], args[6]); + } + + @Test + void secondPassEntitiesAndExcludedSubclassesStayLive() { + when(entity.shouldRenderInPass(1)).thenReturn(true); + capture(); + endCaptureAndStartMainPass(); + assertFalse(EntityShadowReplay.replay(manager, entity, TICK_DELTA, 0)); + AngelicaConfig.entityShadowReplayExcludedClasses = new String[]{"net.minecraft.entity.monster.EntityMob"}; + assertTrue(EntityShadowReplay.isExcluded(EntityZombie.class)); + assertTrue(EntityShadowReplay.isExcluded(EntityPlayer.class)); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlasGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlasGLTest.java index 5b1406123..3093d9b60 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlasGLTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityTextureAtlasGLTest.java @@ -1,9 +1,13 @@ package com.gtnewhorizons.angelica.rendering.tesr; +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.ExitState; import com.gtnewhorizons.angelica.glsm.GLCoreTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.testutil.Reflect; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.iris.layer.PassOverride; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; @@ -12,6 +16,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.joml.Matrix4f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -25,6 +32,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.cubes; +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.onlyGroup; +import static com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.template; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -63,6 +75,7 @@ class EntityTextureAtlasGLTest { @AfterEach void tearDown() { + GLStateManager.cancelExitCapture(); EntityTextureAtlas.INSTANCE.freePages(); GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); GLStateManager.glDeleteFramebuffers(passFbo); @@ -75,6 +88,66 @@ class EntityTextureAtlasGLTest { return 0xFF000000 | (x * 50 + seed) << 16 | (y * 90 + seed) << 8 | 0x20; } + @ParameterizedTest + @CsvSource({"false, false", "true, false", "false, true", "true, true"}) + void entityReplayResolvesAtlasRegionsWithoutRemappingSharedGlintUploads(boolean shared, boolean glint) { + final boolean atlasEnabled = AngelicaConfig.enableEntityTextureAtlas; + final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE; + final RetainedTesrGroups previousGroups = Reflect.get(batcher, "activeGroups"); + final RetainedTesrGroups groups = new RetainedTesrGroups(new AngelicaBufferSource()); + final int otherTexture = texture(GL11.GL_NEAREST, 12); + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(new InstanceRing()), + new RetainedTesrTestSupport.CountingPipeline(true, true)); + try { + AngelicaConfig.enableEntityTextureAtlas = true; + Reflect.set(batcher, "activeGroups", groups); + final EntityTextureAtlas.Slot shadowSlot = EntityTextureAtlas.INSTANCE.slotFor(source, false); + assertNotNull(shadowSlot); + EntityTextureAtlas.INSTANCE.onTextureDeleted(source); + EntityTextureAtlas.INSTANCE.recycleReleasedRegions(); + assertSame(shadowSlot, EntityTextureAtlas.INSTANCE.slotFor(otherTexture, false)); + + final EntityRenderCommands.Model entry = new EntityRenderCommands.Model(); + entry.instance.template = template(); + entry.cubes = cubes(1); + entry.cubesInsideTexture = true; + entry.scale = 1; + entry.inputs.material = EntityMaterials.CUTOUT; + entry.inputs.texture = new ResourceLocation("angelica", "test/replay"); + entry.inputs.textureId = source; + entry.inputs.pass = PassOverride.NONE; + entry.inputs.glintSlot = -1; + if (glint) { + entry.glint = new EntityRenderCommands.ModelGlint(); + entry.replayed = new RetainedTesrGroups.InstanceRange(); + entry.replayed.reuseUpload = true; + } + if (shared) { + entry.source = new RetainedTesrGroups.InstanceColumns(); + entry.source.addCubes(entry.instance.template, entry.cubes, 1, new Matrix4f(), 0, -1, 0, 0, shadowSlot); + entry.end = 1; + } + batcher.beginReplay(new Matrix4f()); + batcher.replay(entry); + + final RetainedTesrGroups.Group main = onlyGroup(groups); + final EntityTextureAtlas.Slot mainSlot = main.cubeColumns.atlasSlot(0); + if (glint) { + assertNull(mainSlot, "glint reuses the armor upload, whose UVs must still address the original texture"); + assertEquals(entry.inputs.texture, main.layer.getTextureId()); + } else { + assertNotNull(mainSlot); + assertNotSame(shadowSlot, mainSlot); + assertSame(EntityTextureAtlas.INSTANCE.slotFor(source, false), mainSlot); + } + } finally { + Reflect.set(batcher, "activeGroups", previousGroups); + AngelicaConfig.enableEntityTextureAtlas = atlasEnabled; + groups.clear(); + GLStateManager.glDeleteTextures(otherTexture); + } + } + private static int texture(int filter, int seed) { final int id = GLStateManager.glGenTextures(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); @@ -114,7 +187,10 @@ class EntityTextureAtlasGLTest { @Test void copiesTheTextureWithEdgeGuttersAndRestoresTheFramebuffers() { + final ExitState state = new ExitState(); + GLStateManager.beginExitCapture(state); final EntityTextureAtlas.Slot slot = EntityTextureAtlas.INSTANCE.slotFor(source, false); + assertTrue(GLStateManager.finishExitCapture(state), "first-use atlas resources are internal batch operations"); assertNotNull(slot); assertEquals(passFbo, GLStateManager.getDrawFramebuffer(), "draw framebuffer restored"); assertEquals(passFbo, GLStateManager.getReadFramebuffer(), "read framebuffer restored"); diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java index 914db5965..1d49ec913 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java @@ -6,6 +6,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.api.tesr.TesrShader; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLCoreTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; @@ -20,6 +21,7 @@ import com.gtnewhorizons.angelica.glsm.states.BlendState; import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; import com.gtnewhorizons.angelica.glsm.testutil.Reflect; import com.gtnewhorizons.angelica.rendering.GlintClock; +import com.gtnewhorizons.angelica.rendering.items.ItemGlint; import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.Group; import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns; import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.TexRun; @@ -27,9 +29,13 @@ import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrTestSupport.Countin import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; import net.coderbot.iris.layer.PassOverride; +import net.coderbot.iris.pipeline.ShadowRenderer; import net.coderbot.iris.uniforms.CapturedStateScope; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.ItemRenderer; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.joml.Matrix4f; @@ -64,6 +70,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; @GLCoreTest class RetainedTesrGroupsGLTest { @@ -755,6 +763,10 @@ class RetainedTesrGroupsGLTest { } private static int createGlintTexture() { + return createGlintTexture(false); + } + + private static int createGlintTexture(boolean opaque) { final int id = GLStateManager.glGenTextures(); GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); @@ -765,7 +777,7 @@ class RetainedTesrGroupsGLTest { final ByteBuffer texels = BufferUtils.createByteBuffer(4 * 4 * 4); for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { - texels.put((byte) (64 + 48 * x)).put((byte) (64 + 48 * y)).put((byte) 200).put((byte) (64 + 48 * x)); + texels.put((byte) (64 + 48 * x)).put((byte) (64 + 48 * y)).put((byte) 200).put((byte) (opaque ? 255 : 64 + 48 * x)); } } texels.flip(); @@ -1000,6 +1012,184 @@ class RetainedTesrGroupsGLTest { } } + @ParameterizedTest + @ValueSource(strings = {"armorTemplate", "armorCubes", "held", "heldMirrored", "dropped", "droppedStack"}) + void shadowGlintReplayMatchesLiveMainPixels(String kind) { + glintState(); + GLStateManager.glDeleteTextures(glintTexture); + glintTexture = createGlintTexture(true); + final boolean held = kind.startsWith("held"), dropped = kind.startsWith("dropped"), cubes = kind.equals("armorCubes"); + final TemplateBuffer baseTemplate; + if (held || dropped) { + final AngelicaTesrMeshCache.GtnhMeshBackend backend = new AngelicaTesrMeshCache.GtnhMeshBackend(); + ItemRenderer.renderItemIn2D(backend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL), 0.75f, 0.1f, 0.25f, 0.9f, 16, 32, 0.0625f); + baseTemplate = backend.endCaptureToTemplate(); + ItemRenderer.renderItemIn2D(backend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL), 0, 0, 1, 1, 16, 32, 0.0625f); + glintTemplate = backend.endCaptureToTemplate(); + } else { + if (!cubes) glintTemplate = capturedQuad(0.5); + baseTemplate = glintTemplate; + } + final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE; + final boolean previousBatching = AngelicaConfig.enableEntityBatching; + final boolean previousReplay = AngelicaConfig.enableEntityShadowReplay; + final boolean previousAtlas = AngelicaConfig.enableEntityTextureAtlas; + final boolean previousShadow = ShadowRenderer.ACTIVE; + final double previousX = RenderManager.renderPosX, previousY = RenderManager.renderPosY, previousZ = RenderManager.renderPosZ; + final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(new AngelicaBufferSource()); + final Matrix4f shadowView = new Matrix4f().rotateXYZ(0.6f, -0.7f, 0.2f).translate(2, -1, 3); + final Matrix4f mainView = new Matrix4f().rotateXYZ(-0.1f, 0.2f, 0.17f); + final Matrix4f pose = new Matrix4f().rotateXYZ(0.13f, 0.41f, -0.27f); + if (held || dropped) pose.scale(0.8f, kind.equals("heldMirrored") ? -0.8f : 0.8f, 0.8f).translate(-0.5f, -0.5f, 0); + final Entity entity = mock(Entity.class); + final Render renderer = mock(Render.class); + final RenderManager manager = mock(RenderManager.class); + when(manager.getEntityRenderObject(entity)).thenReturn(renderer); + BatchStateGuard.suspend(); + try { + AngelicaConfig.enableEntityBatching = true; + AngelicaConfig.enableEntityShadowReplay = true; + AngelicaConfig.enableEntityTextureAtlas = false; + EntityShadowReplay.beginFrame(); + Reflect.set(batcher, "active", true); + Reflect.set(batcher, "mode", ModelPartBatcher.Mode.ENTITIES); + Reflect.set(batcher, "instancedThisCycle", true); + GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(false); + GLStateManager.setOverlayColor(0, 0, 0, 0); + GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + GLStateManager.glDisable(GL11.GL_STENCIL_TEST); + RenderManager.renderPosX = 1000000; + RenderManager.renderPosY = RenderManager.renderPosZ = 0; + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); + Reflect.set(batcher, "activeGroups", groups); + Reflect.set(batcher, "shadow", false); + ShadowRenderer.ACTIVE = false; + GLStateManager.setModelViewMatrix(mainView); + queueEntityGlint(batcher, kind, baseTemplate, pose, true); + final int[][] reference = drawEntityGlint(kind); + + shadowGroups.beginPass(new Matrix4f(), 0, 0, 0, instanced, new CountingPipeline(true, true)); + Reflect.set(batcher, "activeGroups", shadowGroups); + Reflect.set(batcher, "shadow", true); + ShadowRenderer.ACTIVE = true; + GLStateManager.setModelViewMatrix(shadowView); + EntityShadowReplay.beginPass(true, 0); + BatchStateGuard.resume(); + try { + assertTrue(EntityShadowReplay.beginEntity(entity, 0.25f)); + assertTrue(EntityShadowReplay.beginRenderer(renderer, entity, 0.25f, BatchEligibility.SAFE)); + queueEntityGlint(batcher, kind, baseTemplate, pose, false); + EntityShadowReplay.endRenderer(true, BatchEligibility.SAFE); + EntityShadowReplay.endEntity(true); + } finally { + BatchStateGuard.suspend(); + } + assertEquals(1, shadowGroups.groupCount(), "glint must not add a shadow draw group"); + + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); + Reflect.set(batcher, "activeGroups", groups); + Reflect.set(batcher, "shadow", false); + ShadowRenderer.ACTIVE = false; + GLStateManager.setModelViewMatrix(mainView); + EntityShadowReplay.beginPass(false, 0); + assertTrue(EntityShadowReplay.replay(manager, entity, 0.25f, 0)); + final int[][] replayed = drawEntityGlint(kind); + FfpFixture.assertOverlayFootprint(reference[0], reference[1], BACKGROUND, "live glint"); + FfpFixture.assertOverlayFootprint(replayed[0], replayed[1], BACKGROUND, "replayed glint"); + // Replay reaches the main pose through the shadow view, about 1 ulp off the live pose. On llvmpipe that + // flips a single glint pixel on the dropped item's thin edge strips. + FfpFixture.assertPixelParity("replayed glint pixels", reference[1], replayed[1], SIZE, BACKGROUND, 8, 1, 2, RetainedTesrGroupsGLTest::describe); + } finally { + shadowGroups.clear(); + batcher.clear(); + EntityShadowReplay.clear(); + AngelicaConfig.enableEntityBatching = previousBatching; + AngelicaConfig.enableEntityShadowReplay = previousReplay; + AngelicaConfig.enableEntityTextureAtlas = previousAtlas; + ShadowRenderer.ACTIVE = previousShadow; + RenderManager.renderPosX = previousX; + RenderManager.renderPosY = previousY; + RenderManager.renderPosZ = previousZ; + GLStateManager.glDisable(GL11.GL_STENCIL_TEST); + BatchStateGuard.resume(); + } + } + + private void queueEntityGlint(ModelPartBatcher batcher, String kind, TemplateBuffer baseTemplate, Matrix4f pose, boolean legacyDropped) { + final int copies = kind.equals("droppedStack") ? 4 : 1; + for (int copy = 0; copy < copies; copy++) { + queueEntityGlintCopy(batcher, kind, baseTemplate, new Matrix4f(pose).translate(copy * 0.12f, copy * 0.06f, copy * 0.085f), legacyDropped); + } + } + + private void queueEntityGlintCopy(ModelPartBatcher batcher, String kind, TemplateBuffer baseTemplate, Matrix4f pose, boolean legacyDropped) { + final boolean held = kind.startsWith("held"), dropped = kind.startsWith("dropped"), cubes = kind.equals("armorCubes"); + bindBase(); + restoreTexMatrix(); + GLStateManager.glPushMatrix(); + GLStateManager.applyMultMatrix(pose); + GLStateManager.glColor4f(0.4f, 0.6f, 0.8f, 1); + ModelPartBatcher.onTextureBind(new ResourceLocation("angelica", "test/base"), baseTexture); + final GlintCapture capture = new GlintCapture(); + assertTrue(BatchEligibility.begin(BatchEligibility.SAFE, GLStateManager.drawCalls)); + try { + if (!held && !dropped) assertTrue(batcher.beginArmorCapture(capture)); + assertTrue(Reflect.invoke(batcher, "queueTemplate", + new Class[] {TemplateBuffer.class, CubeParams[].class, boolean.class, float.class, TesrMaterial.class, boolean.class}, + baseTemplate, cubes ? glintCubes : null, false, CUBE_SCALE, held || dropped ? EntityMaterials.DROPPED_ITEM_CUTOUT : EntityMaterials.CUTOUT, false)); + if (held) { + assertTrue(batcher.queueSkippedItemGlint(glintTemplate, EntityMaterials.ITEM_GLINT)); + } else if (dropped && legacyDropped) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, glintTexture); + ModelPartBatcher.onTextureBind(GLINT_TEXTURE, glintTexture); + GLStateManager.glColor4f(0.5f * 0.76f, 0.25f * 0.76f, 0.8f * 0.76f, 1); + for (Matrix4f matrix : new Matrix4f[] {ItemGlint.firstMatrix(), ItemGlint.secondMatrix()}) { + GLStateManager.setTextureMatrix(0, matrix); + assertTrue(batcher.queueTemplate(glintTemplate, EntityMaterials.GLINT)); + } + restoreTexMatrix(); + } else if (dropped) { + assertTrue(batcher.queueSkippedItemGlint(glintTemplate, EntityMaterials.GLINT)); + } else { + capture.endWithRestoredPose(); + assertTrue(batcher.queueSkippedArmorGlint(capture, GLINT_TEXTURE)); + } + } finally { + BatchEligibility.end(BatchEligibility.SAFE, GLStateManager.drawCalls); + capture.reset(); + GLStateManager.glPopMatrix(); + } + } + + private int[][] drawEntityGlint(String kind) { + final boolean held = kind.startsWith("held"), dropped = kind.startsWith("dropped"); + FfpFixture.clear(); + final int depth = GLStateManager.pushState(StateSet.BATCH); + try { + int[] base = null; + for (TesrMaterial material : new TesrMaterial[] {held || dropped ? EntityMaterials.DROPPED_ITEM_CUTOUT : EntityMaterials.CUTOUT, + held ? EntityMaterials.ITEM_GLINT : EntityMaterials.GLINT}) { + for (var layers : RetainedTesrTestSupport.byLayer(groups).values()) for (Group group : layers) { + if (group.material != material) continue; + group.layer.getState().apply(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, base == null ? baseTexture : glintTexture); + GLStateManager.enableTexture(); + GLStateManager.glEnable(GL11.GL_STENCIL_TEST); + GLStateManager.glStencilFunc(GL11.GL_ALWAYS, 3, 0xFF); + GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); + groups.drawLayer(group.layer); + assertEquals(GL11.GL_ALWAYS, GL11.glGetInteger(GL11.GL_STENCIL_FUNC)); + assertEquals(3, GL11.glGetInteger(GL11.GL_STENCIL_REF)); + } + if (base == null) base = FfpFixture.readRegion(SIZE); + } + ring.endFrame(); + return new int[][] {base, FfpFixture.readRegion(SIZE)}; + } finally { + GLStateManager.popStateTo(depth); + } + } + @Test void mirroredModelViewUnderCullFrontBatchesLikeTheImmediateDraw() { GLStateManager.glViewport(0, 0, SIZE, SIZE); diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java index bef5f12a6..0486b6411 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java @@ -60,6 +60,198 @@ class RetainedTesrGroupsTest { layer = testLayer(); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void replayRangeMatchesIndividualQueueingAcrossCapacityGrowth(boolean cubes) { + final TemplateBuffer template = template(); + final var cubeParams = cubes ? cubes(2) : null; + final var input = new RetainedTesrGroups.InstanceColumns(); + for (int i = 0; i < 80; i++) { + final Matrix4f matrix = new Matrix4f().translation(i, -i, 2).rotateY(i * 0.1f).scale(0.5f); + if (cubes) input.addCubes(template, cubeParams, i + 1, matrix, i, ~i, i * 2, i * 3L, null); + else input.add(template, matrix, i, ~i, i * 2, i * 3L); + } + final var expected = new RetainedTesrGroups(new AngelicaBufferSource()); + final var pipeline = new RetainedTesrTestSupport.CountingPipeline(true, true); + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring), pipeline); + expected.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring), pipeline); + final RenderLayer layer = layerFor(STREAM); + final Matrix4f transform = new Matrix4f().rotateX(0.2f).translate(5, 7, 3); + final Matrix4f texture = new Matrix4f().translation(0.2f, 0.4f, 0); + for (RetainedTesrGroups dst : new RetainedTesrGroups[] {groups, expected}) { + dst.queue(0, template, cubeParams, 1, layer, STREAM, new Matrix4f(), 0, -1, 0, 0, 0, texture, null); + } + groups.replayInstances(input, 5, 75, layer, STREAM, 0, transform, texture, null, null); + for (int i = 5; i < 75; i++) { + final Matrix4f matrix = new Matrix4f(transform).mul(new Matrix4f().set(input.matrices, i * 16)); + expected.queue(0, template, cubeParams, cubes ? input.scales.getFloat(i) : 1, layer, STREAM, matrix, + input.lights.getInt(i), input.colors.getInt(i), input.overlays.getInt(i), input.infos.getLong(i), 0, texture, null); + } + final var actualGroup = onlyGroup(groups); + final var expectedGroup = onlyGroup(expected); + final var actual = cubes ? actualGroup.cubeColumns : actualGroup.templateColumns; + final var correct = cubes ? expectedGroup.cubeColumns : expectedGroup.templateColumns; + assertEquals(correct.size, actual.size); + for (int i = 0; i < actual.size * 16; i++) assertEquals(correct.matrices[i], actual.matrices[i], 0.00001f); + assertEquals(correct.templates, actual.templates); + assertEquals(correct.cubes, actual.cubes); + assertEquals(correct.scales, actual.scales); + assertEquals(correct.colors, actual.colors); + assertEquals(correct.lights, actual.lights); + assertEquals(correct.overlays, actual.overlays); + assertEquals(correct.infos, actual.infos); + assertEquals(correct.runs.getFirst().parts, actual.runs.getFirst().parts); + assertEquals(correct.runs.getFirst().instances, actual.runs.getFirst().instances); + } + + @Test + void replayRangeRetainedFallbackPreservesTheModelTransform() { + final TemplateBuffer triangles = new TemplateBuffer(new int[3 * VERTEX_SIZE], 3, GL11.GL_TRIANGLES); + final Matrix4f model = new Matrix4f().translation(3, 2, -6).rotateY(0.7f).scale(0.5f); + final Matrix4f transform = new Matrix4f().rotateX(0.2f).translate(5, 7, 3); + final var input = new RetainedTesrGroups.InstanceColumns(); + input.add(triangles, model, 0, -1, 0, 0); + final var expected = new RetainedTesrGroups(new AngelicaBufferSource()); + final RenderLayer layer = layerFor(STREAM); + groups.beginPass(new Matrix4f(), 0, 0, 0); + expected.beginPass(new Matrix4f(), 0, 0, 0); + + groups.replayInstances(input, 0, 1, layer, STREAM, 0, transform, null, null, null); + expected.queue(0, triangles, layer, STREAM, new Matrix4f(transform).mul(model), 0, -1, 0, 0, 0, null); + + final var actual = onlyGroup(groups); + assertEquals(0, groups.streamedInstances); + assertEquals(1, actual.instTexMatrices.size(), "the draw-mode mismatch must take the retained fallback"); + assertTrue(new Matrix4f().set(onlyGroup(expected).templateColumns.matrices) + .equals(new Matrix4f().set(actual.templateColumns.matrices), 0.00001f)); + assertTrue(model.equals(new Matrix4f().set(input.matrices), 0)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void replayRangeProbeMatchesIndividualQueueing(boolean queueBeforeReplay) { + final TemplateBuffer template = template(); + final Matrix4f base = new Matrix4f().rotateX(0.3f).translate(4, -2, 5); + final Matrix4f model = new Matrix4f().translation(3, 2, -6).rotateY(0.7f).scale(0.5f); + final Matrix4f transform = new Matrix4f().rotateX(0.2f).translate(5, 7, 3); + final var input = new RetainedTesrGroups.InstanceColumns(); + input.add(template, model, 0, -1, 0, 0); + final var expected = new RetainedTesrGroups(new AngelicaBufferSource(), () -> clock[0]); + final var renderer = new InstancedTemplateRenderer(ring); + final var state = CapturedRenderingState.INSTANCE; + try (CapturedStateScope ignored = new CapturedStateScope()) { + state.setCurrentEntityAndItem(0, 0); + state.setCurrentBlockEntity(0); + state.setCurrentEntityColor(0, 0, 0, 0); + for (RetainedTesrGroups dst : new RetainedTesrGroups[] {groups, expected}) { + dst.beginPass(base, 100.5, 64.25, -100.75, renderer); + dst.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 0); + dst.queue(0, template, layer, TesrMaterial.CURRENT_STATE, base, 0, -1, 0, 0, 0, null); + } + clock[0] += RetainedTesrGroups.STABILITY_PROBE_MS; + for (RetainedTesrGroups dst : new RetainedTesrGroups[] {groups, expected}) { + dst.beginPass(base, 100.5, 64.25, -100.75, renderer); + if (queueBeforeReplay) { + dst.queue(0, template, layer, TesrMaterial.CURRENT_STATE, base, 0, -1, 0, 0, 0, null); + assertTrue(onlyGroup(dst).probe.probing); + } + } + + groups.replayInstances(input, 0, 1, layer, TesrMaterial.CURRENT_STATE, 0, transform, null, null, null); + expected.queue(0, template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(transform).mul(model), 0, -1, 0, 0, 0, null); + + final var actual = onlyGroup(groups); + final var correct = onlyGroup(expected); + final int offset = queueBeforeReplay ? 16 : 0; + assertTrue(actual.probe.probing); + assertEquals(queueBeforeReplay ? 2 : 1, correct.probe.count); + assertEquals(correct.probe.count, actual.probe.count); + assertTrue(new Matrix4f().set(correct.probe.snapshot.matrices, offset) + .equals(new Matrix4f().set(actual.probe.snapshot.matrices, offset), 0.00001f)); + assertTrue(new Matrix4f().set(correct.templateColumns.matrices, offset) + .equals(new Matrix4f().set(actual.templateColumns.matrices, offset), 0.00001f)); + assertTrue(model.equals(new Matrix4f().set(input.matrices), 0)); + } + } + + @Test + void replayRangeAfterIdleUsesRetainedStorage() { + final TemplateBuffer template = template(); + final Matrix4f base = new Matrix4f().rotateX(0.3f).translate(4, -2, 5); + final Matrix4f model = new Matrix4f().translation(3, 2, -6).rotateY(0.7f).scale(0.5f); + final Matrix4f transform = new Matrix4f().rotateX(0.2f).translate(5, 7, 3); + final var input = new RetainedTesrGroups.InstanceColumns(); + input.add(template, model, 0, -1, 0, 0); + final var expected = new RetainedTesrGroups(new AngelicaBufferSource(), () -> clock[0]); + final var renderer = new InstancedTemplateRenderer(ring); + final var state = CapturedRenderingState.INSTANCE; + try (CapturedStateScope ignored = new CapturedStateScope()) { + state.setCurrentEntityAndItem(0, 0); + state.setCurrentBlockEntity(0); + state.setCurrentEntityColor(0, 0, 0, 0); + for (RetainedTesrGroups dst : new RetainedTesrGroups[] {groups, expected}) { + dst.beginPass(base, 100.5, 64.25, -100.75, renderer); + dst.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 0); + dst.queue(0, template, layer, TesrMaterial.CURRENT_STATE, base, 0, -1, 0, 0, 0, null); + assertTrue(onlyGroup(dst).streamPath); + for (int i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES; i++) { + dst.beginPass(base, 100.5, 64.25, -100.75, renderer); + } + } + + groups.replayInstances(input, 0, 1, layer, TesrMaterial.CURRENT_STATE, 0, transform, null, null, null); + expected.queue(0, template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(transform).mul(model), 0, -1, 0, 0, 0, null); + + final var actual = onlyGroup(groups); + final var correct = onlyGroup(expected); + assertFalse(actual.streamPath); + assertEquals(1, correct.instTexMatrices.size()); + assertEquals(correct.instTexMatrices.size(), actual.instTexMatrices.size()); + assertTrue(actual.templateColumns.runs.isEmpty()); + assertTrue(new Matrix4f().set(correct.templateColumns.matrices) + .equals(new Matrix4f().set(actual.templateColumns.matrices), 0.00001f)); + assertTrue(model.equals(new Matrix4f().set(input.matrices), 0)); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void replayRangeUsesCapturedStateForNonStreamGroups(boolean liveGroupPromoted) { + final TemplateBuffer template = template(); + final Matrix4f model = new Matrix4f().translation(3, 2, -6).rotateY(0.7f).scale(0.5f); + final long info = InstancedAttribs.packEntityInfo(11, 21, 13); + final int overlay = AngelicaBufferSource.packAbgr(1, 0, 0, 0.5f); + final var input = new RetainedTesrGroups.InstanceColumns(); + input.add(template, model, 0, -1, overlay, info); + final var state = CapturedRenderingState.INSTANCE; + try (CapturedStateScope ignored = new CapturedStateScope()) { + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + state.setCurrentEntityAndItem(11, 13); + state.setCurrentBlockEntity(21); + AngelicaBufferSource.setEntityColor(overlay); + groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 21); + final var capturedGroup = onlyGroup(groups); + + state.setCurrentEntityAndItem(12, 14); + state.setCurrentBlockEntity(22); + state.setCurrentEntityColor(0, 1, 0, 0.5f); + final int liveOverlay = AngelicaBufferSource.packEntityColor(state.getCurrentEntityColor()); + if (liveGroupPromoted) groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 21); + + groups.replayInstances(input, 0, 1, layer, TesrMaterial.CURRENT_STATE, 21, new Matrix4f(), null, null, null); + + assertEquals(liveGroupPromoted ? 2 : 1, groups.groupCount()); + assertEquals(1, capturedGroup.templateColumns.size); + assertEquals(info, capturedGroup.templateColumns.infos.getLong(0)); + assertEquals(overlay, capturedGroup.templateColumns.overlays.getInt(0)); + assertEquals(12, state.getCurrentRenderedEntity()); + assertEquals(22, state.getCurrentRenderedBlockEntity()); + assertEquals(14, state.getCurrentRenderedItem()); + assertEquals(liveOverlay, AngelicaBufferSource.packEntityColor(state.getCurrentEntityColor())); + assertTrue(model.equals(new Matrix4f().set(input.matrices), 0)); + } + } + @Test void fallbackKeepsHighMaterialIdsAndTheUnmappedSentinel() { for (int id : new int[] { -1, 0, 32767, 32768, 45020, 50020, 50072, 65534 }) { diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrTestSupport.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrTestSupport.java index a4a7d7a1f..76617794e 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrTestSupport.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrTestSupport.java @@ -86,8 +86,8 @@ public final class RetainedTesrTestSupport { static RenderLayer capturedLayer(TesrMaterial material) { return Reflect.invoke(ModelPartBatcher.INSTANCE, "layerFor", - new Class[] { ResourceLocation.class, TesrMaterial.class, PassOverride.class, float.class, float.class, int.class, int.class, boolean.class, boolean.class }, - null, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap()); + new Class[] { ResourceLocation.class, TesrMaterial.class, PassOverride.class, float.class, float.class, int.class, int.class, boolean.class, boolean.class, boolean.class }, + null, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap(), false); } static final class CountingPipeline implements TesrInstancingPipeline {