diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java index 23077b807..81f5b6ab8 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java @@ -242,6 +242,9 @@ public class GLContextState { public int internalGlDepth; public int internalDrawDepth; public int savedFilterTextureId; + public int savedFilterMin = -1; + public int savedFilterMag = -1; + public float savedFilterAniso = -1.0f; public boolean wideLineEmulationActive = false; public boolean lineStippleActive = false; public Instancing ffpInstancing = Instancing.NONE; 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 7b0926094..4b7ac7f63 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -157,14 +157,18 @@ public class GLStateManager { public static void beforeUncapturedCapabilityChange(int cap) { if (cap == GL11.GL_FOG || cap == GL11.GL_SCISSOR_TEST || cap == GL11.GL_STENCIL_TEST - || (cap == GL11.GL_TEXTURE_2D && getActiveTextureUnit() != 0) - || cap == GL11.GL_TEXTURE_1D || cap == GL12.GL_TEXTURE_3D || cap == GL13.GL_TEXTURE_CUBE_MAP - || (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) - || (cap >= GL11.GL_TEXTURE_GEN_S && cap <= GL11.GL_TEXTURE_GEN_Q)) { + || cap == GL11.GL_COLOR_LOGIC_OP || cap == GL14.GL_COLOR_SUM || cap == GL30.GL_RASTERIZER_DISCARD + || cap == GL13.GL_SAMPLE_ALPHA_TO_COVERAGE || cap == GL13.GL_SAMPLE_ALPHA_TO_ONE || cap == GL13.GL_SAMPLE_COVERAGE + || (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES)) { beforeUncapturedStateChange(); } } + public static void beforeUncapturedTextureUnitChange(int cap, int unit) { + if (cap == GL11.GL_TEXTURE_2D && unit <= 1) return; + beforeUncapturedStateChange(); + } + private static void beforeMatrixChange() { final GLContextState c = ctx(); if (c.matrixMode.getMode() == GL11.GL_PROJECTION @@ -1966,6 +1970,7 @@ public class GLStateManager { private static void changeSecondaryColor(float red, float green, float blue) { final GLContextState glCtx = ctx(); if (!isCachingEnabled() || red != glCtx.secondaryColor.getRed() || green != glCtx.secondaryColor.getGreen() || blue != glCtx.secondaryColor.getBlue()) { + if (glCtx.colorSumState.isEnabled()) beforeUncapturedStateChange(); mod(glCtx.secondaryColor); glCtx.secondaryColor.setRed(red); glCtx.secondaryColor.setGreen(green); @@ -2840,6 +2845,7 @@ public class GLStateManager { return; } } + if (!isCachingEnabled() || ctx().drawBuffer.getValue() != mode) beforeUncapturedStateChange(); if (isCachingEnabled()) mod(ctx().drawBuffer).setValue(mode); RENDER_BACKEND.drawBuffer(mode); } @@ -3398,6 +3404,7 @@ public class GLStateManager { return; } } + if (!isCachingEnabled() || ctx().logicOpMode.getValue() != opcode) beforeUncapturedStateChange(); if (isCachingEnabled()) mod(ctx().logicOpMode).setValue(opcode); RENDER_BACKEND.logicOp(opcode); } @@ -5673,7 +5680,9 @@ public class GLStateManager { } public static void glDepthRange(double near, double far) { - if (isCachingEnabled()) mod(ctx().viewportState).setDepthRange(near, far); + final GLContextState glCtx = ctx(); + if (!isCachingEnabled() || glCtx.viewportState.depthRangeNear != near || glCtx.viewportState.depthRangeFar != far) beforeUncapturedStateChange(); + if (isCachingEnabled()) mod(glCtx.viewportState).setDepthRange(near, far); RENDER_BACKEND.depthRange(near, far); } @@ -6120,24 +6129,19 @@ public class GLStateManager { } // Track front/back separately in cache (Mesa compat semantics), but always issue GL_FRONT_AND_BACK to the driver (core profile constraint). final boolean caching = isCachingEnabled(); - final boolean needsUpdate; - if (face == GL11.GL_FRONT) { - needsUpdate = !caching || glCtx.polygonState.getFrontMode() != polygonMode; - if (caching && needsUpdate) mod(glCtx.polygonState).setFrontMode(polygonMode); - } else if (face == GL11.GL_BACK) { - needsUpdate = !caching || glCtx.polygonState.getBackMode() != polygonMode; - if (caching && needsUpdate) mod(glCtx.polygonState).setBackMode(polygonMode); - } else { // GL_FRONT_AND_BACK - needsUpdate = !caching || glCtx.polygonState.getFrontMode() != polygonMode || glCtx.polygonState.getBackMode() != polygonMode; - if (caching && needsUpdate) { - mod(glCtx.polygonState); - glCtx.polygonState.setFrontMode(polygonMode); - glCtx.polygonState.setBackMode(polygonMode); - } - } - if (needsUpdate) { - RENDER_BACKEND.polygonMode(GL11.GL_FRONT_AND_BACK, polygonMode); + final boolean front = face != GL11.GL_BACK; + final boolean back = face != GL11.GL_FRONT; + final boolean needsUpdate = !caching + || (front && glCtx.polygonState.getFrontMode() != polygonMode) + || (back && glCtx.polygonState.getBackMode() != polygonMode); + if (!needsUpdate) return; + beforeUncapturedStateChange(); + if (caching) { + mod(glCtx.polygonState); + if (front) glCtx.polygonState.setFrontMode(polygonMode); + if (back) glCtx.polygonState.setBackMode(polygonMode); } + RENDER_BACKEND.polygonMode(GL11.GL_FRONT_AND_BACK, polygonMode); } public static void glPolygonOffset(float factor, float units) { @@ -6356,6 +6360,7 @@ public class GLStateManager { return; } } + beforeUncapturedStateChange(); RENDER_BACKEND.drawBuffers(buffer); } @@ -6367,6 +6372,7 @@ public class GLStateManager { return; } } + beforeUncapturedStateChange(); RENDER_BACKEND.drawBuffers(bufs); } @@ -6375,6 +6381,7 @@ public class GLStateManager { if (DisplayListManager.isRecording()) { throw DisplayListManager.unsupportedInList("glSampleCoverage"); } + beforeUncapturedStateChange(); RENDER_BACKEND.sampleCoverage(value, invert); } @@ -8511,6 +8518,56 @@ public class GLStateManager { return ctx().backMaterial; } + public static void captureLighting(LightingSnapshot out) { + final GLContextState glCtx = ctx(); + for (int i = 0; i < out.lights.length; i++) { + out.lightEnabled[i] = glCtx.lightStates[i].isEnabled(); + out.lights[i].set(glCtx.lightDataStates[i]); + } + out.lightModel.set(glCtx.lightModel); + out.frontMaterial.set(glCtx.frontMaterial); + out.backMaterial.set(glCtx.backMaterial); + out.colorMaterial = glCtx.colorMaterial.isEnabled(); + out.colorMaterialFace = glCtx.colorMaterialFace.getValue(); + out.colorMaterialParameter = glCtx.colorMaterialParameter.getValue(); + out.normalize = glCtx.normalizeState.isEnabled(); + out.rescaleNormal = glCtx.rescaleNormalState.isEnabled(); + } + + public static void applyLighting(LightingSnapshot in) { + final GLContextState glCtx = ctx(); + boolean changed = false; + for (int i = 0; i < in.lights.length; i++) { + glCtx.lightStates[i].setEnabled(in.lightEnabled[i]); + if (!glCtx.lightDataStates[i].sameAs(in.lights[i])) { + mod(glCtx.lightDataStates[i]).set(in.lights[i]); + changed = true; + } + } + if (!glCtx.lightModel.sameAs(in.lightModel)) { + mod(glCtx.lightModel).set(in.lightModel); + changed = true; + } + if (!glCtx.frontMaterial.sameAs(in.frontMaterial)) { + mod(glCtx.frontMaterial).set(in.frontMaterial); + changed = true; + } + if (!glCtx.backMaterial.sameAs(in.backMaterial)) { + mod(glCtx.backMaterial).set(in.backMaterial); + changed = true; + } + if (glCtx.colorMaterialFace.getValue() != in.colorMaterialFace || glCtx.colorMaterialParameter.getValue() != in.colorMaterialParameter) { + mod(glCtx.colorMaterialFace).setValue(in.colorMaterialFace); + mod(glCtx.colorMaterialParameter).setValue(in.colorMaterialParameter); + changed = true; + } + // Direct set: glEnable(GL_COLOR_MATERIAL) would bake the current color over the captured material. + glCtx.colorMaterial.setEnabled(in.colorMaterial); + glCtx.normalizeState.setEnabled(in.normalize); + glCtx.rescaleNormalState.setEnabled(in.rescaleNormal); + if (changed) glCtx.lightingGeneration++; + } + public static ViewPortStateStack getViewportState() { return ctx().viewportState; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/LightingSnapshot.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/LightingSnapshot.java new file mode 100644 index 000000000..bef8b2bf3 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/LightingSnapshot.java @@ -0,0 +1,26 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.glsm.ffp.VertexKey; +import com.gtnewhorizons.angelica.glsm.states.LightModelState; +import com.gtnewhorizons.angelica.glsm.states.LightState; +import com.gtnewhorizons.angelica.glsm.states.MaterialState; +import org.lwjgl.opengl.GL11; + +public final class LightingSnapshot { + final boolean[] lightEnabled = new boolean[VertexKey.FFP_LIGHT_COUNT]; + final LightState[] lights = new LightState[VertexKey.FFP_LIGHT_COUNT]; + final LightModelState lightModel = new LightModelState(); + final MaterialState frontMaterial = new MaterialState(GL11.GL_FRONT); + final MaterialState backMaterial = new MaterialState(GL11.GL_BACK); + boolean colorMaterial; + int colorMaterialFace; + int colorMaterialParameter; + boolean normalize; + boolean rescaleNormal; + + public LightingSnapshot() { + for (int i = 0; i < lights.length; i++) { + lights[i] = new LightState(GL11.GL_LIGHT0 + i); + } + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/StateSet.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/StateSet.java index bc8509651..eee819af5 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/StateSet.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/StateSet.java @@ -88,10 +88,15 @@ public final class StateSet { GLStateManager.getActiveTextureUnitStack(), GLStateManager.getBlendMode(), GLStateManager.getAlphaTest(), GLStateManager.getDepthTest(), GLStateManager.getLightingState(), GLStateManager.getCullState(), GLStateManager.getPolygonOffsetFillState(), - GLStateManager.getTextures().getTextureUnitStates(0) + GLStateManager.getTextures().getTextureUnitStates(0), GLStateManager.getTextures().getTextureUnitStates(1), + GLStateManager.getLightStates()[0], GLStateManager.getLightStates()[1], + GLStateManager.getLightDataStates()[0], GLStateManager.getLightDataStates()[1], + GLStateManager.getColorMaterial(), GLStateManager.getColorMaterialFace(), GLStateManager.getColorMaterialParameter(), + GLStateManager.getLightModel(), GLStateManager.getFrontMaterial(), GLStateManager.getBackMaterial(), + GLStateManager.getNormalizeState(), GLStateManager.getRescaleNormalState() ), R_BLEND | R_DEPTH | R_COLOR_MASK | R_POLYGON | R_TEXTURE | R_ACTIVE_UNIT, - B_FRAG_COLORBUF, + B_FRAG_COLORBUF | B_LIGHTING, true); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/TextureUtilHooks.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/TextureUtilHooks.java index e0be18f53..71b893298 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/TextureUtilHooks.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/TextureUtilHooks.java @@ -1,14 +1,28 @@ package com.gtnewhorizons.angelica.glsm.hooks; import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLContextState; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public final class TextureUtilHooks { + private static int pausedTexture; + private static int pausedMin; + private static int pausedMag; + private static float pausedAniso; + + private static int nearestTexture; + private static int nearestMin; + private static int nearestMag; + private static float nearestAniso; + private TextureUtilHooks() {} public static void setMaxLevel(int mipmapLevels) { @@ -16,7 +30,17 @@ public final class TextureUtilHooks { } public static void captureBoundFilterTexture() { - GLStateManager.ctx().savedFilterTextureId = GLStateManager.getBoundTextureForServerState(); + final GLContextState ctx = GLStateManager.ctx(); + final int id = GLStateManager.getBoundTextureForServerState(); + ctx.savedFilterTextureId = id; + final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(id); + if (info != null) { + ctx.savedFilterMin = info.getMinFilter(); + ctx.savedFilterMag = info.getMagFilter(); + ctx.savedFilterAniso = info.getMaxAnisotropy(); + } else { + ctx.savedFilterMin = -1; + } } public static void clearSavedFilterTexture() { @@ -42,4 +66,61 @@ public final class TextureUtilHooks { GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); } } + + public static boolean pauseTemporaryFilter() { + final GLContextState ctx = GLStateManager.ctx(); + final int id = ctx.savedFilterTextureId; + if (id == 0 || pausedTexture != 0 || ctx.savedFilterMin < 0 + || DisplayListManager.getRecordMode() != DisplayListManager.RecordMode.NONE) return false; + final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(id); + if (info == null) return false; + pausedTexture = id; + pausedMin = info.getMinFilter(); + pausedMag = info.getMagFilter(); + pausedAniso = info.getMaxAnisotropy(); + setFilter(id, ctx.savedFilterMin, ctx.savedFilterMag, ctx.savedFilterAniso); + return true; + } + + public static void resumeTemporaryFilter() { + if (pausedTexture == 0) return; + final int id = pausedTexture; + pausedTexture = 0; + setFilter(id, pausedMin, pausedMag, pausedAniso); + } + + /** TextureUtil.func_152777_a(false, false, 1) without using vanilla's single save slot, which the caller may hold. */ + public static void forceNearestFilter() { + final int id = GLStateManager.getBoundTextureForServerState(); + final TextureInfo info = id != 0 ? TextureInfoCache.INSTANCE.getInfo(id) : null; + if (info == null) { + nearestTexture = 0; + return; + } + nearestTexture = id; + nearestMin = info.getMinFilter(); + nearestMag = info.getMagFilter(); + nearestAniso = info.getMaxAnisotropy(); + setFilter(id, GL11.GL_NEAREST, GL11.GL_NEAREST, 1.0f); + } + + public static void restoreFilterAfterNearest() { + if (nearestTexture == 0) return; + final int id = nearestTexture; + nearestTexture = 0; + setFilter(id, nearestMin, nearestMag, nearestAniso); + } + + private static void setFilter(int id, int min, int mag, float aniso) { + final boolean anisotropic = BackendManager.RENDER_BACKEND.isAnisotropicSupported(); + if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.NONE) { + RenderSystem.texParameteri(id, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, min); + RenderSystem.texParameteri(id, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag); + if (anisotropic) RenderSystem.texParameterf(id, GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); + } else { + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, min); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag); + if (anisotropic) GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); + } + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java index 764ac965d..26d165aab 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/TextureUnitBooleanStateStack.java @@ -24,6 +24,9 @@ public final class TextureUnitBooleanStateStack extends BooleanStateStack { @Override public void setEnabled(boolean enabled) { + if (!GLStateManager.isCachingEnabled() || enabled != this.enabled) { + GLStateManager.beforeUncapturedTextureUnitChange(glCap, unitIndex); + } beforeModify(); setEnabledWithUnitSwitch(enabled); } diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateSet_GLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateSet_GLTest.java index 4a54bc104..2d93053dc 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateSet_GLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_StateSet_GLTest.java @@ -706,4 +706,48 @@ public class GLSM_StateSet_GLTest { GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE); } } + + @Test + void batchAppliesPassLightingAndRestoresLiveLighting() { + final boolean lightmapWas = GLStateManager.getTextures().getTextureUnitStates(1).isEnabled(); + final LightingSnapshot pass = new LightingSnapshot(); + try { + GLStateManager.glEnable(GL11.GL_LIGHT0); + GLStateManager.glEnable(GL11.GL_LIGHT1); + GLStateManager.enableColorMaterial(); + GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 2.0f); + GLStateManager.captureLighting(pass); + + GLStateManager.glDisable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_LIGHT1); + GLStateManager.disableColorMaterial(); + GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 1.0f); + GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(false); + final int liveGeneration = GLStateManager.getLightingGeneration(); + + final int d = GLStateManager.pushState(StateSet.BATCH); + GLStateManager.applyLighting(pass); + GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(true); + assertTrue(GLStateManager.getLightStates()[0].isEnabled(), "light 0 from the pass"); + assertTrue(GLStateManager.getLightStates()[1].isEnabled(), "light 1 from the pass"); + assertTrue(GLStateManager.getColorMaterial().isEnabled(), "color material from the pass"); + assertEquals(2.0f, GLStateManager.getLightDataStates()[0].constantAttenuation, "light 0 data from the pass"); + assertTrue(GLStateManager.getLightingGeneration() != liveGeneration, "lighting uniforms marked dirty"); + final int passGeneration = GLStateManager.getLightingGeneration(); + GLStateManager.popStateTo(d); + + assertFalse(GLStateManager.getLightStates()[0].isEnabled(), "light 0 restored by BATCH pop"); + assertFalse(GLStateManager.getLightStates()[1].isEnabled(), "light 1 restored by BATCH pop"); + assertFalse(GLStateManager.getColorMaterial().isEnabled(), "color material restored by BATCH pop"); + assertEquals(1.0f, GLStateManager.getLightDataStates()[0].constantAttenuation, "light 0 data restored by BATCH pop"); + assertFalse(GLStateManager.getTextures().getTextureUnitStates(1).isEnabled(), "lightmap enable restored by BATCH pop"); + assertTrue(GLStateManager.getLightingGeneration() != passGeneration, "lighting uniforms marked dirty after pop"); + } finally { + GLStateManager.glDisable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_LIGHT1); + GLStateManager.disableColorMaterial(); + GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 1.0f); + GLStateManager.getTextures().getTextureUnitStates(1).setEnabled(lightmapWas); + } + } } diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ReadbackFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ReadbackFixture.java index 110026b69..646848da7 100644 --- a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ReadbackFixture.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ReadbackFixture.java @@ -96,7 +96,7 @@ public final class ReadbackFixture { public static void assertFloatsNear(ByteBuffer buf, int offset, float[] expected, String label) { for (int i = 0; i < expected.length; i++) { final int idx = i; - assertEquals(expected[i], buf.getFloat(offset + i * 4), 1e-6f, () -> label + " float " + idx); + assertEquals(expected[i], buf.getFloat(offset + i * 4), 1f / 4096f, () -> label + " float " + idx); } } 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 792f4f756..60bd92199 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -17,6 +17,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.mixins.interfaces.FontRendererAccessor; +import com.gtnewhorizons.angelica.rendering.tesr.BatchDrawDefaults; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -153,6 +154,7 @@ public class BatchingFontRenderer { /** {@code OpenGlHelper.lightmapTexUnit} */ private static final int LIGHTMAP_TEX_UNIT = 1; + private static final int FULL_BRIGHT_LIGHT = GLSMConfig.packBrightness(240.0f, 240.0f); private static int rawCapacity = INITIAL_BATCH_SIZE * VERTEX_SIZE; private static ByteBuffer vertexData = memAlloc(rawCapacity); private static long vertexDataAddress = memAddress0(vertexData); @@ -188,6 +190,7 @@ public class BatchingFontRenderer { private float lightmapV = 0.0f; private boolean lightmapActive = false; private int lightmapTextureId = 0; + private int lightmapPackedLight = -1; private final Vector3f lightingFactor = new Vector3f(1.0f, 1.0f, 1.0f); private boolean lightingFactorActive = false; @@ -214,7 +217,8 @@ public class BatchingFontRenderer { private void captureLightmapState() { final int unitBinding = GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding(); - final boolean active = isWorldSpaceText() && unitBinding != 0; + final boolean active = isWorldSpaceText() && unitBinding != 0 + && GLStateManager.getTextures().getTextureUnitStates(LIGHTMAP_TEX_UNIT).isEnabled(); float u = 0.0f; float v = 0.0f; @@ -226,8 +230,9 @@ public class BatchingFontRenderer { v = scratchLightmapUv.y; texture = unitBinding; } + final int packedLight = active ? GLSMConfig.packedLastBrightness() : FULL_BRIGHT_LIGHT; - if (active == lightmapActive && u == lightmapU && v == lightmapV && texture == lightmapTextureId) { + if (active == lightmapActive && u == lightmapU && v == lightmapV && texture == lightmapTextureId && packedLight == lightmapPackedLight) { return; } sealBatchSegment(); @@ -235,6 +240,7 @@ public class BatchingFontRenderer { lightmapU = u; lightmapV = v; lightmapTextureId = texture; + lightmapPackedLight = packedLight; } private static final class TextSegment { @@ -261,6 +267,7 @@ public class BatchingFontRenderer { private int deferredCmdWatermark; private static final ObjectArrayList deferredSegments = ObjectArrayList.wrap(new TextSegment[16], 0); + private static final BatchDrawDefaults DEFERRED_DRAW_DEFAULTS = new BatchDrawDefaults(); private static final ObjectArrayList deferredSegmentPool = ObjectArrayList.wrap(new TextSegment[16], 0); private final Matrix4f batchProj = new Matrix4f(); @@ -532,7 +539,7 @@ public class BatchingFontRenderer { segment.lightmapU = lightmapU; segment.lightmapV = lightmapV; segment.lightmapTexture = lightmapTextureId; - segment.packedLight = GLSMConfig.packedLastBrightness(); + segment.packedLight = lightmapPackedLight; final Vector3f normal = ShaderManager.getCurrentNormal(); segment.normalX = normal.x; segment.normalY = normal.y; @@ -617,21 +624,26 @@ public class BatchingFontRenderer { public static void flushDeferredText() { if (deferredSegments.isEmpty()) return; - if (deferredSegments.getFirst().owner.shouldDrawThroughPipeline()) { - flushDeferredThroughPipeline(); - return; - } - - final boolean locked = GLStateManager.acquireDrawLock(); + DEFERRED_DRAW_DEFAULTS.apply(); try { - GLStateManager.beginForeignDraw(); + if (deferredSegments.getFirst().owner.shouldDrawThroughPipeline()) { + flushDeferredThroughPipeline(); + return; + } + + final boolean locked = GLStateManager.acquireDrawLock(); try { - flushDeferredTextInner(); + GLStateManager.beginForeignDraw(); + try { + flushDeferredTextInner(); + } finally { + GLStateManager.endForeignDraw(); + } } finally { - GLStateManager.endForeignDraw(); + if (locked) GLStateManager.releaseDrawLock(); } } finally { - if (locked) GLStateManager.releaseDrawLock(); + DEFERRED_DRAW_DEFAULTS.restore(); } } @@ -641,6 +653,7 @@ public class BatchingFontRenderer { final int d = GLStateManager.pushState(StateSet.FONT_PIPELINE); try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); GLStateManager.enableTexture(); GLStateManager.enableAlphaTest(); GLStateManager.enableBlend(); @@ -688,6 +701,7 @@ public class BatchingFontRenderer { final int d = GLStateManager.pushState(StateSet.FONT); try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); deferredSegments.get(0).owner.setupFontDrawState(); GLStateManager.glDepthMask(false); flushLastTexture = DUMMY_RESOURCE_LOCATION; @@ -997,7 +1011,7 @@ public class BatchingFontRenderer { CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId); final Vector3f normal = ShaderManager.getCurrentNormal(); emitRangeThroughPipeline(this, cmdsData, batchSealedEnd, cmdCount, - GLSMConfig.packedLastBrightness(), normal.x, normal.y, normal.z); + lightmapPackedLight, normal.x, normal.y, normal.z); } } finally { GLStateManager.glPopMatrix(); @@ -1091,6 +1105,7 @@ public class BatchingFontRenderer { lightmapU = 0.0f; lightmapV = 0.0f; lightmapTextureId = 0; + lightmapPackedLight = -1; } // === Actual text mesh generation diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java index 672eff7d5..6f3076a69 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java @@ -5,6 +5,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.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.TextureUtilHooks; import com.gtnewhorizons.angelica.rendering.tesr.DrawState; import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import it.unimi.dsi.fastutil.Hash; @@ -18,7 +19,6 @@ import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.layer.PassOverride; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -86,20 +86,20 @@ public final class RenderLayer implements BlendingStateHolder { this.hash = h; } - public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) { - return tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false); + public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap) { + return tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, lightmap, false); } - public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) { - return build(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false, afterGlint); + public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) { + return build(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, lightmap, false, afterGlint); } - public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material, int cull, boolean lit) { - return build(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT, cull, lit, true, false); + public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material, int cull, boolean lit, boolean lightmap) { + return build(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT, cull, lit, lightmap, true, false); } - private static RenderLayer build(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean noPass, boolean afterGlint) { - final DrawState state = DrawState.forMaterial(material, cull, lit, offsetFactor, offsetUnits); + private static RenderLayer build(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean noPass, boolean afterGlint) { + final DrawState state = DrawState.forMaterial(material, cull, lit, lightmap, offsetFactor, offsetUnits); final Hook hook = hookFor(material, noPass ? PassOverride.NONE : pass, glintSlot); final TransparencyType transparency = afterGlint ? TransparencyType.AFTER_GLINT : transparencyFor(state.getBlend()); final RenderLayer candidate = new RenderLayer(null, BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, @@ -110,7 +110,7 @@ public final class RenderLayer implements BlendingStateHolder { retained.name = "angelica_tesr_" + (noPass ? "nopass_" : "") + material.transparency().name().toLowerCase(Locale.ROOT) + (noPass ? "" : pass.nameSuffix()) + (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits) - + "_cull" + state.getCull() + (state.isLit() ? "_lit" : "") + + "_cull" + state.getCull() + (state.isLit() ? "_lit" : "") + (state.isLightmap() ? "" : "_nolightmap") + (glintSlot == ShaderGlint.NO_TINT ? "" : "_tint" + glintSlot) + (afterGlint ? "_after_glint" : ""); } return retained; @@ -204,7 +204,7 @@ public final class RenderLayer implements BlendingStateHolder { Minecraft.getMinecraft().getTextureManager().bindTexture(textureId); if (unfilteredAtlas) { filtering = true; - TextureUtil.func_152777_a(false, false, 1.0F); + TextureUtilHooks.forceNearestFilter(); } } else { GLStateManager.disableTexture(); @@ -223,7 +223,7 @@ public final class RenderLayer implements BlendingStateHolder { } if (filtering) { try { - TextureUtil.func_147945_b(); + TextureUtilHooks.restoreFilterAfterNearest(); } catch (Throwable cleanup) { RenderFailures.suppress(failure, cleanup); } @@ -241,7 +241,7 @@ public final class RenderLayer implements BlendingStateHolder { } finally { if (textureId != null && unfilteredAtlas) { try { - TextureUtil.func_147945_b(); + TextureUtilHooks.restoreFilterAfterNearest(); } catch (Throwable cleanup) { failure = RenderFailures.suppress(failure, cleanup); } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchDrawDefaults.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchDrawDefaults.java new file mode 100644 index 000000000..a296d953a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchDrawDefaults.java @@ -0,0 +1,79 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.TextureUtilHooks; +import net.coderbot.iris.gl.blending.DepthColorStorage; +import net.coderbot.iris.gl.program.Program; +import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.layer.PassOverride; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL30; + +public final class BatchDrawDefaults { + private static final Matrix4f IDENTITY = new Matrix4f(); + private static int passFramebuffer = -1; + + private final Matrix4f callerTextureMatrix = new Matrix4f(); + private int callerFramebuffer = -1; + private int callerProgram; + private boolean textureMatrixReset; + private boolean filterPaused; + private boolean overridesCleared; + + public static void capturePassFramebuffer() { + passFramebuffer = GLStateManager.getDrawFramebuffer(); + } + + public void apply() { + if (passFramebuffer >= 0 && TesrBatchRenderer.deferredPipeline() == null) { + final int framebuffer = GLStateManager.getDrawFramebuffer(); + if (framebuffer != passFramebuffer) { + callerFramebuffer = framebuffer; + GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, passFramebuffer); + } + } + final int program = GLStateManager.getActiveProgram(); + if (program != 0 && !Program.isManagedBind(program) && !DepthColorStorage.isOwnedProgram(program)) { + callerProgram = program; + GLStateManager.glUseProgram(0); + } + final Matrix4f textureMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0); + if (!MatrixHelper.isIdentity(textureMatrix)) { + callerTextureMatrix.set(textureMatrix); + GLStateManager.setTextureMatrix(0, IDENTITY); + textureMatrixReset = true; + } + filterPaused = TextureUtilHooks.pauseTemporaryFilter(); + if (GbufferPrograms.getSpecialCondition() != null || GbufferPrograms.getDeclaredTranslucency() != null + || GbufferPrograms.getOverridePhase() != null) { + PassOverride.NONE.apply(); + overridesCleared = true; + } + } + + public void restore() { + if (overridesCleared) { + overridesCleared = false; + PassOverride.NONE.clear(); + } + if (filterPaused) { + filterPaused = false; + TextureUtilHooks.resumeTemporaryFilter(); + } + if (textureMatrixReset) { + textureMatrixReset = false; + GLStateManager.setTextureMatrix(0, callerTextureMatrix); + } + if (callerProgram != 0) { + final int program = callerProgram; + callerProgram = 0; + GLStateManager.glUseProgram(program); + } + if (callerFramebuffer >= 0) { + final int framebuffer = callerFramebuffer; + callerFramebuffer = -1; + GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, framebuffer); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/DrawState.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/DrawState.java index e99be7b5d..d9ab38eab 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/DrawState.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/DrawState.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.rendering.tesr; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.PolygonState; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; import lombok.Getter; @@ -15,6 +16,8 @@ public final class DrawState { public static final int CULL_BACK = 1; public static final int CULL_FRONT = 2; public static final int CULL_BOTH = 3; + public static final int FRONT_FACE_CLOCKWISE = 4; + private static final int CULL_FACE_MASK = 3; public static final int OPAQUE = 0; public static final int TRANSLUCENT = 1; @@ -22,6 +25,8 @@ public final class DrawState { public static final int ADDITIVE_ALPHA = 3; public static final int GLINT = 4; + private static final int LIGHTMAP_UNIT = 1; + private static final ObjectOpenCustomHashSet CACHE = new ObjectOpenCustomHashSet<>(HashStrategy.INSTANCE); static void clearInterning() { @@ -39,11 +44,12 @@ public final class DrawState { @Getter private final boolean colorWrite; @Getter private final float alphaCutoff; @Getter private final boolean lit; + @Getter private final boolean lightmap; @Getter private final float offsetFactor; @Getter private final float offsetUnits; private final int hash; - private DrawState(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, float offsetFactor, float offsetUnits) { + private DrawState(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, boolean lightmap, float offsetFactor, float offsetUnits) { this.cull = cull; this.blend = blend; this.depthEqual = depthEqual; @@ -51,6 +57,7 @@ public final class DrawState { this.colorWrite = colorWrite; this.alphaCutoff = alphaCutoff; this.lit = lit; + this.lightmap = lightmap; this.offsetFactor = offsetFactor; this.offsetUnits = offsetUnits; int h = cull; @@ -60,16 +67,17 @@ public final class DrawState { h = h * 31 + (colorWrite ? 1 : 0); h = h * 31 + Float.floatToIntBits(alphaCutoff); h = h * 31 + (lit ? 1 : 0); + h = h * 31 + (lightmap ? 1 : 0); h = h * 31 + Float.floatToIntBits(offsetFactor); h = h * 31 + Float.floatToIntBits(offsetUnits); this.hash = h; } - public static DrawState of(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, float offsetFactor, float offsetUnits) { - return CACHE.addOrGet(new DrawState(cull, blend, depthEqual, depthWrite, colorWrite, alphaCutoff, lit, offsetFactor, offsetUnits)); + public static DrawState of(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, boolean lightmap, float offsetFactor, float offsetUnits) { + return CACHE.addOrGet(new DrawState(cull, blend, depthEqual, depthWrite, colorWrite, alphaCutoff, lit, lightmap, offsetFactor, offsetUnits)); } - public static DrawState forMaterial(TesrMaterial material, int cull, boolean lit, float offsetFactor, float offsetUnits) { + public static DrawState forMaterial(TesrMaterial material, int cull, boolean lit, boolean lightmap, float offsetFactor, float offsetUnits) { return of(material.isNoCull() ? DISABLED : cull, blendFor(material.transparency()), material.isDepthEqual(), @@ -77,6 +85,7 @@ public final class DrawState { !material.isDepthOnly(), material.cutoutAlpha(), lit && !material.isUnlit(), + lightmap, offsetFactor, offsetUnits); } @@ -100,13 +109,19 @@ public final class DrawState { } public static int liveCull() { - return packCull(GLStateManager.getCullState().isEnabled(), GLStateManager.getPolygonState().getCullFaceMode()); + final PolygonState polygon = GLStateManager.getPolygonState(); + final int cull = packCull(GLStateManager.getCullState().isEnabled(), polygon.getCullFaceMode()); + return cull != DISABLED && polygon.getFrontFace() == GL11.GL_CW ? cull | FRONT_FACE_CLOCKWISE : cull; } public static boolean liveLit(TesrMaterial material) { return GLStateManager.getLightingState().isEnabled() && !material.isUnlit(); } + public static boolean liveLightmap() { + return GLStateManager.getTextures().getTextureUnitStates(LIGHTMAP_UNIT).isEnabled(); + } + public void apply() { switch (blend) { case TRANSLUCENT -> { @@ -145,8 +160,9 @@ public final class DrawState { } else { GLStateManager.disableLighting(); } + GLStateManager.getTextures().getTextureUnitStates(LIGHTMAP_UNIT).setEnabled(lightmap); - switch (cull) { + switch (cull & CULL_FACE_MASK) { case CULL_BACK -> { GLStateManager.enableCull(); GLStateManager.glCullFace(GL11.GL_BACK); @@ -161,6 +177,7 @@ public final class DrawState { } default -> GLStateManager.disableCull(); } + GLStateManager.glFrontFace((cull & FRONT_FACE_CLOCKWISE) != 0 ? GL11.GL_CW : GL11.GL_CCW); if (offsetFactor != 0.0f || offsetUnits != 0.0f) { GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); @@ -183,7 +200,7 @@ public final class DrawState { @Override public String toString() { - return "DrawState[cull=" + cull + ", blend=" + blend + ", depthEqual=" + depthEqual + ", depthWrite=" + depthWrite + ", colorWrite=" + colorWrite + ", alphaCutoff=" + alphaCutoff + ", lit=" + lit + ", offset=" + offsetFactor + '/' + offsetUnits + ']'; + return "DrawState[cull=" + cull + ", blend=" + blend + ", depthEqual=" + depthEqual + ", depthWrite=" + depthWrite + ", colorWrite=" + colorWrite + ", alphaCutoff=" + alphaCutoff + ", lit=" + lit + ", lightmap=" + lightmap + ", offset=" + offsetFactor + '/' + offsetUnits + ']'; } private enum HashStrategy implements Hash.Strategy { @@ -198,7 +215,7 @@ public final class DrawState { public boolean equals(@Nullable DrawState a, @Nullable DrawState b) { if (a == b) return true; if (a == null || b == null) return false; - return a.cull == b.cull && a.blend == b.blend && a.depthEqual == b.depthEqual && a.depthWrite == b.depthWrite && a.colorWrite == b.colorWrite && Float.floatToIntBits(a.alphaCutoff) == Float.floatToIntBits(b.alphaCutoff) && a.lit == b.lit && Float.floatToIntBits(a.offsetFactor) == Float.floatToIntBits(b.offsetFactor) && Float.floatToIntBits(a.offsetUnits) == Float.floatToIntBits(b.offsetUnits); + return a.cull == b.cull && a.blend == b.blend && a.depthEqual == b.depthEqual && a.depthWrite == b.depthWrite && a.colorWrite == b.colorWrite && Float.floatToIntBits(a.alphaCutoff) == Float.floatToIntBits(b.alphaCutoff) && a.lit == b.lit && a.lightmap == b.lightmap && Float.floatToIntBits(a.offsetFactor) == Float.floatToIntBits(b.offsetFactor) && Float.floatToIntBits(a.offsetUnits) == Float.floatToIntBits(b.offsetUnits); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java index 061011e40..572a4cef2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java @@ -164,7 +164,7 @@ final class EntityShadowBatcher { private RenderLayer layer() { RenderLayer l = layer; if (l == null) { - l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F, ShaderGlint.NO_TINT, DrawState.CULL_BACK, false); + l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F, ShaderGlint.NO_TINT, DrawState.CULL_BACK, false, true); layer = l; } return l; 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 6840f4067..936673244 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java @@ -155,14 +155,16 @@ public final class ModelPartBatcher { int glintSlot; int cull; boolean lit; + boolean lightmap; boolean afterGlint; - boolean matches(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) { + boolean matches(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) { return this.texture == texture && this.material == material && pass.equals(this.pass) && this.offsetFactor == offsetFactor - && this.offsetUnits == offsetUnits && this.glintSlot == glintSlot && this.cull == cull && this.lit == lit && this.afterGlint == afterGlint; + && this.offsetUnits == offsetUnits && this.glintSlot == glintSlot && this.cull == cull && this.lit == lit && this.lightmap == lightmap + && this.afterGlint == afterGlint; } - LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) { + LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) { this.texture = texture; this.material = material; this.pass = pass; @@ -171,6 +173,7 @@ public final class ModelPartBatcher { this.glintSlot = glintSlot; this.cull = cull; this.lit = lit; + this.lightmap = lightmap; this.afterGlint = afterGlint; return this; } @@ -182,7 +185,7 @@ public final class ModelPartBatcher { && Objects.equals(pass, other.pass) && Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor) && Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits) - && glintSlot == other.glintSlot && cull == other.cull && lit == other.lit && afterGlint == other.afterGlint; + && glintSlot == other.glintSlot && cull == other.cull && lit == other.lit && lightmap == other.lightmap && afterGlint == other.afterGlint; } @Override @@ -193,6 +196,7 @@ public final class ModelPartBatcher { h = h * 31 + glintSlot; h = h * 31 + cull; h = h * 31 + (lit ? 1 : 0); + h = h * 31 + (lightmap ? 1 : 0); h = h * 31 + (afterGlint ? 1 : 0); return h; } @@ -249,6 +253,8 @@ public final class ModelPartBatcher { activeGroups = shadow ? 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 (nowMs - lastSweepMs >= SWEEP_INTERVAL_MS) { lastSweepMs = nowMs; @@ -440,7 +446,7 @@ public final class ModelPartBatcher { final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); final PolygonState polygon = GLStateManager.getPolygonState(); final int cullCode = EntityMaterials.ITEM_GLINT.isNoCull() ? DrawState.DISABLED : DrawState.liveCull(); - final RenderLayer layer = layerFor(HeldItemGlint.texture(), EntityMaterials.ITEM_GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, ShaderGlint.NO_TINT, cullCode, false); + final RenderLayer layer = layerFor(HeldItemGlint.texture(), EntityMaterials.ITEM_GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, ShaderGlint.NO_TINT, cullCode, false, DrawState.liveLightmap()); activeGroups.queueGlintLayers(template, layer, EntityMaterials.ITEM_GLINT, currentModelView(), GLSMConfig.packedLastBrightness(), VANILLA_GLINT_COLOR, currentOverlay(), currentEntityInfo(0), HeldItemGlint.firstMatrix(), HeldItemGlint.secondMatrix()); parts++; @@ -484,7 +490,7 @@ public final class ModelPartBatcher { final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); final PolygonState polygon = GLStateManager.getPolygonState(); final int cullCode = EntityMaterials.GLINT.isNoCull() ? DrawState.DISABLED : DrawState.liveCull(); - armorGlintLayer = layerFor(texture, EntityMaterials.GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, glintSlot, cullCode, lit); + armorGlintLayer = layerFor(texture, EntityMaterials.GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, glintSlot, cullCode, lit, DrawState.liveLightmap()); armorGlintTexture.set(textureMatrix); armorGlintColor = color; armorGlintLight = GLSMConfig.packedLastBrightness(); @@ -605,7 +611,7 @@ public final class ModelPartBatcher { final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT; final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull(); final boolean lit = DrawState.liveLit(material); - final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint); + final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, DrawState.liveLightmap(), afterGlint); // 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(); @@ -705,24 +711,24 @@ public final class ModelPartBatcher { entry.cubes = cubes; } - private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit) { - return layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, false); + 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, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean afterGlint) { + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean lightmap, boolean afterGlint) { for (int i = 0; i < RECENT_LAYERS; i++) { final RenderLayer recent = recentLayers[i]; - if (recent != null && recentKeys[i].matches(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint)) { + if (recent != null && recentKeys[i].matches(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, afterGlint)) { return lastLayer = recent; } } - RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint)); + RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, afterGlint)); if (layer == null) { - layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint); - layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint), layer); + layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, afterGlint); + layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, afterGlint), layer); } if (recentKeys[recentNext] == null) recentKeys[recentNext] = new LayerKey(); - recentKeys[recentNext].set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint); + recentKeys[recentNext].set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, lightmap, afterGlint); recentLayers[recentNext] = layer; recentNext = (recentNext + 1) % RECENT_LAYERS; return lastLayer = layer; @@ -754,7 +760,7 @@ public final class ModelPartBatcher { active = false; shaderPipeline = null; layers.clear(); - scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, false); + scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, false, false); Arrays.fill(recentLayers, null); recentNext = 0; lastLayer = null; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java index f955df453..517965918 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java @@ -88,6 +88,8 @@ public final class TesrBatchRenderer { discardDeferred(); } activePass = passKey; + bufferSource.capturePassLighting(); + BatchDrawDefaults.capturePassFramebuffer(); retained[passKey].beginPass(baseMV, camX, camY, camZ, instancedCapable() ? instancedRenderer : null, deferredPipeline()); if (passKey == PASS_MAIN_0) { final long now = System.currentTimeMillis(); @@ -175,7 +177,7 @@ public final class TesrBatchRenderer { final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull(); final boolean lit = DrawState.liveLit(material); final RenderLayer layer = layerFor(texture, material, pass, - offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f, cullCode, lit); + offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f, cullCode, lit, DrawState.liveLightmap()); final int blockEntityId = pass.isEntityPhase() ? CapturedRenderingState.INSTANCE.getCurrentRenderedEntity() : CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); @@ -209,8 +211,9 @@ public final class TesrBatchRenderer { float offsetUnits; int cull; boolean lit; + boolean lightmap; - LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cull, boolean lit) { + LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cull, boolean lit, boolean lightmap) { this.texture = texture; this.transparency = transparency; this.noCull = noCull; @@ -227,11 +230,12 @@ public final class TesrBatchRenderer { this.offsetUnits = offsetUnits; this.cull = cull; this.lit = lit; + this.lightmap = lightmap; return this; } LayerKey copy() { - return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass, pass, offsetFactor, offsetUnits, cull, lit); + return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass, pass, offsetFactor, offsetUnits, cull, lit, lightmap); } @Override @@ -245,7 +249,7 @@ public final class TesrBatchRenderer { && Objects.equals(pass, other.pass) && Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor) && Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits) - && cull == other.cull && lit == other.lit; + && cull == other.cull && lit == other.lit && lightmap == other.lightmap; } @Override @@ -266,6 +270,7 @@ public final class TesrBatchRenderer { h = h * 31 + Float.floatToIntBits(offsetUnits); h = h * 31 + cull; h = h * 31 + (lit ? 1 : 0); + h = h * 31 + (lightmap ? 1 : 0); return h; } } @@ -279,19 +284,22 @@ public final class TesrBatchRenderer { private float lastLayerOffsetUnits; private int lastLayerCull; private boolean lastLayerLit; + private boolean lastLayerLightmap; private RenderLayer lastLayer; private ResourceLocation lastImmediateTexture; private TesrMaterial lastImmediateMaterial; private int lastImmediateCull; private boolean lastImmediateLit; + private boolean lastImmediateLightmap; private RenderLayer lastImmediateLayer; - private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit) { + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit, boolean lightmap) { if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass) - && offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && cullCode == lastLayerCull && lit == lastLayerLit) { + && offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && cullCode == lastLayerCull && lit == lastLayerLit + && lightmap == lastLayerLightmap) { return lastLayer; } - final RenderLayer layer = layerLookup(texture, material, false, pass, offsetFactor, offsetUnits, cullCode, lit); + final RenderLayer layer = layerLookup(texture, material, false, pass, offsetFactor, offsetUnits, cullCode, lit, lightmap); lastLayerTexture = texture; lastLayerMaterial = material; lastLayerPass = pass; @@ -299,6 +307,7 @@ public final class TesrBatchRenderer { lastLayerOffsetUnits = offsetUnits; lastLayerCull = cullCode; lastLayerLit = lit; + lastLayerLightmap = lightmap; lastLayer = layer; return layer; } @@ -306,23 +315,26 @@ public final class TesrBatchRenderer { private RenderLayer noPassLayerFor(ResourceLocation texture, TesrMaterial material) { final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull(); final boolean lit = DrawState.liveLit(material); - if (texture == lastImmediateTexture && material == lastImmediateMaterial && cullCode == lastImmediateCull && lit == lastImmediateLit) { + final boolean lightmap = DrawState.liveLightmap(); + if (texture == lastImmediateTexture && material == lastImmediateMaterial && cullCode == lastImmediateCull && lit == lastImmediateLit + && lightmap == lastImmediateLightmap) { return lastImmediateLayer; } - final RenderLayer layer = layerLookup(texture, material, true, PassOverride.NONE, 0.0f, 0.0f, cullCode, lit); + final RenderLayer layer = layerLookup(texture, material, true, PassOverride.NONE, 0.0f, 0.0f, cullCode, lit, lightmap); lastImmediateTexture = texture; lastImmediateMaterial = material; lastImmediateCull = cullCode; lastImmediateLit = lit; + lastImmediateLightmap = lightmap; lastImmediateLayer = layer; return layer; } - private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit) { - final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass, pass, offsetFactor, offsetUnits, cullCode, lit); + private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit, boolean lightmap) { + final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass, pass, offsetFactor, offsetUnits, cullCode, lit, lightmap); RenderLayer layer = layers.get(key); if (layer == null) { - layer = noPass ? RenderLayer.tesrNoPass(texture, material, cullCode, lit) : RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, ShaderGlint.NO_TINT, cullCode, lit); + layer = noPass ? RenderLayer.tesrNoPass(texture, material, cullCode, lit, lightmap) : RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, ShaderGlint.NO_TINT, cullCode, lit, lightmap); layers.put(key.copy(), layer); } return layer; diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java index 737803712..7e5a73da3 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java @@ -2,7 +2,9 @@ package net.coderbot.batchedentityrendering.impl; import com.gtnewhorizons.angelica.rendering.RenderFailures; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.rendering.tesr.BatchDrawDefaults; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.LightingSnapshot; import com.gtnewhorizons.angelica.glsm.StateSet; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -45,6 +47,8 @@ public class AngelicaBufferSource implements Groupable { private int drawStateDepth = -1; private boolean irisStateSaved; private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY; + private LightingSnapshot passLighting; + private final BatchDrawDefaults drawDefaults = new BatchDrawDefaults(); public AngelicaBufferSource() { for (int i = 0; i < builders.length; i++) { @@ -53,6 +57,11 @@ public class AngelicaBufferSource implements Groupable { affinities.defaultReturnValue(-1); } + public void capturePassLighting() { + if (passLighting == null) passLighting = new LightingSnapshot(); + GLStateManager.captureLighting(passLighting); + } + public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) { renderOrderManager.begin(type); int affinity = affinities.getAndMoveToLast(type); @@ -188,6 +197,7 @@ public class AngelicaBufferSource implements Groupable { private void restoreDrawState() { if (drawStateDepth >= 0) { + drawDefaults.restore(); GLStateManager.popStateTo(drawStateDepth); drawStateDepth = -1; } @@ -221,6 +231,8 @@ public class AngelicaBufferSource implements Groupable { if (drawStateDepth < 0) { drawStateDepth = GLStateManager.pushState(StateSet.BATCH); GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + if (passLighting != null) GLStateManager.applyLighting(passLighting); + drawDefaults.apply(); } saveIrisState(); layer.startDrawing(); diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchStateGuardGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchStateGuardGLTest.java index edca9cdab..0ecd62528 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchStateGuardGLTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchStateGuardGLTest.java @@ -10,6 +10,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL30; import java.util.concurrent.atomic.AtomicInteger; @@ -136,6 +138,133 @@ class BatchStateGuardGLTest { } } + @Test + void perUnitCapsFlushExceptTheTexturesBatchLayersOwn() { + final AtomicInteger flushes = new AtomicInteger(); + BatchStateGuard.flush = flushes::incrementAndGet; + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + assertEquals(0, flushes.get(), "albedo and lightmap enables are stored with each layer"); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + flushes.set(0); + BatchStateGuard.flush = () -> { + assertFalse(GLStateManager.getTextures().getTextureUnitStates(2).isEnabled()); + flushes.incrementAndGet(); + }; + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + assertEquals(1, flushes.get()); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + assertEquals(1, flushes.get(), "unchanged enable does not flush"); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_S); + flushes.set(0); + BatchStateGuard.flush = flushes::incrementAndGet; + GLStateManager.glEnable(GL11.GL_TEXTURE_GEN_S); + assertEquals(1, flushes.get()); + } finally { + BatchStateGuard.flush = null; + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + } + } + + @Test + void rasterStateNotStoredWithLayersFlushesBeforeChanging() { + final AtomicInteger flushes = new AtomicInteger(); + try { + BatchStateGuard.flush = () -> { + assertEquals(GL11.GL_FILL, GLStateManager.getPolygonState().getFrontMode()); + flushes.incrementAndGet(); + }; + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); + GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); + assertEquals(1, flushes.get()); + + flushes.set(0); + BatchStateGuard.flush = () -> { + assertEquals(1.0, GLStateManager.getViewportState().depthRangeFar); + flushes.incrementAndGet(); + }; + GLStateManager.glDepthRange(0.0, 0.5); + GLStateManager.glDepthRange(0.0, 0.5); + assertEquals(1, flushes.get()); + + flushes.set(0); + BatchStateGuard.flush = flushes::incrementAndGet; + GLStateManager.glEnable(GL11.GL_COLOR_LOGIC_OP); + GLStateManager.glLogicOp(GL11.GL_XOR); + GLStateManager.glEnable(GL14.GL_COLOR_SUM); + assertEquals(3, flushes.get()); + } finally { + BatchStateGuard.flush = null; + } + } + + @Test + void sampleDrawBufferAndDiscardStateFlushesBeforeChanging() { + final AtomicInteger flushes = new AtomicInteger(); + BatchStateGuard.flush = flushes::incrementAndGet; + final int drawBuffer = GLStateManager.ctx().drawBuffer.getValue(); + try { + GLStateManager.glEnable(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE); + GLStateManager.glDisable(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE); + GLStateManager.glEnable(GL30.GL_RASTERIZER_DISCARD); + GLStateManager.glDisable(GL30.GL_RASTERIZER_DISCARD); + GLStateManager.glSampleCoverage(0.5f, false); + assertEquals(5, flushes.get()); + + flushes.set(0); + GLStateManager.glDrawBuffer(GL11.GL_NONE); + GLStateManager.glDrawBuffer(GL11.GL_NONE); + assertEquals(1, flushes.get(), "unchanged draw buffer does not flush"); + GLStateManager.glDrawBuffers(GL11.GL_NONE); + assertEquals(2, flushes.get()); + } finally { + BatchStateGuard.flush = null; + GLStateManager.glSampleCoverage(1.0f, false); + GLStateManager.glDrawBuffer(drawBuffer); + } + } + + @Test + void secondaryColorFlushesOnlyWhileColorSumIsOn() { + final AtomicInteger flushes = new AtomicInteger(); + GLStateManager.glSecondaryColor3f(0f, 0f, 0f); + BatchStateGuard.flush = flushes::incrementAndGet; + try { + GLStateManager.glSecondaryColor3f(0.5f, 0f, 0f); + assertEquals(0, flushes.get(), "secondary color is unused while color sum is off"); + GLStateManager.glEnable(GL14.GL_COLOR_SUM); + flushes.set(0); + GLStateManager.glSecondaryColor3f(0.25f, 0f, 0f); + assertEquals(1, flushes.get()); + } finally { + BatchStateGuard.flush = null; + GLStateManager.glDisable(GL14.GL_COLOR_SUM); + GLStateManager.glSecondaryColor3f(0f, 0f, 0f); + } + } + + @Test + void lightingChangesDoNotDrainBatches() { + final AtomicInteger flushes = new AtomicInteger(); + BatchStateGuard.flush = flushes::incrementAndGet; + GLStateManager.glEnable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_LIGHT0); + GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL); + GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL); + GLStateManager.glEnable(GL11.GL_NORMALIZE); + GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 2.0f); + assertEquals(0, flushes.get(), "batches draw with the lighting captured when their pass began"); + } + @Test void textureMatrixChangesDrainOtherUnitsButKeepUnitZeroInstanced() { GLStateManager.glActiveTexture(GL13.GL_TEXTURE2); diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/DrawStateTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/DrawStateTest.java index c25bca447..761473b00 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/DrawStateTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/DrawStateTest.java @@ -34,37 +34,38 @@ class DrawStateTest { @Test void equalValuesInternToOneInstance() { - assertSame(DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f), DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f)); - assertNotSame(DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f), DrawState.of(DrawState.CULL_FRONT, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f)); + assertSame(DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f), DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f)); + assertNotSame(DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f), DrawState.of(DrawState.CULL_FRONT, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f)); + assertNotSame(DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f), DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, false, 0f, 0f)); } @Test void lifecycleResetBoundsInterningAndReinternsIdentity() { DrawState.clearInterning(); - final DrawState before = DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f); - DrawState.of(DrawState.CULL_FRONT, DrawState.TRANSLUCENT, false, false, true, 0f, false, 1f, 1f); + final DrawState before = DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f); + DrawState.of(DrawState.CULL_FRONT, DrawState.TRANSLUCENT, false, false, true, 0f, false, true, 1f, 1f); assertEquals(2, DrawState.internedStateCount()); DrawState.clearInterning(); DrawState.clearInterning(); assertEquals(0, DrawState.internedStateCount()); - final DrawState after = DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f); + final DrawState after = DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f); assertNotSame(before, after); - assertSame(after, DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, 0f, 0f)); + assertSame(after, DrawState.of(DrawState.CULL_BACK, DrawState.OPAQUE, false, true, true, 0f, true, true, 0f, 0f)); } @Test void noCullMaterialNormalizesToDisabled() { final TesrMaterial noCull = TesrMaterial.builder().noCull().build(); - assertSame(DrawState.forMaterial(noCull, DrawState.CULL_FRONT, true, 0f, 0f), DrawState.forMaterial(noCull, DrawState.CULL_BACK, true, 0f, 0f)); - assertEquals(DrawState.DISABLED, DrawState.forMaterial(noCull, DrawState.CULL_FRONT, true, 0f, 0f).getCull()); + assertSame(DrawState.forMaterial(noCull, DrawState.CULL_FRONT, true, true, 0f, 0f), DrawState.forMaterial(noCull, DrawState.CULL_BACK, true, true, 0f, 0f)); + assertEquals(DrawState.DISABLED, DrawState.forMaterial(noCull, DrawState.CULL_FRONT, true, true, 0f, 0f).getCull()); } @Test void unlitMaterialNormalizesToUnlit() { final TesrMaterial unlit = TesrMaterial.builder().unlit().build(); - assertSame(DrawState.forMaterial(unlit, DrawState.CULL_BACK, true, 0f, 0f), DrawState.forMaterial(unlit, DrawState.CULL_BACK, false, 0f, 0f)); + assertSame(DrawState.forMaterial(unlit, DrawState.CULL_BACK, true, true, 0f, 0f), DrawState.forMaterial(unlit, DrawState.CULL_BACK, false, true, 0f, 0f)); } @Test diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RenderLayerInterningTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RenderLayerInterningTest.java index f0ac04810..a8813271f 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RenderLayerInterningTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RenderLayerInterningTest.java @@ -20,8 +20,8 @@ class RenderLayerInterningTest { @Test void noCullMaterialInternsToOneLayerRegardlessOfCullCode() { final TesrMaterial noCull = TesrMaterial.builder().noCull().build(); - final RenderLayer back = RenderLayer.tesr(TEX, noCull, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true); - final RenderLayer front = RenderLayer.tesr(TEX, noCull, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_FRONT, true); + final RenderLayer back = RenderLayer.tesr(TEX, noCull, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); + final RenderLayer front = RenderLayer.tesr(TEX, noCull, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_FRONT, true, true); assertSame(back, front); assertEquals(DrawState.DISABLED, back.getState().getCull()); } @@ -29,25 +29,35 @@ class RenderLayerInterningTest { @Test void unlitMaterialRequestedLitYieldsUnlitState() { final TesrMaterial unlit = TesrMaterial.builder().unlit().build(); - final RenderLayer layer = RenderLayer.tesr(TEX, unlit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true); + final RenderLayer layer = RenderLayer.tesr(TEX, unlit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); assertFalse(layer.getState().isLit()); } @Test void litMaterialRequestedUnlitYieldsUnlitStateAndDistinctLayer() { final TesrMaterial lit = TesrMaterial.builder().build(); - final RenderLayer unlitRequest = RenderLayer.tesr(TEX, lit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, false); - final RenderLayer litRequest = RenderLayer.tesr(TEX, lit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true); + final RenderLayer unlitRequest = RenderLayer.tesr(TEX, lit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, false, true); + final RenderLayer litRequest = RenderLayer.tesr(TEX, lit, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); assertFalse(unlitRequest.getState().isLit()); assertTrue(litRequest.getState().isLit()); assertNotSame(unlitRequest, litRequest); } + @Test + void lightmapIsPartOfLayerIdentity() { + final TesrMaterial material = TesrMaterial.builder().build(); + final RenderLayer withLightmap = RenderLayer.tesr(TEX, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); + final RenderLayer withoutLightmap = RenderLayer.tesr(TEX, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, false); + assertTrue(withLightmap.getState().isLightmap()); + assertFalse(withoutLightmap.getState().isLightmap()); + assertNotSame(withLightmap, withoutLightmap); + } + @Test void noPassIsPartOfStructuredInterningIdentity() { final TesrMaterial material = TesrMaterial.builder().build(); - final RenderLayer regular = RenderLayer.tesr(TEX, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true); - final RenderLayer noPass = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true); + final RenderLayer regular = RenderLayer.tesr(TEX, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); + final RenderLayer noPass = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true, true); assertNotSame(regular, noPass); } @@ -55,10 +65,10 @@ class RenderLayerInterningTest { @Test void cacheResetAllowsFreshCanonicalIdentity() { final TesrMaterial material = TesrMaterial.builder().build(); - final RenderLayer before = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true); + final RenderLayer before = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true, true); RenderLayer.clearInterningAndHooks(); - final RenderLayer first = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true); - final RenderLayer second = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true); + final RenderLayer first = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true, true); + final RenderLayer second = RenderLayer.tesrNoPass(TEX, material, DrawState.CULL_BACK, true, true); assertNotSame(before, first); assertSame(first, second); 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 25952eecb..4d1e9c266 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java @@ -553,7 +553,7 @@ class RetainedTesrGroupsGLTest { private void glintState() { GLStateManager.glViewport(0, 0, SIZE, SIZE); - layer = RenderLayer.tesr(GLINT_TEXTURE, TesrMaterial.CURRENT_STATE, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false); + layer = RenderLayer.tesr(GLINT_TEXTURE, TesrMaterial.CURRENT_STATE, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, true); GlintClock.beginFrame(123456789L); final float u0 = Reflect.getStatic(GlintClock.class, "armorU0"); @@ -872,7 +872,7 @@ class RetainedTesrGroupsGLTest { final int[] reference = FfpFixture.readRegion(SIZE); assertTrue(reference[center] != blank[center], "the mirrored quad must survive glCullFace(GL_FRONT) when drawn immediately, otherwise the parity check is vacuous: " + describe(reference[center])); - final RenderLayer culled = RenderLayer.tesr(null, RetainedTesrGroupsTest.STREAM, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, cullCode, false); + final RenderLayer culled = RenderLayer.tesr(null, RetainedTesrGroupsTest.STREAM, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, cullCode, false, true); FfpFixture.clear(); groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); groups.queue(quad, culled, RetainedTesrGroupsTest.STREAM, mirrored, 0, COLOR_ABGR, 0, 0L, 1, null); @@ -930,7 +930,7 @@ class RetainedTesrGroupsGLTest { final TemplateBuffer quad = capturedQuad(0.5); final TesrMaterial opposite = TesrMaterial.builder().build(); - final RenderLayer opposingLayer = RenderLayer.tesr(null, opposite, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false); + final RenderLayer opposingLayer = RenderLayer.tesr(null, opposite, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, true); groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); groups.queue(quad, opposingLayer, RetainedTesrGroupsTest.STREAM, new Matrix4f(), 0, COLOR_ABGR, 0, 0L, 1, null); 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 342c9510d..3e69fc5ee 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java @@ -39,7 +39,7 @@ class RetainedTesrGroupsTest { private RenderLayer layer; static RenderLayer testLayer() { - return RenderLayer.tesr(null, TesrMaterial.CURRENT_STATE, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false); + return RenderLayer.tesr(null, TesrMaterial.CURRENT_STATE, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, true); } @BeforeEach diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java index a441757fe..11d2aef85 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerKeyTest.java @@ -23,53 +23,55 @@ class TesrLayerKeyTest { @Test void scratchProbeMatchesCopiedKey() { - final TesrBatchRenderer.LayerKey scratch = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + final TesrBatchRenderer.LayerKey scratch = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); final TesrBatchRenderer.LayerKey stored = scratch.copy(); assertNotSame(scratch, stored); assertEquals(scratch, stored); assertEquals(scratch.hashCode(), stored.hashCode()); - scratch.set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + scratch.set(TEX, TesrMaterial.Transparency.OPAQUE, true, false, false, false, 0.1f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertEquals(stored, scratch, "re-set scratch still matches stored copy"); } @Test void fieldChangesBreakEquality() { - final TesrBatchRenderer.LayerKey base = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + final TesrBatchRenderer.LayerKey base = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); final TesrBatchRenderer.LayerKey other = base.copy(); - other.set(null, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(null, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.TRANSLUCENT, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.TRANSLUCENT, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0.5f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0.5f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, true, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, true, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, TesrMaterial.SpecialRender.GLINT, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, TesrMaterial.SpecialRender.GLINT, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, SHADER, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, true, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, true, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.CULL_FRONT, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.CULL_FRONT, false, true); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, true); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, true, true); + assertNotEquals(base, other); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, false); assertNotEquals(base, other); - other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + other.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertEquals(base, other); } @Test void passSeparatesOtherwiseIdenticalKeys() { - final TesrBatchRenderer.LayerKey plain = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + final TesrBatchRenderer.LayerKey plain = new TesrBatchRenderer.LayerKey().set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); final TesrBatchRenderer.LayerKey eyes = plain.copy(); - eyes.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, EYES, 0.0f, 0.0f, DrawState.DISABLED, false); + eyes.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, EYES, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(plain, eyes); final TesrBatchRenderer.LayerKey translucent = plain.copy(); - translucent.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, TRANSLUCENT, 0.0f, 0.0f, DrawState.DISABLED, false); + translucent.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, TRANSLUCENT, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertNotEquals(plain, translucent); assertNotEquals(eyes, translucent); @@ -78,7 +80,7 @@ class TesrLayerKeyTest { // Polygon offset is the other thing a batch outlives -- the coplanar eye overlay needs it at emit time. final TesrBatchRenderer.LayerKey offset = plain.copy(); - offset.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, -1.0f, -1.0f, DrawState.DISABLED, false); + offset.set(TEX, TesrMaterial.Transparency.OPAQUE, false, false, false, false, 0f, false, NONE, null, false, NO_PASS, -1.0f, -1.0f, DrawState.DISABLED, false, true); assertNotEquals(plain, offset); assertEquals(offset, offset.copy()); assertEquals(offset.hashCode(), offset.copy().hashCode()); @@ -86,7 +88,7 @@ class TesrLayerKeyTest { @Test void nullTextureAndShaderHash() { - final TesrBatchRenderer.LayerKey key = new TesrBatchRenderer.LayerKey().set(null, null, false, false, false, false, 0f, false, null, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false); + final TesrBatchRenderer.LayerKey key = new TesrBatchRenderer.LayerKey().set(null, null, false, false, false, false, 0f, false, null, null, false, NO_PASS, 0.0f, 0.0f, DrawState.DISABLED, false, true); assertEquals(key, key.copy()); assertEquals(key.hashCode(), key.copy().hashCode()); } diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java index 1147448ca..763d48d61 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.rendering.tesr; +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.api.tesr.TesrShaders; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; @@ -7,13 +8,18 @@ import com.gtnewhorizons.angelica.glsm.GLCoreTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.StateSet; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.hooks.TextureUtilHooks; import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.iris.gl.blending.AlphaTestStorage; +import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.gl.blending.DepthColorStorage; +import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.layer.PassOverride; +import net.coderbot.iris.pipeline.WorldRenderingPhase; import net.minecraft.util.ResourceLocation; import org.joml.Matrix4f; import org.junit.jupiter.api.AfterEach; @@ -21,6 +27,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; import java.util.ArrayList; import java.util.List; @@ -28,6 +36,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; +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.assertThrows; @@ -77,7 +86,7 @@ class TesrLayerStateTest { } private static RenderLayer layer(TesrMaterial material) { - return RenderLayer.tesr(null, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true); + return RenderLayer.tesr(null, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); } @Test @@ -138,7 +147,7 @@ class TesrLayerStateTest { final AngelicaBufferSource source = new AngelicaBufferSource(); final RenderLayer liquid = layer(EntityMaterials.DROPPED_ITEM_CUTOUT); final RenderLayer glint = glint(ShaderGlint.NO_TINT); - final RenderLayer bottle = RenderLayer.tesr(null, EntityMaterials.DROPPED_ITEM_CUTOUT, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true); + final RenderLayer bottle = RenderLayer.tesr(null, EntityMaterials.DROPPED_ITEM_CUTOUT, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.CULL_BACK, true, true, true); final List drawn = new ArrayList<>(); final AngelicaBufferSource.LayerDrawHook hook = new AngelicaBufferSource.LayerDrawHook() { @Override @@ -166,8 +175,164 @@ class TesrLayerStateTest { } } + @Test + void batchDrawDoesNotInheritTheInterruptedRenderersTextureMatrixOrIrisOverride() { + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RenderLayer layer = layer(EntityMaterials.DROPPED_ITEM_CUTOUT); + final int[] draws = { 0 }; + final AngelicaBufferSource.LayerDrawHook hook = new AngelicaBufferSource.LayerDrawHook() { + @Override + public boolean hasDraws(RenderLayer candidate) { + return candidate == layer; + } + + @Override + public void drawLayer(RenderLayer drawn) { + draws[0]++; + assertTrue(MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)), "unit 0 texture matrix during batch draw"); + assertNull(GbufferPrograms.getSpecialCondition(), "special condition during batch draw"); + assertNull(GbufferPrograms.getOverridePhase(), "override phase during batch draw"); + } + }; + GLStateManager.setTextureMatrix(0, new Matrix4f().translation(0.25f, 0f, 0f)); + GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT); + GbufferPrograms.pushOverridePhase(WorldRenderingPhase.TERRAIN_CUTOUT); + try { + source.declareUse(layer); + source.endBatch(hook); + assertEquals(1, draws[0]); + assertEquals(0.25f, GLStateManager.getTextures().getTextureUnitMatrix(0).m30(), "caller texture matrix restored"); + assertEquals(SpecialCondition.GLINT, GbufferPrograms.getSpecialCondition(), "caller special condition restored"); + assertEquals(WorldRenderingPhase.TERRAIN_CUTOUT, GbufferPrograms.getOverridePhase(), "caller override phase restored"); + } finally { + GbufferPrograms.popOverridePhase(); + GbufferPrograms.teardownSpecialRenderCondition(); + GLStateManager.setTextureMatrix(0, new Matrix4f()); + source.discard(); + source.freeBuffers(); + } + } + + @Test + void clockwiseFrontFaceIsStoredWithTheLayer() { + GLStateManager.glCullFace(GL11.GL_BACK); + GLStateManager.glFrontFace(GL11.GL_CW); + try { + final int cull = DrawState.liveCull(); + assertEquals(DrawState.CULL_BACK | DrawState.FRONT_FACE_CLOCKWISE, cull); + final RenderLayer layer = RenderLayer.tesr(null, TesrMaterial.builder().build(), PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, cull, true, true); + GLStateManager.glFrontFace(GL11.GL_CCW); + final int depth = GLStateManager.pushState(StateSet.BATCH); + layer.startDrawing(); + assertEquals(GL11.GL_CW, GLStateManager.getPolygonState().getFrontFace(), "cached front face"); + assertEquals(GL11.GL_CW, GL11.glGetInteger(GL11.GL_FRONT_FACE), "driver front face"); + assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "cull stays on"); + layer.endDrawing(); + GLStateManager.popStateTo(depth); + assertEquals(GL11.GL_CCW, GLStateManager.getPolygonState().getFrontFace(), "front face restored by BATCH pop"); + } finally { + GLStateManager.glFrontFace(GL11.GL_CCW); + } + } + + @Test + void batchDrawSwapsOutAForeignProgramAndFramebuffer() { + final int program = linkTrivialProgram(); + final int framebuffer = GLStateManager.glGenFramebuffers(); + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RenderLayer layer = layer(EntityMaterials.DROPPED_ITEM_CUTOUT); + final int[] draws = { 0 }; + final AngelicaBufferSource.LayerDrawHook hook = new AngelicaBufferSource.LayerDrawHook() { + @Override + public boolean hasDraws(RenderLayer candidate) { + return candidate == layer; + } + + @Override + public void drawLayer(RenderLayer drawn) { + draws[0]++; + assertEquals(0, GLStateManager.getActiveProgram(), "program during batch draw"); + assertEquals(0, GLStateManager.getDrawFramebuffer(), "framebuffer during batch draw"); + } + }; + try { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + BatchDrawDefaults.capturePassFramebuffer(); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer); + GLStateManager.glUseProgram(program); + source.declareUse(layer); + source.endBatch(hook); + assertEquals(1, draws[0]); + assertEquals(program, GLStateManager.getActiveProgram(), "caller program restored"); + assertEquals(framebuffer, GLStateManager.getDrawFramebuffer(), "caller framebuffer restored"); + } finally { + GLStateManager.glUseProgram(0); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDeleteFramebuffers(framebuffer); + GLStateManager.glDeleteProgram(program); + source.discard(); + source.freeBuffers(); + } + } + + @Test + void batchDrawUsesTheFilterFromBeforeAnItemRenderersBlurWindow() { + final int texture = GLStateManager.glGenTextures(); + final AngelicaBufferSource source = new AngelicaBufferSource(); + final RenderLayer layer = layer(EntityMaterials.DROPPED_ITEM_CUTOUT); + final int[] draws = { 0 }; + final AngelicaBufferSource.LayerDrawHook hook = new AngelicaBufferSource.LayerDrawHook() { + @Override + public boolean hasDraws(RenderLayer candidate) { + return candidate == layer; + } + + @Override + public void drawLayer(RenderLayer drawn) { + draws[0]++; + assertEquals(GL11.GL_LINEAR, TextureInfoCache.INSTANCE.getInfo(texture).getMinFilter(), "filter from before the window"); + } + }; + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + // What TextureUtil.func_152777_a(false, false, 1) does around an item render. + TextureUtilHooks.captureBoundFilterTexture(); + 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); + source.declareUse(layer); + source.endBatch(hook); + assertEquals(1, draws[0]); + assertEquals(GL11.GL_NEAREST, TextureInfoCache.INSTANCE.getInfo(texture).getMinFilter(), "window filter restored"); + } finally { + TextureUtilHooks.clearSavedFilterTexture(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDeleteTextures(texture); + source.discard(); + source.freeBuffers(); + } + } + + private static int linkTrivialProgram() { + final int vertex = GLStateManager.glCreateShader(GL20.GL_VERTEX_SHADER); + GLStateManager.glShaderSource(vertex, "#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n"); + GLStateManager.glCompileShader(vertex); + final int fragment = GLStateManager.glCreateShader(GL20.GL_FRAGMENT_SHADER); + GLStateManager.glShaderSource(fragment, "#version 330 core\nout vec4 color;\nvoid main() { color = vec4(1.0); }\n"); + GLStateManager.glCompileShader(fragment); + final int program = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(program, vertex); + GLStateManager.glAttachShader(program, fragment); + GLStateManager.glLinkProgram(program); + GLStateManager.glDeleteShader(vertex); + GLStateManager.glDeleteShader(fragment); + return program; + } + private static RenderLayer glint(int slot) { - return RenderLayer.tesr(null, EntityMaterials.GLINT, PassOverride.NONE, 0f, 0f, slot, DrawState.CULL_BACK, true); + return RenderLayer.tesr(null, EntityMaterials.GLINT, PassOverride.NONE, 0f, 0f, slot, DrawState.CULL_BACK, true, true); } @Test @@ -195,14 +360,14 @@ class TesrLayerStateTest { 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 }, - null, material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, liveCull(material), DrawState.liveLit(material)); + 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, liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap()); } private static RenderLayer queuedLayer(TesrMaterial material) { return Reflect.invoke(TesrBatchRenderer.INSTANCE, "layerFor", - new Class[] { ResourceLocation.class, TesrMaterial.class, PassOverride.class, float.class, float.class, int.class, boolean.class }, - null, material, PassOverride.NONE, 0f, 0f, liveCull(material), DrawState.liveLit(material)); + new Class[] { ResourceLocation.class, TesrMaterial.class, PassOverride.class, float.class, float.class, int.class, boolean.class, boolean.class }, + null, material, PassOverride.NONE, 0f, 0f, liveCull(material), DrawState.liveLit(material), DrawState.liveLightmap()); } private static void drawInBatch(RenderLayer layer, boolean culled) { diff --git a/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java b/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java index 3e27d66a2..7828cf876 100644 --- a/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java +++ b/src/test/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilderTest.java @@ -69,7 +69,7 @@ class SegmentedBufferBuilderTest { static RenderLayer layer(String name, TransparencyType transparencyType) { final TesrMaterial material = transparencyType == TransparencyType.OPAQUE ? OPAQUE_MATERIAL : TRANSLUCENT_MATERIAL; - return RenderLayer.tesr(new ResourceLocation("angelicatest", name), material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false); + return RenderLayer.tesr(new ResourceLocation("angelicatest", name), material, PassOverride.NONE, 0f, 0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, true); } static ModelQuad quad() {