diff --git a/glsm/build.gradle.kts b/glsm/build.gradle.kts index d732afb70..4373c5227 100644 --- a/glsm/build.gradle.kts +++ b/glsm/build.gradle.kts @@ -103,6 +103,11 @@ repositories { mavenLocal() } +val spirvTestRuntime by configurations.creating { + isCanBeConsumed = false + isCanBeResolved = true +} + dependencies { // MC compile stubs compileOnly(sourceSets["stubs"].output) @@ -133,6 +138,7 @@ dependencies { testRuntimeOnly(libs.lwjgl3.spvc) { artifact { classifier = lwjglNatives } } testRuntimeOnly(libs.lwjgl3) testRuntimeOnly(libs.lwjgl3) { artifact { classifier = lwjglNatives } } + spirvTestRuntime(libs.lwjgl3.opengl) // @Lwjgl3Aware annotation compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false } compileOnly(libs.retrofuturabootstrap) { isTransitive = false } @@ -309,7 +315,7 @@ val spirvTest by tasks.registering(Test::class) { classpath = sourceSets["test"].runtimeClasspath.filter { file -> // Strip the LWJGL2 jars - they collide with LWJGL3's sealed org.lwjgl package. !file.name.startsWith("lwjgl-2.") && !file.name.startsWith("lwjgl_util-") && !file.name.startsWith("lwjgl-platform-") - } + }.plus(spirvTestRuntime) filter { includeTestsMatching("com.gtnewhorizons.angelica.glsm.shader.SpirvShaderTranslator*Test") diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java index 69fa3f262..b8b5bd942 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/config/SystemProperties.java @@ -54,6 +54,7 @@ public final class SystemProperties { public static final boolean FLYBY_EXIT_WHEN_DONE = Boolean.getBoolean("angelica.flyby.exitWhenDone"); public static final long FLYBY_TIME_OF_DAY = Math.floorMod(Long.getLong("angelica.flyby.timeOfDay", 6000L), 24000L); public static final String FLYBY_COMMANDS = System.getProperty("angelica.flyby.commands", ""); + public static final String FLYBY_ORIGIN = System.getProperty("angelica.flyby.origin", ""); public static final FlybyPacing FLYBY_PACING = parseEnum("angelica.flyby.pacing", FlybyPacing.UNCAPPED, FlybyPacing.UNCAPPED, FlybyPacing.class); // Debug 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 9d0523594..b452ee5b7 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -13,6 +13,7 @@ import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; import com.gtnewhorizons.angelica.glsm.backend.RenderBackend; import com.gtnewhorizons.angelica.glsm.backend.VSyncMode; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; @@ -427,11 +428,7 @@ public class GLStateManager { public static boolean wideLineEmulationActive = false; public static boolean lineStippleActive = false; - public static boolean instancedFfpDrawActive = false; - - - - + public static Instancing ffpInstancing = Instancing.NONE; private static final MethodHandle MAT4_STACK_CURR_DEPTH; @@ -1429,8 +1426,11 @@ public class GLStateManager { } public static void endForeignDraw() { - if (foreignDrawDepth > 0 && --foreignDrawDepth == 0 && GLSMHooks.FOREIGN_DRAW_END.hasListeners()) { - GLSMHooks.FOREIGN_DRAW_END.post(GLSMHooks.foreignDrawEndEvent); + if (foreignDrawDepth > 0 && --foreignDrawDepth == 0) { + GLSMHooks.resolvePendingProgram(); + if (GLSMHooks.FOREIGN_DRAW_END.hasListeners()) { + GLSMHooks.FOREIGN_DRAW_END.post(GLSMHooks.foreignDrawEndEvent); + } } } @@ -4062,6 +4062,14 @@ public class GLStateManager { } } + public static void setTextureMatrix(int unit, Matrix4fc m) { + if (isCachingEnabled()) { + final GLContextState glCtx = ctx(); + glCtx.textures.getTextureUnitMatrix(unit).set(m); + glCtx.texMatrixGeneration++; + } + } + public static void setProjectionMatrix(Matrix4fc m) { final GLContextState glCtx = ctx(); if (isCachingEnabled()) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeInstancedAttribs.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeInstancedAttribs.java new file mode 100644 index 000000000..65b24c02f --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeInstancedAttribs.java @@ -0,0 +1,27 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; + +public final class CubeInstancedAttribs { + + public static final int LOC_LIGHTMAP_SCALE = InstancedAttribs.LOC_LIGHTMAP; + public static final int LOC_CUBE_TEX = 15; + + public static final int OFFSET_LIGHTMAP_SCALE = InstancedAttribs.HEAD_SIZE; + public static final int OFFSET_CUBE_TEX = OFFSET_LIGHTMAP_SCALE + 16; + public static final int STRIDE = OFFSET_CUBE_TEX + 16; + + public static void pointInstanceAttribs(long base) { + InstancedAttribs.pointHead(base, STRIDE); + GLStateManager.glVertexAttribPointer(LOC_LIGHTMAP_SCALE, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_LIGHTMAP_SCALE); + GLStateManager.glVertexAttribPointer(LOC_CUBE_TEX, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_CUBE_TEX); + } + + static void enableInstanceArrays() { + InstancedAttribs.enableHeadArrays(); + InstancedAttribs.enableInstanced(LOC_CUBE_TEX); + } + + private CubeInstancedAttribs() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParams.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParams.java new file mode 100644 index 000000000..09c9763d1 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParams.java @@ -0,0 +1,54 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; + +public record CubeParams(float minX, float minY, float minZ, float spanX, float spanY, float spanZ, float u0, float v0, float uScaleX, float vScaleY, float uScaleZ, float vScaleZ) { + + private static final float MIN_SPAN = 1.0e-4f; + + public CubeParams { + if (!(spanX > MIN_SPAN && spanY > MIN_SPAN && spanZ > MIN_SPAN)) throw new IllegalArgumentException("degenerate cube span"); + } + + public static CubeParams of(float texWidth, float texHeight, boolean mirror, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate) { + if (texWidth <= 0.0f || texHeight <= 0.0f) return null; + if (sizeX < 0 || sizeY < 0 || sizeZ < 0) return null; + if (mirror && sizeX == 0) return null; + final float minX = x - inflate; + final float minY = y - inflate; + final float minZ = z - inflate; + final float spanX = ((x + sizeX) + inflate) - minX; + final float spanY = ((y + sizeY) + inflate) - minY; + final float spanZ = ((z + sizeZ) + inflate) - minZ; + if (spanX <= MIN_SPAN || spanY <= MIN_SPAN || spanZ <= MIN_SPAN) return null; + return new CubeParams(minX, minY, minZ, spanX, spanY, spanZ, texU / texWidth, texV / texHeight, (mirror ? -sizeX : sizeX) / texWidth, sizeY / texHeight, sizeZ / texWidth, sizeZ / texHeight); + } + + public void writeRows(long ptr, float[] mv, int off, float scale) { + final float tx = minX * scale; + final float ty = minY * scale; + final float tz = minZ * scale; + final float sx = spanX * scale; + final float sy = spanY * scale; + final float sz = spanZ * scale; + for (int r = 0; r < 3; r++) { + final float c0 = mv[off + r]; + final float c1 = mv[off + 4 + r]; + final float c2 = mv[off + 8 + r]; + final long row = ptr + InstancedAttribs.OFFSET_ROWS + r * 16L; + memPutFloat(row, c0 * sx); + memPutFloat(row + 4, c1 * sy); + memPutFloat(row + 8, c2 * sz); + memPutFloat(row + 12, mv[off + 12 + r] + c0 * tx + c1 * ty + c2 * tz); + } + } + + public void writeTexture(long ptr) { + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE + 8, uScaleZ); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE + 12, vScaleZ); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_CUBE_TEX, u0); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_CUBE_TEX + 4, v0); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_CUBE_TEX + 8, uScaleX); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_CUBE_TEX + 12, vScaleY); + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java index bb33eb648..b8416e047 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java @@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL13; * Packed-long fragment shader permutation key for FFP emulation. * * Layout: - * long[0]: global bits (13) + unit 0 (47 bits at offset 13) + * long[0]: global bits (14) + unit 0 (47 bits at offset 14) * long[1..3]: unit 1..3 (47 bits each, low-aligned) * Only max(1, nrEnabledUnits) longs are significant. * @@ -63,7 +63,7 @@ public final class FragmentKey { public static final int FOG_EXP = 2; public static final int FOG_EXP2 = 3; - private static final int GLOBAL_BITS = 13; + private static final int GLOBAL_BITS = 14; private static final int BIT_FOG_MODE = 0; // 2 bits private static final int BIT_ALPHA_TEST = 2; // 1 bit private static final int BIT_ALPHA_FUNC = 3; // 3 bits @@ -72,6 +72,7 @@ public final class FragmentKey { private static final int BIT_OVERLAY_ENABLED = 10; // 1 bit private static final int BIT_LINE_STIPPLE = 11; // 1 bit private static final int BIT_COLOR_SUM = 12; // 1 bit + private static final int BIT_OVERLAY_INSTANCED = 13; private static final int U_ENABLED = 0; private static final int U_MODE = 1; // 3 bits @@ -123,7 +124,9 @@ public final class FragmentKey { } // Damage overlay - if (GLStateManager.getOverlayA() != 0.0f) { + if (GLStateManager.ffpInstancing.hasInstanceHead()) { + global |= (1L << BIT_OVERLAY_INSTANCED); + } else if (GLStateManager.getOverlayA() != 0.0f) { global |= (1L << BIT_OVERLAY_ENABLED); } @@ -245,6 +248,7 @@ public final class FragmentKey { public boolean lineStipple() { return ((packed[0] >> BIT_LINE_STIPPLE) & 1) != 0; } public int nrEnabledUnits() { return (int) ((packed[0] >> BIT_NR_ENABLED_UNITS) & 0x7); } public boolean overlayEnabled() { return ((packed[0] >> BIT_OVERLAY_ENABLED) & 1) != 0; } + public boolean overlayInstanced() { return ((packed[0] >> BIT_OVERLAY_INSTANCED) & 1) != 0; } private long unitBits(int i) { return (i == 0) ? (packed[0] >>> GLOBAL_BITS) : packed[i]; @@ -378,10 +382,7 @@ public final class FragmentKey { default -> "?"; }; final StringBuilder sb = new StringBuilder(); - sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b colorSum=%b overlay=%b units=%d", - fogName, alphaTestEnabled(), - alphaTestEnabled() ? String.format("0x%04X", decodeAlphaFunc(alphaTestFunc())) : "-", - separateSpecular(), colorSum(), overlayEnabled(), nrEnabledUnits())); + sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b colorSum=%b overlay=%b units=%d", fogName, alphaTestEnabled(), alphaTestEnabled() ? String.format("0x%04X", decodeAlphaFunc(alphaTestFunc())) : "-", separateSpecular(), colorSum(), overlayEnabled() || overlayInstanced(), nrEnabledUnits())); for (int i = 0; i < nrEnabledUnits(); i++) { if (!unitEnabled(i)) { sb.append(String.format(" u%d=OFF", i)); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java index 404681cb7..bbe95c705 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java @@ -35,6 +35,9 @@ public final class FragmentShaderGenerator { private static void emitInputs(StringBuilder sb, FragmentKey key) { sb.append("// Inputs from vertex shader\n"); sb.append("in vec4 v_Color;\n"); + if (key.overlayInstanced()) { + sb.append("in vec4 v_Overlay;\n"); + } if (key.separateSpecular()) { sb.append("in vec3 v_SpecularColor;\n"); } @@ -116,8 +119,11 @@ public final class FragmentShaderGenerator { * Emit the modern-style damage overlay mix. */ private static void emitOverlay(StringBuilder sb, FragmentKey key) { - if (!key.overlayEnabled()) return; - sb.append(" color.rgb = mix(color.rgb, u_OverlayColor.rgb, u_OverlayColor.a);\n"); + if (key.overlayInstanced()) { + sb.append(" color.rgb = mix(color.rgb, v_Overlay.rgb, v_Overlay.a);\n"); + } else if (key.overlayEnabled()) { + sb.append(" color.rgb = mix(color.rgb, u_OverlayColor.rgb, u_OverlayColor.a);\n"); + } } private static void emitSimpleUnit(StringBuilder sb, FragmentKey key, int unit, String texVar, String envColorVar, String prevVar, String assign) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java index 8fa664372..5242f009a 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedAttribs.java @@ -1,18 +1,84 @@ package com.gtnewhorizons.angelica.glsm.ffp; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutLong; + public final class InstancedAttribs { - public static final int LOC_MATRIX_COL0 = 5; - public static final int LOC_MATRIX_COL1 = 6; - public static final int LOC_MATRIX_COL2 = 7; - public static final int LOC_MATRIX_COL3 = 8; - public static final int LOC_COLOR = 9; + public static final int LOC_ROW0 = 5; + public static final int LOC_ROW1 = 6; + public static final int LOC_ROW2 = 7; + public static final int LOC_COLOR = 8; + public static final int LOC_OVERLAY = 9; public static final int LOC_LIGHTMAP = 10; + public static final int LOC_ENTITY = 11; - public static final int OFFSET_MATRIX = 0; - public static final int OFFSET_COLOR = 64; - public static final int OFFSET_LIGHTMAP = 68; - public static final int STRIDE = 80; + public static final int OFFSET_ROWS = 0; + public static final int OFFSET_COLOR = 48; + public static final int OFFSET_OVERLAY = 52; + public static final int OFFSET_ENTITY = 56; + public static final int HEAD_SIZE = 64; + public static final int OFFSET_LIGHTMAP = HEAD_SIZE; + public static final int STRIDE = 72; + + public static void writeHead(long ptr, float[] colMajor, int off, int colorABGR, int overlayABGR, long entityInfo) { + writeRows(ptr, colMajor, off); + writeTail(ptr, colorABGR, overlayABGR, entityInfo); + } + + private static void writeRows(long ptr, float[] colMajor, int off) { + for (int r = 0; r < 3; r++) { + final long row = ptr + OFFSET_ROWS + r * 16L; + memPutFloat(row, colMajor[off + r]); + memPutFloat(row + 4, colMajor[off + 4 + r]); + memPutFloat(row + 8, colMajor[off + 8 + r]); + memPutFloat(row + 12, colMajor[off + 12 + r]); + } + } + + public static void writeTail(long ptr, int colorABGR, int overlayABGR, long entityInfo) { + memPutInt(ptr + OFFSET_COLOR, colorABGR); + memPutInt(ptr + OFFSET_OVERLAY, overlayABGR); + memPutLong(ptr + OFFSET_ENTITY, entityInfo); + } + + public static void writeLightmap(long ptr, int packedLight) { + memPutFloat(ptr, packedLight & 0xFFFF); + memPutFloat(ptr + 4, (packedLight >>> 16) & 0xFFFF); + } + + public static long packEntityInfo(int entity, int blockEntity, int item) { + return (entity & 0xFFFFL) | ((blockEntity & 0xFFFFL) << 16) | ((item & 0xFFFFL) << 32); + } + + public static void pointHead(long base, int stride) { + for (int r = 0; r < 3; r++) { + GLStateManager.glVertexAttribPointer(LOC_ROW0 + r, 4, GL11.GL_FLOAT, false, stride, base + OFFSET_ROWS + r * 16L); + } + GLStateManager.glVertexAttribPointer(LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, stride, base + OFFSET_COLOR); + GLStateManager.glVertexAttribPointer(LOC_OVERLAY, 4, GL11.GL_UNSIGNED_BYTE, true, stride, base + OFFSET_OVERLAY); + GLStateManager.glVertexAttribIPointer(LOC_ENTITY, 4, GL11.GL_SHORT, stride, base + OFFSET_ENTITY); + } + + public static void pointTemplate(long base) { + pointHead(base, STRIDE); + GLStateManager.glVertexAttribPointer(LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_LIGHTMAP); + } + + public static void enableHeadArrays() { + for (int loc = LOC_ROW0; loc <= LOC_ENTITY; loc++) { + enableInstanced(loc); + } + } + + static void enableInstanced(int loc) { + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribDivisor(loc, 1); + } private InstancedAttribs() {} } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java new file mode 100644 index 000000000..5e6ecf04c --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedGlslHelpers.java @@ -0,0 +1,84 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; + +import java.util.ArrayList; + +public final class InstancedGlslHelpers { + + private InstancedGlslHelpers() {} + + public static String mat4FromRows(String row0, String row1, String row2) { + return "mat4(" + + "vec4(" + row0 + ".x, " + row1 + ".x, " + row2 + ".x, 0.0), " + + "vec4(" + row0 + ".y, " + row1 + ".y, " + row2 + ".y, 0.0), " + + "vec4(" + row0 + ".z, " + row1 + ".z, " + row2 + ".z, 0.0), " + + "vec4(" + row0 + ".w, " + row1 + ".w, " + row2 + ".w, 1.0))"; + } + + public static String mat3FromRows(String row0, String row1, String row2) { + return "mat3(" + + "normalize(vec3(" + row0 + ".x, " + row1 + ".x, " + row2 + ".x)), " + + "normalize(vec3(" + row0 + ".y, " + row1 + ".y, " + row2 + ".y)), " + + "normalize(vec3(" + row0 + ".z, " + row1 + ".z, " + row2 + ".z)))"; + } + + public static String particlePos(String centerHalf, String offset) { + return "vec4(" + centerHalf + ".xyz + " + offset + " * " + centerHalf + ".w, 1.0)"; + } + + public static String particleUv(String uv, String corner) { + return "vec4(" + + "mix(" + uv + ".x, " + uv + ".z, " + corner + ".x), " + + "mix(" + uv + ".y, " + uv + ".w, " + corner + ".y), " + + "0.0, 1.0)"; + } + + public static String cubePrelude(String prefix, String mid, String delta, String normal, String tex, String sep) { + return "float " + prefix + "cubeMirror = " + tex + ".z < 0.0 ? 1.0 : 0.0;" + sep + + "vec2 " + prefix + "cubeMidU = " + mid + ".xy - " + prefix + "cubeMirror * " + normal + ".x;" + sep + + "vec2 " + prefix + "cubeU = " + prefix + "cubeMidU + (1.0 - 2.0 * " + prefix + "cubeMirror) * " + delta + ".xy;" + sep + + "vec2 " + prefix + "cubeV = " + mid + ".zw + " + delta + ".zw;"; + } + + public static String cubeUv(String tex, String lightScale, String uA, String uZ, String vA, String vZ) { + return "vec4(" + + tex + ".x + " + uA + " * abs(" + tex + ".z) + " + uZ + " * " + lightScale + ".z, " + + tex + ".y + " + vA + " * " + tex + ".w + " + vZ + " * " + lightScale + ".w, " + + "0.0, 1.0)"; + } + + public static String[] attributeDecls(String prefix, Instancing kind) { + final ArrayList decls = new ArrayList<>(9); + switch (kind) { + case NONE -> {} + case TEMPLATE -> addHead(decls, prefix, "vec2", "InstLightmap"); + case CUBE -> { + decls.add(decl(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(), "vec4", prefix + "CubeMid")); + decls.add(decl(VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation(), "vec4", prefix + "CubeDelta")); + addHead(decls, prefix, "vec4", "InstLightmapScale"); + decls.add(decl(CubeInstancedAttribs.LOC_CUBE_TEX, "vec4", prefix + "CubeTex")); + } + case PARTICLE -> { + decls.add(decl(ParticleInstancedAttribs.LOC_CENTER_HALF, "vec4", prefix + "InstCenterHalf")); + decls.add(decl(ParticleInstancedAttribs.LOC_UV, "vec4", prefix + "InstUv")); + decls.add(decl(ParticleInstancedAttribs.LOC_COLOR, "vec4", prefix + "InstColor")); + decls.add(decl(ParticleInstancedAttribs.LOC_LIGHTMAP, "vec2", prefix + "InstLightmap")); + } + } + return decls.toArray(String[]::new); + } + + private static void addHead(ArrayList decls, String prefix, String lightmapType, String lightmapName) { + decls.add(decl(InstancedAttribs.LOC_ROW0, "vec4", prefix + "InstRow0")); + decls.add(decl(InstancedAttribs.LOC_ROW1, "vec4", prefix + "InstRow1")); + decls.add(decl(InstancedAttribs.LOC_ROW2, "vec4", prefix + "InstRow2")); + decls.add(decl(InstancedAttribs.LOC_COLOR, "vec4", prefix + "InstColor")); + decls.add(decl(InstancedAttribs.LOC_OVERLAY, "vec4", prefix + "InstOverlay")); + decls.add(decl(InstancedAttribs.LOC_LIGHTMAP, lightmapType, prefix + lightmapName)); + } + + private static String decl(int loc, String type, String name) { + return "layout(location = " + loc + ") in " + type + " " + name + ";"; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java new file mode 100644 index 000000000..58b0e4431 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Instancing.java @@ -0,0 +1,20 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +public enum Instancing { + NONE(""), + TEMPLATE("_instanced"), + CUBE("_cubeinstanced"), + PARTICLE("_particleinstanced"); + + public static final Instancing[] VALUES = values(); + + public final String variantSuffix; + + Instancing(String variantSuffix) { + this.variantSuffix = variantSuffix; + } + + public boolean hasInstanceHead() { + return this == TEMPLATE || this == CUBE; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleInstancedAttribs.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleInstancedAttribs.java new file mode 100644 index 000000000..f3bf10ef1 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleInstancedAttribs.java @@ -0,0 +1,50 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; + +public final class ParticleInstancedAttribs { + + public static final int LOC_CENTER_HALF = 5; + public static final int LOC_UV = 6; + public static final int LOC_COLOR = InstancedAttribs.LOC_COLOR; + public static final int LOC_LIGHTMAP = InstancedAttribs.LOC_LIGHTMAP; + + public static final int OFFSET_CENTER_HALF = 0; + public static final int OFFSET_UV = 16; + public static final int OFFSET_COLOR = 32; + public static final int OFFSET_LIGHTMAP = 36; + public static final int STRIDE = 48; + + public static void pointInstanceAttribs(long base) { + GLStateManager.glVertexAttribPointer(LOC_CENTER_HALF, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_CENTER_HALF); + GLStateManager.glVertexAttribPointer(LOC_UV, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_UV); + GLStateManager.glVertexAttribPointer(LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, STRIDE, base + OFFSET_COLOR); + GLStateManager.glVertexAttribPointer(LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_LIGHTMAP); + } + + static void enableInstanceArrays() { + InstancedAttribs.enableInstanced(LOC_CENTER_HALF); + InstancedAttribs.enableInstanced(LOC_UV); + InstancedAttribs.enableInstanced(LOC_COLOR); + InstancedAttribs.enableInstanced(LOC_LIGHTMAP); + } + + public static void writeInstance(long ptr, float cx, float cy, float cz, float half, float u0, float v0, float u1, float v1, int colorABGR, int packedLight) { + memPutFloat(ptr + OFFSET_CENTER_HALF, cx); + memPutFloat(ptr + OFFSET_CENTER_HALF + 4, cy); + memPutFloat(ptr + OFFSET_CENTER_HALF + 8, cz); + memPutFloat(ptr + OFFSET_CENTER_HALF + 12, half); + memPutFloat(ptr + OFFSET_UV, u0); + memPutFloat(ptr + OFFSET_UV + 4, v0); + memPutFloat(ptr + OFFSET_UV + 8, u1); + memPutFloat(ptr + OFFSET_UV + 12, v1); + memPutInt(ptr + OFFSET_COLOR, colorABGR); + InstancedAttribs.writeLightmap(ptr + OFFSET_LIGHTMAP, packedLight); + } + + private ParticleInstancedAttribs() {} +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleQuadMesh.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleQuadMesh.java new file mode 100644 index 000000000..e06d373b9 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleQuadMesh.java @@ -0,0 +1,160 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; + +public final class ParticleQuadMesh { + + public static final int VERTEX_FLAGS = VertexFlags.TEXTURE_BIT; + + public static final int VERTEX_COUNT = 4; + private static final int VERTEX_STRIDE = 24; + + private static final int OFFSET_OFFSET = 0; + private static final int OFFSET_CORNER = 12; + private static final int OFFSET_TANGENT = 20; + + private static final float[] CORNER_A = { -1.0f, -1.0f, 1.0f, 1.0f }; + private static final float[] CORNER_B = { -1.0f, 1.0f, 1.0f, -1.0f }; + + private static int vao; + private static int vbo; + private static ByteBuffer staging; + private static boolean written; + private static float lastRotX, lastRotXZ, lastRotZ, lastRotYZ, lastRotXY; + + private ParticleQuadMesh() {} + + public static float cornerA(int corner) { + return CORNER_A[corner]; + } + + public static float cornerB(int corner) { + return CORNER_B[corner]; + } + + public static float offsetX(float a, float b, float rotX, float rotYZ) { + return a * rotX + b * rotYZ; + } + + public static float offsetY(float b, float rotXZ) { + return b * rotXZ; + } + + public static float offsetZ(float a, float b, float rotZ, float rotXY) { + return a * rotZ + b * rotXY; + } + + public static int vao() { + if (vao == 0) build(); + return vao; + } + + public static void update(float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY) { + if (vao == 0) build(); + if (written && rotX == lastRotX && rotXZ == lastRotXZ && rotZ == lastRotZ && rotYZ == lastRotYZ && rotXY == lastRotXY) { + return; + } + lastRotX = rotX; + lastRotXZ = rotXZ; + lastRotZ = rotZ; + lastRotYZ = rotYZ; + lastRotXY = rotXY; + written = true; + + write(memAddress0(staging), rotX, rotXZ, rotZ, rotYZ, rotXY); + final int savedVBO = GLStateManager.getBoundVBO(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + staging.position(0).limit(VERTEX_COUNT * VERTEX_STRIDE); + GLStateManager.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0L, staging); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, savedVBO); + } + + private static void write(long dst, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY) { + final int tangent = packTangent(rotX, 0.0f, rotZ); + long ptr = dst; + for (int i = 0; i < VERTEX_COUNT; i++) { + final float a = cornerA(i); + final float b = cornerB(i); + memPutFloat(ptr + OFFSET_OFFSET, offsetX(a, b, rotX, rotYZ)); + memPutFloat(ptr + OFFSET_OFFSET + 4, offsetY(b, rotXZ)); + memPutFloat(ptr + OFFSET_OFFSET + 8, offsetZ(a, b, rotZ, rotXY)); + memPutFloat(ptr + OFFSET_CORNER, (a + 1.0f) * 0.5f); + memPutFloat(ptr + OFFSET_CORNER + 4, (b + 1.0f) * 0.5f); + memPutInt(ptr + OFFSET_TANGENT, tangent); + ptr += VERTEX_STRIDE; + } + } + + private static int packTangent(float x, float y, float z) { + final float lenSq = x * x + y * y + z * z; + final float nx, ny, nz; + if (lenSq < 1.0e-12f) { + nx = 1.0f; + ny = 0.0f; + nz = 0.0f; + } else { + final float inv = (float) (1.0 / Math.sqrt(lenSq)); + nx = x * inv; + ny = y * inv; + nz = z * inv; + } + return NormI8.pack(nx, ny, nz) | (127 << 24); + } + + private static void build() { + final int savedVAO = GLStateManager.getBoundVAO(); + final int savedVBO = GLStateManager.getBoundVBO(); + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, (long) VERTEX_COUNT * VERTEX_STRIDE, GL15.GL_DYNAMIC_DRAW); + + attrib(VertexFormatElement.Usage.POSITION.getAttributeLocation(), 3, GL11.GL_FLOAT, false, OFFSET_OFFSET); + attrib(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(), 2, GL11.GL_FLOAT, false, OFFSET_CORNER); + attrib(ImmediateExtendedAttribHandler.LOC_TANGENT, 4, GL11.GL_BYTE, true, OFFSET_TANGENT); + + ParticleInstancedAttribs.enableInstanceArrays(); + + GLStateManager.glBindVertexArray(savedVAO); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, savedVBO); + + if (staging == null) staging = memAlloc(VERTEX_COUNT * VERTEX_STRIDE); + written = false; + } + + private static void attrib(int loc, int size, int type, boolean normalized, int offset) { + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribPointer(loc, size, type, normalized, VERTEX_STRIDE, offset); + } + + public static void delete() { + if (vbo != 0) { + GLStateManager.glDeleteBuffers(vbo); + vbo = 0; + } + if (vao != 0) { + GLStateManager.glDeleteVertexArrays(vao); + vao = 0; + } + if (staging != null) { + memFree(staging); + staging = null; + } + written = false; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java index 3693f60d9..73d915c84 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java @@ -97,6 +97,8 @@ public final class ShaderManager { final long vkPacked = VertexKey.packFromState(true, true, true, true, fragMask); final VertexKey vk = VertexKey.fromPacked(vkPacked); VertexShaderGenerator.generate(vk); + VertexShaderGenerator.generate(VertexKey.fromPacked(VertexKey.withInstancing(vkPacked, Instancing.CUBE))); + VertexShaderGenerator.generate(VertexKey.fromPacked(VertexKey.withInstancing(vkPacked, Instancing.PARTICLE))); FragmentShaderGenerator.generate(FragmentKey.fromPacked(fkScratch, fkLen)); GeometryShaderGenerator.generate(vk); final Class[] touched = { Program.class, ShaderCache.class, TessellatorStreamingDrawer.class, QuadConverter.class }; @@ -127,6 +129,7 @@ public final class ShaderManager { } public void preDraw() { + GLSMHooks.resolvePendingProgram(); final DeferredBlendHandler bh = GLSMHooks.blendHandler; if (bh != null) bh.flushDeferredBlend(); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/UnitCubeMesh.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/UnitCubeMesh.java new file mode 100644 index 000000000..3b490fd34 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/UnitCubeMesh.java @@ -0,0 +1,161 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; + +public final class UnitCubeMesh { + + public static final int VERTEX_FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT; + + public static final int FACE_COUNT = 6; + public static final int VERTEX_COUNT = 24; + public static final int VERTEX_STRIDE = 64; + + public static final int OFFSET_POSITION = 0; + private static final int OFFSET_COLOR = 12; + public static final int OFFSET_MID = 16; + public static final int OFFSET_DELTA = 32; + public static final int OFFSET_NORMAL = 48; + public static final int OFFSET_TANGENT = 60; + + public static final float[][] CORNERS = { + { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, + { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 }, + }; + + public record Span(int a, int z) { + public int texels(int sizeA, int sizeZ) { + return a * sizeA + z * sizeZ; + } + } + + public record Net(Span uLow, Span uHigh, Span vLow, Span vHigh) { + public Span u(int vertex) { + return vertex == 0 || vertex == 3 ? uHigh : uLow; + } + + public Span v(int vertex) { + return vertex >= 2 ? vHigh : vLow; + } + } + + public record Face(int[] corners, float[] normal, float[] tangent, Net net) {} + + public static final Face[] FACES = { + new Face(new int[] { 5, 1, 2, 6 }, new float[] { 1, 0, 0 }, new float[] { 0, 0, 1, 1 }, new Net(new Span(1, 1), new Span(1, 2), new Span(0, 1), new Span(1, 1))), + new Face(new int[] { 0, 4, 7, 3 }, new float[] { -1, 0, 0 }, new float[] { 0, 0, -1, 1 }, new Net(new Span(0, 0), new Span(0, 1), new Span(0, 1), new Span(1, 1))), + new Face(new int[] { 5, 4, 0, 1 }, new float[] { 0, -1, 0 }, new float[] { 1, 0, 0, 1 }, new Net(new Span(0, 1), new Span(1, 1), new Span(0, 0), new Span(0, 1))), + new Face(new int[] { 2, 3, 7, 6 }, new float[] { 0, 1, 0 }, new float[] { 1, 0, 0, -1 }, new Net(new Span(1, 1), new Span(2, 1), new Span(0, 1), new Span(0, 0))), + new Face(new int[] { 1, 0, 3, 2 }, new float[] { 0, 0, -1 }, new float[] { 1, 0, 0, 1 }, new Net(new Span(0, 1), new Span(1, 1), new Span(0, 1), new Span(1, 1))), + new Face(new int[] { 4, 5, 6, 7 }, new float[] { 0, 0, 1 }, new float[] { -1, 0, 0, 1 }, new Net(new Span(1, 2), new Span(2, 2), new Span(0, 1), new Span(1, 1))), + }; + + private static int vao; + private static int vbo; + + private UnitCubeMesh() {} + + public static void write(long dst) { + long ptr = dst; + for (int f = 0; f < FACE_COUNT; f++) { + final Face face = FACES[f]; + final Net net = face.net(); + final float midUA = (net.uLow().a() + net.uHigh().a()) * 0.5f; + final float midUZ = (net.uLow().z() + net.uHigh().z()) * 0.5f; + final float midVA = (net.vLow().a() + net.vHigh().a()) * 0.5f; + final float midVZ = (net.vLow().z() + net.vHigh().z()) * 0.5f; + for (int c = 0; c < 4; c++) { + final float[] corner = CORNERS[face.corners()[c]]; + final Span u = net.u(c); + final Span v = net.v(c); + memPutFloat(ptr + OFFSET_POSITION, corner[0]); + memPutFloat(ptr + OFFSET_POSITION + 4, corner[1]); + memPutFloat(ptr + OFFSET_POSITION + 8, corner[2]); + memPutInt(ptr + OFFSET_COLOR, 0xFFFFFFFF); + memPutFloat(ptr + OFFSET_MID, midUA); + memPutFloat(ptr + OFFSET_MID + 4, midUZ); + memPutFloat(ptr + OFFSET_MID + 8, midVA); + memPutFloat(ptr + OFFSET_MID + 12, midVZ); + memPutFloat(ptr + OFFSET_DELTA, u.a() - midUA); + memPutFloat(ptr + OFFSET_DELTA + 4, u.z() - midUZ); + memPutFloat(ptr + OFFSET_DELTA + 8, v.a() - midVA); + memPutFloat(ptr + OFFSET_DELTA + 12, v.z() - midVZ); + memPutFloat(ptr + OFFSET_NORMAL, face.normal()[0]); + memPutFloat(ptr + OFFSET_NORMAL + 4, face.normal()[1]); + memPutFloat(ptr + OFFSET_NORMAL + 8, face.normal()[2]); + final float[] tangent = face.tangent(); + memPutInt(ptr + OFFSET_TANGENT, packTangent(tangent[0], tangent[1], tangent[2], tangent[3])); + ptr += VERTEX_STRIDE; + } + } + } + + private static int packTangent(float x, float y, float z, float w) { + return NormI8.pack(x, y, z) | (((int) (w * 127.0f) & 0xFF) << 24); + } + + public static int vao() { + if (vao == 0) build(); + return vao; + } + + private static void build() { + final int savedVAO = GLStateManager.getBoundVAO(); + final int savedVBO = GLStateManager.getBoundVBO(); + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + + final int bytes = VERTEX_COUNT * VERTEX_STRIDE; + final ByteBuffer data = memAlloc(bytes); + try { + write(memAddress0(data)); + data.position(0).limit(bytes); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW); + } finally { + memFree(data); + } + + attrib(VertexFormatElement.Usage.POSITION.getAttributeLocation(), 3, GL11.GL_FLOAT, false, OFFSET_POSITION); + attrib(VertexFormatElement.Usage.COLOR.getAttributeLocation(), 4, GL11.GL_UNSIGNED_BYTE, true, OFFSET_COLOR); + attrib(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(), 4, GL11.GL_FLOAT, false, OFFSET_MID); + attrib(VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation(), 4, GL11.GL_FLOAT, false, OFFSET_DELTA); + attrib(VertexFormatElement.Usage.NORMAL.getAttributeLocation(), 3, GL11.GL_FLOAT, false, OFFSET_NORMAL); + attrib(ImmediateExtendedAttribHandler.LOC_TANGENT, 4, GL11.GL_BYTE, true, OFFSET_TANGENT); + + CubeInstancedAttribs.enableInstanceArrays(); + + GLStateManager.glBindVertexArray(savedVAO); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, savedVBO); + } + + private static void attrib(int loc, int size, int type, boolean normalized, int offset) { + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribPointer(loc, size, type, normalized, VERTEX_STRIDE, offset); + } + + public static void delete() { + if (vbo != 0) { + GLStateManager.glDeleteBuffers(vbo); + vbo = 0; + } + if (vao != 0) { + GLStateManager.glDeleteVertexArrays(vao); + vao = 0; + } + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java index a143bd287..d8acd2ec0 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -49,7 +49,7 @@ public final class VertexKey { private static final int BIT_UNIT_TEXMAT_BASE = BIT_WIDE_LINE + 1; private static final int BIT_UNIT23_UV_FROM_UNIT0 = BIT_UNIT_TEXMAT_BASE + MAX_UNITS; private static final int BIT_LINE_STIPPLE = BIT_UNIT23_UV_FROM_UNIT0 + 1; - private static final int BIT_INSTANCED = BIT_LINE_STIPPLE + 1; + private static final int BIT_INSTANCING = BIT_LINE_STIPPLE + 1; public static final int TG_NONE = 0; public static final int TG_OBJ_LINEAR = 1; @@ -97,7 +97,7 @@ public final class VertexKey { public boolean clipPlanesEnabled() { return bit(BIT_CLIP_PLANES); } public boolean wideLineEmulation() { return bit(BIT_WIDE_LINE); } public boolean lineStipple() { return bit(BIT_LINE_STIPPLE); } - public boolean instancedDraw() { return bit(BIT_INSTANCED); } + public Instancing instancing() { return Instancing.VALUES[(int) ((packed >> BIT_INSTANCING) & 0x3)]; } public boolean cmReplacesAmbient() { final int m = colorMaterialMode(); return m == CM_AMBIENT || m == CM_AMBIENT_AND_DIFFUSE; } public boolean cmReplacesDiffuse() { final int m = colorMaterialMode(); return m == CM_DIFFUSE || m == CM_AMBIENT_AND_DIFFUSE; } @@ -226,13 +226,15 @@ public final class VertexKey { bits |= (1L << BIT_LINE_STIPPLE); } - if (GLStateManager.instancedFfpDrawActive) { - bits |= (1L << BIT_INSTANCED); - } + bits |= (long) GLStateManager.ffpInstancing.ordinal() << BIT_INSTANCING; return bits; } + static long withInstancing(long packed, Instancing kind) { + return (packed & ~(0x3L << BIT_INSTANCING)) | ((long) kind.ordinal() << BIT_INSTANCING); + } + public static VertexKey fromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap, int fragUnitMask) { return new VertexKey(packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap, fragUnitMask)); } @@ -255,12 +257,6 @@ public final class VertexKey { @Override public String toString() { - return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%b]", - packed, lightingEnabled(), lightEnabled(0), lightEnabled(1), - colorMaterialEnabled(), fogEnabled(), - unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0, - unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0, - hasVertexColor(), hasVertexNormal(), hasVertexTexCoord(), hasVertexLightmap(), - texGenModeS(), texGenModeT(), texGenModeR(), texGenModeQ(), clipPlanesEnabled(), wideLineEmulation(), instancedDraw()); + return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%s]", packed,lightingEnabled(), lightEnabled(0), lightEnabled(1), colorMaterialEnabled(), fogEnabled(), unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0, unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0, hasVertexColor(), hasVertexNormal(), hasVertexTexCoord(), hasVertexLightmap(), texGenModeS(), texGenModeT(), texGenModeR(), texGenModeQ(), clipPlanesEnabled(), wideLineEmulation(), instancing()); } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java index 04acbb210..9f8133eeb 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java @@ -55,31 +55,43 @@ public final class VertexShaderGenerator { } private static void emitAttributes(StringBuilder sb, VertexKey key) { + final Instancing kind = key.instancing(); sb.append("// Vertex attributes\n"); sb.append("layout(location = ").append(VertexFormatElement.Usage.POSITION.getAttributeLocation()).append(") in vec3 a_Position;\n"); - if (key.hasVertexColor()) { - sb.append("layout(location = ").append(VertexFormatElement.Usage.COLOR.getAttributeLocation()).append(") in vec4 a_Color;\n"); - } - if (key.hasVertexTexCoord()) { + if (kind == Instancing.PARTICLE) { sb.append("layout(location = ").append(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation()).append(") in vec2 a_TexCoord0;\n"); + } else { + if (key.hasVertexColor()) { + sb.append("layout(location = ").append(VertexFormatElement.Usage.COLOR.getAttributeLocation()).append(") in vec4 a_Color;\n"); + } + if (kind != Instancing.CUBE) { + if (key.hasVertexTexCoord()) { + sb.append("layout(location = ").append(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation()).append(") in vec2 a_TexCoord0;\n"); + } + if (key.hasVertexLightmap()) { + sb.append("layout(location = ").append(VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation()).append(") in vec2 a_TexCoord1;\n"); + } + } + if (key.hasVertexNormal() || kind == Instancing.CUBE) { + sb.append("layout(location = ").append(VertexFormatElement.Usage.NORMAL.getAttributeLocation()).append(") in vec3 a_Normal;\n"); + } } - if (key.hasVertexLightmap()) { - sb.append("layout(location = ").append(VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation()).append(") in vec2 a_TexCoord1;\n"); - } - if (key.hasVertexNormal()) { - sb.append("layout(location = ").append(VertexFormatElement.Usage.NORMAL.getAttributeLocation()).append(") in vec3 a_Normal;\n"); - } - if (key.instancedDraw()) { - sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL0).append(") in vec4 a_InstCol0;\n"); - sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL1).append(") in vec4 a_InstCol1;\n"); - sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL2).append(") in vec4 a_InstCol2;\n"); - sb.append("layout(location = ").append(InstancedAttribs.LOC_MATRIX_COL3).append(") in vec4 a_InstCol3;\n"); - sb.append("layout(location = ").append(InstancedAttribs.LOC_COLOR).append(") in vec4 a_InstColor;\n"); - sb.append("layout(location = ").append(InstancedAttribs.LOC_LIGHTMAP).append(") in vec2 a_InstLightmap;\n"); + for (String d : InstancedGlslHelpers.attributeDecls("a_", kind)) { + sb.append(d).append('\n'); } sb.append('\n'); } + private static final String PARTICLE_UV = InstancedGlslHelpers.particleUv("a_InstUv", "a_TexCoord0"); + + private static String unit0Source(VertexKey key) { + return switch (key.instancing()) { + case CUBE -> "cubeUv"; + case PARTICLE -> PARTICLE_UV; + case NONE, TEMPLATE -> key.hasVertexTexCoord() ? "vec4(a_TexCoord0, 0.0, 1.0)" : "u_CurrentTexCoord0"; + }; + } + private static void emitLineStart(StringBuilder sb) { sb.append(" vec2 ndc = gl_Position.xy / gl_Position.w;\n"); sb.append(" v_LineStart = u_Viewport.xy + (ndc * 0.5 + 0.5) * u_Viewport.zw;\n\n"); @@ -93,6 +105,10 @@ public final class VertexShaderGenerator { private static void emitOutputs(StringBuilder sb, VertexKey key) { sb.append("// Outputs\n"); sb.append("out vec4 v_Color;\n"); + if (key.instancing().hasInstanceHead()) { + sb.append("out vec4 v_Overlay;\n"); + sb.append("invariant gl_Position;\n"); + } if (key.lineStipple()) { sb.append("flat out vec2 v_LineStart;\n"); } @@ -116,11 +132,16 @@ public final class VertexShaderGenerator { private static void emitPositionTransform(StringBuilder sb, VertexKey key) { sb.append(" // Position transform\n"); - sb.append(" vec4 pos4 = vec4(a_Position, 1.0);\n"); - if (key.instancedDraw()) { - sb.append(" mat4 instMV = mat4(a_InstCol0, a_InstCol1, a_InstCol2, a_InstCol3);\n"); + if (key.instancing() == Instancing.PARTICLE) { + sb.append(" vec4 pos4 = ").append(InstancedGlslHelpers.particlePos("a_InstCenterHalf", "a_Position")).append(";\n"); + } else { + sb.append(" vec4 pos4 = vec4(a_Position, 1.0);\n"); + } + if (key.instancing().hasInstanceHead()) { + sb.append(" mat4 instMV = ").append(InstancedGlslHelpers.mat4FromRows("a_InstRow0", "a_InstRow1", "a_InstRow2")).append(";\n"); sb.append(" vec4 eyePos = instMV * pos4;\n"); sb.append(" gl_Position = u_ProjectionMatrix * eyePos;\n"); + sb.append(" v_Overlay = a_InstOverlay;\n"); } else { sb.append(" gl_Position = u_MVPMatrix * pos4;\n"); @@ -134,8 +155,8 @@ public final class VertexShaderGenerator { private static void emitNormalTransform(StringBuilder sb, VertexKey key) { sb.append(" // Normal transform\n"); - final String srcNormal = key.hasVertexNormal() ? "a_Normal" : "u_CurrentNormal"; - if (key.instancedDraw()) { + final String srcNormal = key.hasVertexNormal() && key.instancing() != Instancing.PARTICLE ? "a_Normal" : "u_CurrentNormal"; + if (key.instancing().hasInstanceHead()) { sb.append(" vec3 normal = normalize(mat3(instMV) * ").append(srcNormal).append(");\n"); sb.append('\n'); return; @@ -156,9 +177,13 @@ public final class VertexShaderGenerator { if (key.colorMaterialEnabled()) { // Color material: vertex color replaces specific material properties per glColorMaterial mode (Mesa ffvertex_prog.c get_material() bitmask approach) sb.append(" vec4 matColor = "); - sb.append(key.hasVertexColor() ? "a_Color" : "u_CurrentColor"); - if (key.instancedDraw()) { - sb.append(" * a_InstColor"); + if (key.instancing() == Instancing.PARTICLE) { + sb.append("a_InstColor"); + } else { + sb.append(key.hasVertexColor() ? "a_Color" : "u_CurrentColor"); + if (key.instancing().hasInstanceHead()) { + sb.append(" * a_InstColor"); + } } sb.append(";\n"); @@ -255,22 +280,27 @@ public final class VertexShaderGenerator { private static void emitColorPassthrough(StringBuilder sb, VertexKey key) { sb.append(" // Color passthrough (no lighting)\n"); final String src = key.hasVertexColor() ? "a_Color" : "u_CurrentColor"; - if (key.instancedDraw()) { - sb.append(" v_Color = ").append(src).append(" * a_InstColor;\n"); - } else { - sb.append(" v_Color = ").append(src).append(";\n"); + switch (key.instancing()) { + case PARTICLE -> sb.append(" v_Color = a_InstColor;\n"); + case TEMPLATE, CUBE -> sb.append(" v_Color = ").append(src).append(" * a_InstColor;\n"); + case NONE -> sb.append(" v_Color = ").append(src).append(";\n"); } sb.append('\n'); } private static void emitTexCoordPassthrough(StringBuilder sb, VertexKey key) { + final boolean cube = key.instancing() == Instancing.CUBE; + final boolean unit0FromCube = cube && key.unitTexCoordEnabled(0) && !key.texGenEnabled(); + final boolean unit23FromCube = cube && key.unit23UvFromUnit0() && (key.unitTexCoordEnabled(2) || key.unitTexCoordEnabled(3)); + if (unit0FromCube || unit23FromCube) { + emitCubeTexCoord(sb); + } + if (key.texGenEnabled()) { emitTexGenCoordGeneration(sb, key); } else if (key.unitTexCoordEnabled(0)) { sb.append(" // Texture coordinates - unit 0\n"); - final String src = key.hasVertexTexCoord() - ? "vec4(a_TexCoord0, 0.0, 1.0)" - : "u_CurrentTexCoord0"; + final String src = unit0Source(key); if (key.unitTexMatEnabled(0)) { sb.append(" v_TexCoord0 = u_TextureMatrix0 * ").append(src).append(";\n"); } else { @@ -279,20 +309,17 @@ public final class VertexShaderGenerator { } if (key.lightmapEnabled()) { - if (key.instancedDraw()) { - sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(a_InstLightmap, 0.0, 1.0);\n"); - } else if (key.hasVertexLightmap()) { - sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(a_TexCoord1, 0.0, 1.0);\n"); - } else { - sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(u_CurrentLightmapCoord, 0.0, 1.0);\n"); - } + final String lightmap = switch (key.instancing()) { + case PARTICLE, TEMPLATE -> "a_InstLightmap"; + case CUBE -> "a_InstLightmapScale.xy"; + case NONE -> key.hasVertexLightmap() ? "a_TexCoord1" : "u_CurrentLightmapCoord"; + }; + sb.append(" v_TexCoord1 = u_LightmapTextureMatrix * vec4(").append(lightmap).append(", 0.0, 1.0);\n"); } for (int i = 2; i < VertexKey.MAX_UNITS; i++) { if (!key.unitTexCoordEnabled(i)) continue; - final String src = key.unit23UvFromUnit0() - ? "vec4(a_TexCoord0, 0.0, 1.0)" - : "u_CurrentTexCoord" + i; + final String src = key.unit23UvFromUnit0() ? unit0Source(key) : "u_CurrentTexCoord" + i; if (!key.unit23UvFromUnit0() && key.unitTexMatEnabled(i)) { sb.append(" v_TexCoord").append(i).append(" = u_TextureMatrix").append(i).append(" * ").append(src).append(";\n"); } else { @@ -301,6 +328,12 @@ public final class VertexShaderGenerator { } } + private static void emitCubeTexCoord(StringBuilder sb) { + sb.append(" // Cube texture net\n"); + sb.append(" ").append(InstancedGlslHelpers.cubePrelude("", "a_CubeMid", "a_CubeDelta", "a_Normal", "a_CubeTex", "\n ")).append('\n'); + sb.append(" vec4 cubeUv = ").append(InstancedGlslHelpers.cubeUv("a_CubeTex", "a_InstLightmapScale", "cubeU.x", "cubeU.y", "cubeV.x", "cubeV.y")).append(";\n\n"); + } + /** * Emit per-coordinate texgen code following Mesa's ffvertex_prog.c build order. * OBJ_LINEAR: dot(pos4, objPlane), EYE_LINEAR: dot(eyePos, eyePlane). diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java index 9d0a1cf07..d8abb241e 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.glsm.hooks; +import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.hooks.events.*; import net.minecraftforge.eventbus.api.bus.EventBus; @@ -14,6 +15,12 @@ public final class GLSMHooks { public static ShaderTransformPostProcessor postTransformProcessor; public static PerFrameUniformBlock perFrameUniformBlock; public static PerFrameUniformBlock perPassUniformBlock; + public static PendingProgramSelection pendingProgramSelection; + + public static void resolvePendingProgram() { + final PendingProgramSelection p = pendingProgramSelection; + if (p != null && !DisplayListManager.isRecording()) p.resolvePendingProgram(); + } // EventBus instances public static final EventBus TEXTURE_BIND = EventBus.create(TextureBindEvent.class); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PendingProgramSelection.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PendingProgramSelection.java new file mode 100644 index 000000000..282fabc36 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/PendingProgramSelection.java @@ -0,0 +1,5 @@ +package com.gtnewhorizons.angelica.glsm.hooks; + +public interface PendingProgramSelection { + void resolvePendingProgram(); +} diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java index 1e3558b00..89fa0effc 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockSpirvLayoutTest.java @@ -1,8 +1,12 @@ package com.gtnewhorizons.angelica.glsm.ffp; import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryUtil; import org.lwjgl.util.shaderc.Shaderc; @@ -12,6 +16,7 @@ import org.lwjgl.util.spvc.SpvcReflectedResource; import java.nio.ByteBuffer; import java.nio.IntBuffer; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -33,6 +38,47 @@ class FFPUniformBlockSpirvLayoutTest { assertBlockLayout(FragmentShaderGenerator.generate(fk), Shaderc.shaderc_fragment_shader); } + static Stream instancedKeys() { + return Stream.of( + Arguments.of("cube-lightmap-texmat", cubeKey(true, true, false)), + Arguments.of("cube-texgen", cubeKey(false, false, true)), + Arguments.of("particle-fog-texmat", particleFogTexMatKey()) + ); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("instancedKeys") + void instancedVariantCompilesToSpirv(String label, VertexKey key) { + final String glsl = VertexShaderGenerator.generate(key); + final SpirvCompiler.Result result = SpirvCompiler.compile(glsl, Shaderc.shaderc_vertex_shader, label, SpirvCompiler.Options.vulkanForced460Core()); + assertNotNull(result.spirv(), () -> "SPIR-V compile failed: " + result.error() + "\n" + glsl); + MemoryUtil.memFree(result.spirv()); + } + + private static VertexKey cubeKey(boolean lightmapUnit, boolean unit0TextureMatrix, boolean texGen) { + long bits = bit("BIT_HAS_VERTEX_COLOR") | bit("BIT_HAS_VERTEX_NORMAL") | bit("BIT_HAS_VERTEX_TEX") | bit("BIT_UNIT_TEX_BASE"); + if (lightmapUnit) bits |= 1L << (position("BIT_UNIT_TEX_BASE") + 1); + if (unit0TextureMatrix || texGen) bits |= bit("BIT_UNIT_TEXMAT_BASE"); + if (texGen) { + bits |= (long) VertexKey.TG_OBJ_LINEAR << position("BIT_TEXGEN_S"); + bits |= (long) VertexKey.TG_OBJ_LINEAR << position("BIT_TEXGEN_T"); + } + return VertexKey.fromPacked(VertexKey.withInstancing(bits, Instancing.CUBE)); + } + + private static VertexKey particleFogTexMatKey() { + final long bits = bit("BIT_UNIT_TEX_BASE") | 1L << (position("BIT_UNIT_TEX_BASE") + 1) | bit("BIT_UNIT_TEXMAT_BASE") | bit("BIT_FOG"); + return VertexKey.fromPacked(VertexKey.withInstancing(bits, Instancing.PARTICLE)); + } + + private static long bit(String name) { + return 1L << position(name); + } + + private static int position(String name) { + return Reflect.getStatic(VertexKey.class, name); + } + private static void assertBlockLayout(String glsl, int shaderKind) { final SpirvCompiler.Result result = SpirvCompiler.compile(glsl, shaderKind, "ffp-layout-test", SpirvCompiler.Options.vulkanForced460Core()); assertNotNull(result.spirv(), () -> "SPIR-V compile failed: " + result.error() + "\n" + glsl); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java index 46014fd04..5012caf9e 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/InstancedFFPDrawGLTest.java @@ -2,14 +2,23 @@ package com.gtnewhorizons.angelica.glsm.ffp; import com.gtnewhorizons.angelica.glsm.GLCoreTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PendingProgramSelection; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.COLOR_BIT; import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.NORMAL_BIT; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -22,41 +31,203 @@ class InstancedFFPDrawGLTest { private static final int TEMPLATE_STRIDE = 32; private static final int INSTANCE_STRIDE = InstancedAttribs.STRIDE; + private static final int PARITY_SIZE = 256; + private static final int INTEGER_WIDTH = 300; + private static final int INTEGER_HEIGHT = 100; + + private static final List log = new ArrayList<>(); + + private static final PendingProgramSelection LOGGING_SELECTION = () -> log.add("resolve"); + + private static final class LoggingBlendHandler implements DeferredBlendHandler { + @Override + public boolean isBlendLocked() { + return false; + } + + @Override + public boolean isOverrideHeld() { + return false; + } + + @Override + public void deferBlendModeToggle(boolean enabled) {} + + @Override + public void deferBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {} + + @Override + public void flushDeferredBlend() { + log.add("flush"); + } + } + + private static boolean capturing; + private int vao, templateVbo, instanceVbo; + @BeforeAll + static void registerForeignDrawEndListener() { + capturing = true; + GLSMHooks.FOREIGN_DRAW_END.addListener(event -> { + if (capturing) log.add("listener"); + }); + } + + @AfterAll + static void stopCapturing() { + capturing = false; + } + @AfterEach void cleanup() { - GLStateManager.instancedFfpDrawActive = false; - final ShaderManager sm = ShaderManager.getInstance(); - if (sm.isActive()) sm.deactivate(); - sm.disable(); - GLStateManager.glBindVertexArray(0); + GLSMHooks.pendingProgramSelection = null; + GLSMHooks.blendHandler = null; + log.clear(); + FfpFixture.IntegerInstances.delete(); + FfpFixture.resetFfpState(); + CubeParityFixture.disableDirectionalLight(); + CubeParityFixture.deleteResources(); + ParticleParityFixture.deleteResources(); if (templateVbo != 0) { GLStateManager.glDeleteBuffers(templateVbo); templateVbo = 0; } if (instanceVbo != 0) { GLStateManager.glDeleteBuffers(instanceVbo); instanceVbo = 0; } if (vao != 0) { GLStateManager.glDeleteVertexArrays(vao); vao = 0; } } @Test - void vertexKeyCarriesInstancedBit() { - GLStateManager.instancedFfpDrawActive = false; - final long plain = VertexKey.packFromState(true, true, false, false, 0); - GLStateManager.instancedFfpDrawActive = true; - final long instanced = VertexKey.packFromState(true, true, false, false, 0); - GLStateManager.instancedFfpDrawActive = false; + void drawArraysResolvesBeforeFlushDeferredBlend() { + GLSMHooks.pendingProgramSelection = LOGGING_SELECTION; + GLSMHooks.blendHandler = new LoggingBlendHandler(); - assertFalse(VertexKey.fromPacked(plain).instancedDraw()); - assertTrue(VertexKey.fromPacked(instanced).instancedDraw()); - assertEquals(1, Long.bitCount(plain ^ instanced), "only the instanced bit may differ"); + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 0); + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + + assertEquals(List.of("resolve", "flush"), log); + } + + @Test + void resolveIsSuppressedWhileDisplayListIsRecording() { + GLSMHooks.pendingProgramSelection = LOGGING_SELECTION; + final int list = GLStateManager.glGenLists(1); + + GLStateManager.glNewList(list, GL11.GL_COMPILE); + GLSMHooks.resolvePendingProgram(); + assertTrue(log.isEmpty()); + GLStateManager.glEndList(); + + GLSMHooks.resolvePendingProgram(); + assertEquals(List.of("resolve"), log); + } + + @Test + void nestedForeignDrawsResolveOnceAtOutermostEndBeforeListeners() { + GLSMHooks.pendingProgramSelection = LOGGING_SELECTION; + + GLStateManager.beginForeignDraw(); + GLStateManager.beginForeignDraw(); + GLStateManager.endForeignDraw(); + assertTrue(log.isEmpty()); + + GLStateManager.endForeignDraw(); + assertEquals(List.of("resolve", "listener"), log); + } + + @Test + void unitCubeMatchesBakedQuadsWithLightmap() { + assertCubeParity(true, false); + } + + @Test + void unitCubeMatchesBakedQuadsWhenLit() { + assertCubeParity(false, true); + } + + private void assertCubeParity(boolean lightmap, boolean lit) { + GLStateManager.glViewport(0, 0, PARITY_SIZE, PARITY_SIZE); + CubeParityFixture.setupScene(lightmap, lit); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + final CubeParityFixture.Spec[] specs = CubeParityFixture.specs(); + + FfpFixture.clear(); + CubeParityFixture.drawReference(specs, lightmap); + final int[] reference = FfpFixture.readRegion(PARITY_SIZE); + + FfpFixture.clear(); + CubeParityFixture.drawInstanced(specs); + final int[] instanced = FfpFixture.readRegion(PARITY_SIZE); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "parity draws must not raise a GL error"); + + CubeParityFixture.assertPixelParity(reference, instanced, PARITY_SIZE, 0xFF000000, pixel -> "0x" + Integer.toHexString(pixel)); + } + + @Test + void particleUnit0TextureMatrixMatchesReference() { + final ParticleParityFixture.Rotation rot = ParticleParityFixture.Rotation.of(35f, -12f, false); + GLStateManager.glViewport(0, 0, PARITY_SIZE, PARITY_SIZE); + ParticleParityFixture.setupScene(true); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + final ParticleParityFixture.Particle[] particles = ParticleParityFixture.particles(); + + FfpFixture.clear(); + ParticleParityFixture.drawReference(particles, rot.x(), rot.xz(), rot.z(), rot.yz(), rot.xy()); + final int[] reference = FfpFixture.readRegion(PARITY_SIZE); + + FfpFixture.clear(); + ParticleParityFixture.drawInstanced(particles, rot.x(), rot.xz(), rot.z(), rot.yz(), rot.xy()); + final int[] instanced = FfpFixture.readRegion(PARITY_SIZE); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "parity draws must not raise a GL error"); + ParticleParityFixture.assertPixelParity(reference, instanced, PARITY_SIZE, 0xFF000000, pixel -> "0x" + Integer.toHexString(pixel)); + } + + @Test + void entityAttribSelectsColorPerInstance() { + GLStateManager.glViewport(0, 0, INTEGER_WIDTH, INTEGER_HEIGHT); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + + FfpFixture.IntegerInstances.build(0.66f); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + + FfpFixture.IntegerInstances.draw(); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced ivec4 draw must not raise a GL error"); + + assertPixel(51, 50, 255, 0, 0, "entity -1 must render red"); + assertPixel(150, 50, 0, 255, 0, "entity 7 must render green"); + assertPixel(249, 50, 0, 0, 255, "entity 42 must render blue"); + } + + private static void assertPixel(int x, int y, int r, int g, int b, String label) { + final ByteBuffer pixel = BufferUtils.createByteBuffer(4); + GL11.glReadPixels(x, y, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); + final int gotR = pixel.get(0) & 0xFF; + final int gotG = pixel.get(1) & 0xFF; + final int gotB = pixel.get(2) & 0xFF; + assertEquals(r, gotR, () -> label + ": red channel, got (" + gotR + "," + gotG + "," + gotB + ")"); + assertEquals(g, gotG, () -> label + ": green channel, got (" + gotR + "," + gotG + "," + gotB + ")"); + assertEquals(b, gotB, () -> label + ": blue channel, got (" + gotR + "," + gotG + "," + gotB + ")"); } @Test void instancedSourceUsesInstanceAttribs() { - GLStateManager.instancedFfpDrawActive = true; + GLStateManager.ffpInstancing = Instancing.TEMPLATE; final VertexKey key = VertexKey.fromState(true, true, false, false, 0b10); - GLStateManager.instancedFfpDrawActive = false; + GLStateManager.ffpInstancing = Instancing.NONE; final String source = VertexShaderGenerator.generate(key); - assertTrue(source.contains("a_InstCol0"), "instance matrix attribs declared"); + assertTrue(source.contains("a_InstRow0"), "instance matrix attribs declared"); assertTrue(source.contains("mat4 instMV"), "instance matrix used as modelview"); assertTrue(source.contains("a_InstColor"), "instance color multiplier used"); assertTrue(source.contains("a_InstLightmap"), "instance lightmap coord used"); @@ -74,7 +245,7 @@ class InstancedFFPDrawGLTest { GLStateManager.disableCull(); buildTemplate(); - buildInstances(); + uploadInstances(0xFF0000FF, 0, 0xFF00FF00, 0); final ShaderManager sm = ShaderManager.getInstance(); sm.enable(); @@ -83,14 +254,12 @@ class InstancedFFPDrawGLTest { GLStateManager.glClearColor(0f, 0f, 0f, 1f); GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); - GLStateManager.instancedFfpDrawActive = true; - GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); - GLStateManager.instancedFfpDrawActive = false; + drawInstances(); assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced draw must not raise a GL error"); - final int[] left = readPixel(200, 300); - final int[] right = readPixel(600, 300); + final int[] left = FfpFixture.readPixel(200, 300); + final int[] right = FfpFixture.readPixel(600, 300); assertTrue(left[0] > 200 && left[1] < 50, "left instance red, got " + left[0] + "," + left[1] + "," + left[2]); assertTrue(right[1] > 200 && right[0] < 50, "right instance green, got " + right[0] + "," + right[1] + "," + right[2]); } @@ -106,7 +275,7 @@ class InstancedFFPDrawGLTest { GLStateManager.disableCull(); buildTemplate(); - buildInstancesWithAlpha(); + uploadInstances(0xFF0000FF, 0, 0x0D0000FF, 0); final ShaderManager sm = ShaderManager.getInstance(); sm.enable(); @@ -117,14 +286,12 @@ class InstancedFFPDrawGLTest { GLStateManager.glClearColor(0f, 0f, 0f, 1f); GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); - GLStateManager.instancedFfpDrawActive = true; - GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); - GLStateManager.instancedFfpDrawActive = false; + drawInstances(); GLStateManager.disableAlphaTest(); assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); - final int[] left = readPixel(200, 300); - final int[] right = readPixel(600, 300); + final int[] left = FfpFixture.readPixel(200, 300); + final int[] right = FfpFixture.readPixel(600, 300); assertTrue(left[0] > 200, "opaque instance drawn, got " + left[0]); assertTrue(right[0] < 20 && right[1] < 20, "alpha 0.05 instance discarded, got " + right[0] + "," + right[1]); } @@ -141,7 +308,7 @@ class InstancedFFPDrawGLTest { GLStateManager.disableCull(); buildTemplate(); - buildInstances(); + uploadInstances(0xFF0000FF, 0, 0xFF00FF00, 0); final ShaderManager sm = ShaderManager.getInstance(); sm.enable(); @@ -150,48 +317,71 @@ class InstancedFFPDrawGLTest { GLStateManager.glClearColor(0f, 0f, 0f, 1f); GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); - GLStateManager.instancedFfpDrawActive = true; - GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + drawInstances(); GLStateManager.glDepthFunc(GL11.GL_EQUAL); GLStateManager.enableBlend(); GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GLStateManager.glColor4f(1f, 1f, 1f, 1f); - rewriteInstanceColors(0x800000FF, 0x8000FF00); - GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); - GLStateManager.instancedFfpDrawActive = false; + uploadInstances(0x800000FF, 0, 0x8000FF00, 0); + drawInstances(); GLStateManager.disableBlend(); GLStateManager.glDepthFunc(GL11.GL_LEQUAL); GLStateManager.disableDepthTest(); assertEquals(GL11.GL_NO_ERROR, GL11.glGetError()); - final int[] left = readPixel(200, 300); - final int[] background = readPixel(400, 550); + final int[] left = FfpFixture.readPixel(200, 300); + final int[] background = FfpFixture.readPixel(400, 550); assertTrue(left[0] > 200, "overlay blended over base, got " + left[0]); assertTrue(background[0] < 20 && background[1] < 20, "overlay must not draw off-base, got " + background[0]); } - private void rewriteInstanceColors(int leftABGR, int rightABGR) { - final ByteBuffer patch = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); - putInstance(patch, -0.5f, leftABGR); - putInstance(patch, 0.5f, rightABGR); - patch.flip(); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); - GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, patch, GL15.GL_STATIC_DRAW); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + @Test + void perInstanceOverlayMixesOnlyTintedInstances() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + + buildTemplate(); + uploadInstances(0xFFFFFFFF, 0, 0xFFFFFFFF, 0xFF0000FF); + + final ShaderManager sm = ShaderManager.getInstance(); + sm.enable(); + sm.activate(); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + + GLStateManager.setOverlayColor(0f, 1f, 0f, 1f); + drawInstances(); + GLStateManager.setOverlayColor(0f, 0f, 0f, 0f); + + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced overlay draw must not raise a GL error"); + + final int[] left = FfpFixture.readPixel(200, 300); + final int[] right = FfpFixture.readPixel(600, 300); + assertTrue(left[0] > 200 && left[1] > 200 && left[2] > 200, "left instance overlay alpha 0 keeps its base color, got " + left[0] + "," + left[1] + "," + left[2]); + assertTrue(right[0] > 200 && right[1] < 50 && right[2] < 50, "right instance is mixed to its own opaque red overlay, got " + right[0] + "," + right[1] + "," + right[2]); } - private void buildInstancesWithAlpha() { + private void uploadInstances(int leftColor, int leftOverlay, int rightColor, int rightOverlay) { final ByteBuffer instances = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); - putInstance(instances, -0.5f, 0xFF0000FF); - putInstance(instances, 0.5f, 0x0D0000FF); + putInstance(instances, -0.5f, leftColor, leftOverlay); + putInstance(instances, 0.5f, rightColor, rightOverlay); instances.flip(); - instanceVbo = GLStateManager.glGenBuffers(); + final boolean first = instanceVbo == 0; + if (first) instanceVbo = GLStateManager.glGenBuffers(); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, instances, GL15.GL_STATIC_DRAW); - pointAndEnableInstanceAttribs(); + if (first) { + pointAndEnableInstanceAttribs(); + } GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } @@ -225,47 +415,23 @@ class InstancedFFPDrawGLTest { buf.position(base + TEMPLATE_STRIDE); } - private void buildInstances() { - final ByteBuffer instances = BufferUtils.createByteBuffer(2 * INSTANCE_STRIDE); - putInstance(instances, -0.5f, 0xFF0000FF); - putInstance(instances, 0.5f, 0xFF00FF00); - instances.flip(); - - instanceVbo = GLStateManager.glGenBuffers(); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); - GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, instances, GL15.GL_STATIC_DRAW); - pointAndEnableInstanceAttribs(); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); - } - private static void pointAndEnableInstanceAttribs() { - for (int c = 0; c < 4; c++) { - final int loc = InstancedAttribs.LOC_MATRIX_COL0 + c; - GLStateManager.glEnableVertexAttribArray(loc); - GLStateManager.glVertexAttribPointer(loc, 4, GL11.GL_FLOAT, false, INSTANCE_STRIDE, c * 16L); - GLStateManager.glVertexAttribDivisor(loc, 1); - } - GLStateManager.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR); - GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, INSTANCE_STRIDE, InstancedAttribs.OFFSET_COLOR); - GLStateManager.glVertexAttribDivisor(InstancedAttribs.LOC_COLOR, 1); - GLStateManager.glEnableVertexAttribArray(InstancedAttribs.LOC_LIGHTMAP); - GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, INSTANCE_STRIDE, InstancedAttribs.OFFSET_LIGHTMAP); - GLStateManager.glVertexAttribDivisor(InstancedAttribs.LOC_LIGHTMAP, 1); + InstancedAttribs.enableHeadArrays(); + InstancedAttribs.pointTemplate(0L); } - private void putInstance(ByteBuffer buf, float translateX, int colorABGR) { + private static void putInstance(ByteBuffer buf, float translateX, int colorABGR, int overlayABGR) { final int base = buf.position(); - buf.putFloat(base, 1f).putFloat(base + 20, 1f).putFloat(base + 40, 1f).putFloat(base + 60, 1f); - buf.putFloat(base + 48, translateX); - buf.putInt(base + InstancedAttribs.OFFSET_COLOR, colorABGR); - buf.putFloat(base + InstancedAttribs.OFFSET_LIGHTMAP, 240f); - buf.putFloat(base + InstancedAttribs.OFFSET_LIGHTMAP + 4, 240f); + final long ptr = memAddress0(buf) + base; + InstancedAttribs.writeHead(ptr, FfpFixture.translationMatrix(translateX), 0, colorABGR, overlayABGR, 0L); + memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP, 240f); + memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP + 4, 240f); buf.position(base + INSTANCE_STRIDE); } - private static int[] readPixel(int x, int y) { - final ByteBuffer pixel = BufferUtils.createByteBuffer(4); - GL11.glReadPixels(x, y, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); - return new int[] { pixel.get(0) & 0xFF, pixel.get(1) & 0xFF, pixel.get(2) & 0xFF }; + private static void drawInstances() { + GLStateManager.ffpInstancing = Instancing.TEMPLATE; + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 3, 2); + GLStateManager.ffpInstancing = Instancing.NONE; } } diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParityFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParityFixture.java new file mode 100644 index 000000000..706338733 --- /dev/null +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/CubeParityFixture.java @@ -0,0 +1,308 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.function.IntFunction; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; + +public final class CubeParityFixture { + + private static final int TEX_WIDTH = 64; + private static final int TEX_HEIGHT = 32; + private static final float SCALE = 0.0625f; + private static final short BRIGHTNESS = 240; + + public record Spec(int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate, boolean mirror) {} + + private static final float[] MODELVIEW = { + 1.25f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.25f, 0.0f, 0.0f, + 0.375f, 0.25f, -0.25f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; + + private static final float[] MODELVIEW_CONFORMAL = { + 1.0f, 0.0f, 0.75f, 0.0f, + 0.0f, 1.25f, 0.0f, 0.0f, + -0.75f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; + + private static float[] modelView = MODELVIEW; + + private static int netTexture; + private static int lightmapTexture; + + private CubeParityFixture() {} + + public static Spec[] specs() { + return new Spec[] { + new Spec(0, 0, -4, -6, -2, 8, 12, 4, 0.0f, false), + new Spec(16, 8, -3, 1, -3, 6, 4, 6, 0.25f, true), + }; + } + + private static void setupCamera(boolean conformal) { + modelView = conformal ? MODELVIEW_CONFORMAL : MODELVIEW; + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + final FloatBuffer mv = BufferUtils.createFloatBuffer(16); + mv.put(modelView).flip(); + GLStateManager.glLoadMatrix(mv); + } + + public static void setupScene(boolean lightmap, boolean lit) { + GLStateManager.glDisable(GL11.GL_FOG); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + GLStateManager.glEnable(GL11.GL_DEPTH_TEST); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + GLStateManager.glEnable(GL11.GL_CULL_FACE); + GLStateManager.glCullFace(GL11.GL_BACK); + setupCamera(lit); + if (lit) { + enableDirectionalLight(); + } else { + GLStateManager.glDisable(GL11.GL_LIGHTING); + } + + netTexture = createNetTexture(); + if (lightmap) { + lightmapTexture = createNetTexture(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, lightmapTexture); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glScalef(0.00390625f, 0.00390625f, 0.00390625f); + GLStateManager.glTranslatef(8.0f, 8.0f, 8.0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, netTexture); + } + } + + private static void enableDirectionalLight() { + final FloatBuffer buf = BufferUtils.createFloatBuffer(4); + GLStateManager.glEnable(GL11.GL_LIGHTING); + GLStateManager.glEnable(GL11.GL_NORMALIZE); + GLStateManager.glEnable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_LIGHT1); + GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, fill(buf, 0.2f, 0.2f, 0.2f, 1.0f)); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, fill(buf, 0.375f, 0.75f, 0.5f, 0.0f)); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, fill(buf, 1.0f, 1.0f, 1.0f, 1.0f)); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_AMBIENT, fill(buf, 0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, fill(buf, 0.0f, 0.0f, 0.0f, 1.0f)); + GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL); + GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE); + } + + public static void disableDirectionalLight() { + GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL); + GLStateManager.glDisable(GL11.GL_LIGHT0); + GLStateManager.glDisable(GL11.GL_NORMALIZE); + GLStateManager.glDisable(GL11.GL_LIGHTING); + } + + private static FloatBuffer fill(FloatBuffer buf, float x, float y, float z, float w) { + buf.clear(); + buf.put(x).put(y).put(z).put(w).flip(); + return buf; + } + + private static int createNetTexture() { + final int id = GLStateManager.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); + 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); + final ByteBuffer texels = BufferUtils.createByteBuffer(TEX_WIDTH * TEX_HEIGHT * 4); + for (int y = 0; y < TEX_HEIGHT; y++) { + for (int x = 0; x < TEX_WIDTH; x++) { + texels.put((byte) (16 + x * 3)); + texels.put((byte) (16 + y * 7)); + texels.put((byte) (255 - x * 3)); + texels.put((byte) 255); + } + } + texels.flip(); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, TEX_WIDTH, TEX_HEIGHT, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + return id; + } + + private static final int REF_STRIDE = 44; + + private static int referenceVao; + private static int referenceVbo; + + private static ByteBuffer buildQuadData(Spec[] specs) { + final ByteBuffer data = BufferUtils.createByteBuffer(specs.length * 24 * REF_STRIDE); + for (Spec spec : specs) { + final float[] corners = corners(spec); + for (int face = 0; face < UnitCubeMesh.FACE_COUNT; face++) { + final float[] uv = faceRect(spec, face); + final float[] normal = UnitCubeMesh.FACES[face].normal(); + for (int corner = 0; corner < 4; corner++) { + final int source = spec.mirror() ? 3 - corner : corner; + final int index = UnitCubeMesh.FACES[face].corners()[source]; + final int base = data.position(); + data.putFloat(base, corners[index * 3] * SCALE); + data.putFloat(base + 4, corners[index * 3 + 1] * SCALE); + data.putFloat(base + 8, corners[index * 3 + 2] * SCALE); + data.putInt(base + 12, 0xFFFFFFFF); + data.putFloat(base + 16, uv[(source == 0 || source == 3) ? 2 : 0]); + data.putFloat(base + 20, uv[source >= 2 ? 3 : 1]); + data.putFloat(base + 24, BRIGHTNESS); + data.putFloat(base + 28, BRIGHTNESS); + data.putFloat(base + 32, spec.mirror() ? -normal[0] : normal[0]); + data.putFloat(base + 36, normal[1]); + data.putFloat(base + 40, normal[2]); + data.position(base + REF_STRIDE); + } + } + } + data.flip(); + return data; + } + + private static int uploadQuads(int vbo, Spec[] specs, boolean lightmap) { + final ByteBuffer data = buildQuadData(specs); + if (vbo == 0) vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STREAM_DRAW); + FfpFixture.attrib(0, 3, GL11.GL_FLOAT, false, REF_STRIDE, 0); + FfpFixture.attrib(1, 4, GL11.GL_UNSIGNED_BYTE, true, REF_STRIDE, 12); + FfpFixture.attrib(2, 2, GL11.GL_FLOAT, false, REF_STRIDE, 16); + if (lightmap) { + FfpFixture.attrib(3, 2, GL11.GL_FLOAT, false, REF_STRIDE, 24); + } else { + GLStateManager.glDisableVertexAttribArray(3); + } + FfpFixture.attrib(4, 3, GL11.GL_FLOAT, false, REF_STRIDE, 32); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + return vbo; + } + + public static void drawReference(Spec[] specs, boolean lightmap) { + if (referenceVao == 0) referenceVao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(referenceVao); + referenceVbo = uploadQuads(referenceVbo, specs, lightmap); + VAOManager.setCurrentVertexFlags(UnitCubeMesh.VERTEX_FLAGS | (lightmap ? VertexFlags.BRIGHTNESS_BIT : 0)); + + GLStateManager.glDrawArrays(GL11.GL_QUADS, 0, specs.length * 24); + GLStateManager.glBindVertexArray(0); + } + + private static float[] corners(Spec spec) { + final float minX = spec.x() - spec.inflate(); + final float minY = spec.y() - spec.inflate(); + final float minZ = spec.z() - spec.inflate(); + final float maxX = (spec.x() + spec.sizeX()) + spec.inflate(); + final float maxY = (spec.y() + spec.sizeY()) + spec.inflate(); + final float maxZ = (spec.z() + spec.sizeZ()) + spec.inflate(); + final float lowX = spec.mirror() ? maxX : minX; + final float highX = spec.mirror() ? minX : maxX; + final float[] out = new float[UnitCubeMesh.CORNERS.length * 3]; + for (int index = 0; index < UnitCubeMesh.CORNERS.length; index++) { + final float[] corner = UnitCubeMesh.CORNERS[index]; + out[index * 3] = corner[0] > 0f ? highX : lowX; + out[index * 3 + 1] = corner[1] > 0f ? maxY : minY; + out[index * 3 + 2] = corner[2] > 0f ? maxZ : minZ; + } + return out; + } + + private static float[] faceRect(Spec spec, int face) { + final int i = spec.texU(); + final int j = spec.texV(); + final int k = spec.sizeX(); + final int l = spec.sizeY(); + final int m = spec.sizeZ(); + final int[] rect = switch (face) { + case 0 -> new int[] { i + m + k, j + m, i + m + k + m, j + m + l }; + case 1 -> new int[] { i, j + m, i + m, j + m + l }; + case 2 -> new int[] { i + m, j, i + m + k, j + m }; + case 3 -> new int[] { i + m + k, j + m, i + m + k + k, j }; + case 4 -> new int[] { i + m, j + m, i + m + k, j + m + l }; + default -> new int[] { i + m + k + m, j + m, i + m + k + m + k, j + m + l }; + }; + return new float[] { + rect[0] / (float) TEX_WIDTH, rect[1] / (float) TEX_HEIGHT, + rect[2] / (float) TEX_WIDTH, rect[3] / (float) TEX_HEIGHT, + }; + } + + private static int instanceVbo; + + public static void drawInstanced(Spec[] specs) { + final ByteBuffer records = BufferUtils.createByteBuffer(specs.length * CubeInstancedAttribs.STRIDE); + final long records0 = memAddress0(records); + for (int index = 0; index < specs.length; index++) { + final Spec spec = specs[index]; + final CubeParams cube = CubeParams.of(TEX_WIDTH, TEX_HEIGHT, spec.mirror(), spec.texU(), spec.texV(), spec.x(), spec.y(), spec.z(), spec.sizeX(), spec.sizeY(), spec.sizeZ(), spec.inflate()); + if (cube == null) { + throw new AssertionError("spec " + index + " is not cube instanceable"); + } + final long ptr = records0 + (long) index * CubeInstancedAttribs.STRIDE; + cube.writeRows(ptr, modelView, 0, SCALE); + InstancedAttribs.writeTail(ptr, 0xFFFFFFFF, 0, 0L); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE, BRIGHTNESS); + memPutFloat(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE + 4, BRIGHTNESS); + cube.writeTexture(ptr); + } + records.position(0).limit(specs.length * CubeInstancedAttribs.STRIDE); + + GLStateManager.glBindVertexArray(UnitCubeMesh.vao()); + VAOManager.setCurrentVertexFlags(UnitCubeMesh.VERTEX_FLAGS); + if (instanceVbo == 0) instanceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, records, GL15.GL_STREAM_DRAW); + CubeInstancedAttribs.pointInstanceAttribs(0L); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + GLStateManager.ffpInstancing = Instancing.CUBE; + GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, specs.length); + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + } + + public static void assertPixelParity(int[] reference, int[] instanced, int size, int background, IntFunction describe) { + FfpFixture.assertPixelParity("instanced cubes", reference, instanced, size, background, 8, 1, describe); + } + + public static void deleteResources() { + if (instanceVbo != 0) { + GLStateManager.glDeleteBuffers(instanceVbo); + instanceVbo = 0; + } + if (referenceVbo != 0) { + GLStateManager.glDeleteBuffers(referenceVbo); + referenceVbo = 0; + } + if (referenceVao != 0) { + GLStateManager.glDeleteVertexArrays(referenceVao); + referenceVao = 0; + } + if (netTexture != 0) { + GLStateManager.glDeleteTextures(netTexture); + netTexture = 0; + } + if (lightmapTexture != 0) { + GLStateManager.glDeleteTextures(lightmapTexture); + lightmapTexture = 0; + } + UnitCubeMesh.delete(); + } +} diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java new file mode 100644 index 000000000..9b579509e --- /dev/null +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java @@ -0,0 +1,272 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; + +import java.nio.ByteBuffer; +import java.util.function.IntFunction; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public final class FfpFixture { + + private FfpFixture() {} + + public static final class IntegerInstances { + + private static final int INSTANCES = 3; + + private static final String VS_HEAD = """ + #version 330 core + layout(location = 0) in vec3 a_Position; + layout(location = 5) in vec4 a_InstRow0; + layout(location = 6) in vec4 a_InstRow1; + layout(location = 7) in vec4 a_InstRow2; + layout(location = 11) in ivec4 iris_Entity; + flat out vec3 v_Color; + void main() { + """; + + private static final String VS_TAIL = """ + gl_Position = instMV * vec4(a_Position, 1.0); + if (iris_Entity.x == -1) { v_Color = vec3(1.0, 0.0, 0.0); } + else if (iris_Entity.x == 7) { v_Color = vec3(0.0, 1.0, 0.0); } + else { v_Color = vec3(0.0, 0.0, 1.0); } + } + """; + + private static final String VS = VS_HEAD + " mat4 instMV = " + InstancedGlslHelpers.mat4FromRows("a_InstRow0", "a_InstRow1", "a_InstRow2") + ";\n" + VS_TAIL; + + private static final String FS = """ + #version 330 core + flat in vec3 v_Color; + out vec4 fragColor; + void main() { fragColor = vec4(v_Color, 1.0); } + """; + + private static int program; + private static int vao; + private static int templateVbo; + private static int instanceVbo; + + private IntegerInstances() {} + + public static void build(float spacing) { + program = buildProgram(); + GLStateManager.glUseProgram(program); + + buildTemplate(); + buildInstances(new float[] { -spacing, 0.0f, spacing }, new int[] { -1, 7, 42 }); + } + + public static void draw() { + GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, 4, INSTANCES); + } + + public static void delete() { + GLStateManager.glUseProgram(0); + if (program != 0) { GLStateManager.glDeleteProgram(program); program = 0; } + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + if (templateVbo != 0) { GLStateManager.glDeleteBuffers(templateVbo); templateVbo = 0; } + if (instanceVbo != 0) { GLStateManager.glDeleteBuffers(instanceVbo); instanceVbo = 0; } + GLStateManager.glBindVertexArray(0); + if (vao != 0) { GLStateManager.glDeleteVertexArrays(vao); vao = 0; } + } + + private static void buildTemplate() { + vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + + final ByteBuffer quad = BufferUtils.createByteBuffer(4 * 12); + putVertex(quad, -0.15f, -0.8f); + putVertex(quad, 0.15f, -0.8f); + putVertex(quad, 0.15f, 0.8f); + putVertex(quad, -0.15f, 0.8f); + quad.flip(); + + templateVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, templateVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, quad, GL15.GL_STATIC_DRAW); + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 12, 0L); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + private static void putVertex(ByteBuffer buf, float x, float y) { + final int base = buf.position(); + buf.putFloat(base, x).putFloat(base + 4, y).putFloat(base + 8, 0f); + buf.position(base + 12); + } + + private static void buildInstances(float[] translateX, int[] entities) { + final ByteBuffer instances = BufferUtils.createByteBuffer(entities.length * InstancedAttribs.STRIDE); + final long base0 = memAddress0(instances); + for (int i = 0; i < entities.length; i++) { + final long ptr = base0 + (long) i * InstancedAttribs.STRIDE; + InstancedAttribs.writeHead(ptr, translationMatrix(translateX[i]), 0, 0xFFFFFFFF, 0, InstancedAttribs.packEntityInfo(entities[i], 0, 0)); + } + instances.position(0).limit(entities.length * InstancedAttribs.STRIDE); + + instanceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, instances, GL15.GL_STATIC_DRAW); + InstancedAttribs.enableHeadArrays(); + InstancedAttribs.pointTemplate(0L); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + } + + private static int buildProgram() { + final int vs = compile(GL20.GL_VERTEX_SHADER, VS); + final int fs = compile(GL20.GL_FRAGMENT_SHADER, FS); + final int p = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(p, vs); + GLStateManager.glAttachShader(p, fs); + GLStateManager.glLinkProgram(p); + assertNotEquals(0, GLStateManager.glGetProgrami(p, GL20.GL_LINK_STATUS), () -> "test program must link: " + GLStateManager.glGetProgramInfoLog(p, 4096)); + GLStateManager.glDeleteShader(vs); + GLStateManager.glDeleteShader(fs); + return p; + } + + private static int compile(int type, String source) { + final int shader = GLStateManager.glCreateShader(type); + GLStateManager.glShaderSource(shader, source); + GLStateManager.glCompileShader(shader); + if (GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) == 0) { + fail("test shader failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096) + "\n\n" + source); + } + return shader; + } + } + + public static void attrib(int loc, int size, int type, boolean normalized, int stride, int offset) { + GLStateManager.glEnableVertexAttribArray(loc); + GLStateManager.glVertexAttribPointer(loc, size, type, normalized, stride, offset); + } + + public static void clear() { + GLStateManager.glClearColor(0f, 0f, 0f, 0f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + } + + public static int[] readRegion(int size) { + final ByteBuffer pixels = BufferUtils.createByteBuffer(size * size * 4); + GLStateManager.glReadPixels(0, 0, size, size, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + final int[] out = new int[size * size]; + for (int i = 0; i < out.length; i++) { + out[i] = pixels.getInt(i * 4); + } + return out; + } + + public static int[] readPixel(int x, int y) { + final ByteBuffer pixel = BufferUtils.createByteBuffer(4); + GLStateManager.glReadPixels(x, y, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); + return new int[] { pixel.get(0) & 0xFF, pixel.get(1) & 0xFF, pixel.get(2) & 0xFF, pixel.get(3) & 0xFF }; + } + + public static int solidTexture(int r, int g, int b, int a) { + final int id = GLStateManager.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); + 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); + final ByteBuffer texels = BufferUtils.createByteBuffer(2 * 2 * 4); + for (int i = 0; i < 4; i++) { + texels.put((byte) r).put((byte) g).put((byte) b).put((byte) a); + } + texels.flip(); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, 2, 2, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + return id; + } + + public static float[] translationMatrix(float x) { + return new float[] { + 1f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, + 0f, 0f, 1f, 0f, + x, 0f, 0f, 1f, + }; + } + + public static void assertPixelParity(String subject, int[] reference, int[] candidate, int size, int background, int minCoverageDivisor, int channelTolerance, IntFunction describe) { + int covered = 0; + for (int pixel : reference) { + if (pixel != background) covered++; + } + final int coveredPixels = covered; + assertTrue(coveredPixels > reference.length / minCoverageDivisor, () -> "reference draw covered only " + coveredPixels + " of " + reference.length + " pixels"); + + int mismatches = 0; + int firstMismatch = -1; + for (int i = 0; i < reference.length; i++) { + if (!withinTolerance(reference[i], candidate[i], channelTolerance)) { + mismatches++; + if (firstMismatch < 0) firstMismatch = i; + } + } + final int index = firstMismatch; + final int differing = mismatches; + assertEquals(0, mismatches, () -> subject + " differ from baked quads in " + differing + " of " + reference.length + " pixels, first at (" + (index % size) + "," + (index / size) + "): reference " + describe.apply(reference[index]) + " instanced " + describe.apply(candidate[index])); + } + + private static boolean withinTolerance(int a, int b, int tolerance) { + if (tolerance == 0) return a == b; + for (int shift = 0; shift <= 24; shift += 8) { + final int ca = (a >> shift) & 0xFF; + final int cb = (b >> shift) & 0xFF; + if (Math.abs(ca - cb) > tolerance) return false; + } + return true; + } + + public static void assertOverlayFootprint(int[] base, int[] overlay, int background, String overlayName) { + int covered = 0; + for (int i = 0; i < base.length; i++) { + final int index = i; + if (base[i] != background) { + covered++; + assertTrue(base[i] != overlay[i], () -> "pixel " + index + " covered by the base draw did not change under the " + overlayName + ": 0x" + Integer.toHexString(overlay[index])); + } else { + assertEquals(base[i], overlay[i], () -> "pixel " + index + " outside the base footprint must not be touched by the " + overlayName); + } + } + final int coveredPixels = covered; + assertTrue(coveredPixels > base.length / 8, "base draw covered only " + coveredPixels + " of " + base.length + " pixels"); + } + + public static void resetFfpState() { + GLStateManager.ffpInstancing = Instancing.NONE; + final ShaderManager sm = ShaderManager.getInstance(); + if (sm.isActive()) sm.deactivate(); + sm.disable(); + GLStateManager.glBindVertexArray(0); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDepthMask(true); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDisable(GL11.GL_DEPTH_TEST); + GLStateManager.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + } +} diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleParityFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleParityFixture.java new file mode 100644 index 000000000..02484a141 --- /dev/null +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/ParticleParityFixture.java @@ -0,0 +1,216 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.util.function.IntFunction; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; + +public final class ParticleParityFixture { + + public record Particle(float cx, float cy, float cz, float half, float u0, float v0, float u1, float v1, int colorABGR) {} + + public record Rotation(float x, float xz, float z, float yz, float xy) { + public static Rotation of(float yawDeg, float pitchDeg, boolean thirdPersonFront) { + final float sign = thirdPersonFront ? -1f : 1f; + final float yaw = (float) Math.toRadians(yawDeg); + final float pitch = (float) Math.toRadians(pitchDeg); + final float rotX = (float) Math.cos(yaw) * sign; + final float rotZ = (float) Math.sin(yaw) * sign; + final float rotYZ = -rotZ * (float) Math.sin(pitch) * sign; + final float rotXY = rotX * (float) Math.sin(pitch) * sign; + final float rotXZ = (float) Math.cos(pitch); + return new Rotation(rotX, rotXZ, rotZ, rotYZ, rotXY); + } + + public float offsetX(float a, float b) { + return a * x + b * yz; + } + + public float offsetY(float b) { + return b * xz; + } + + public float offsetZ(float a, float b) { + return a * z + b * xy; + } + } + + private static final float[] CORNER_A = { -1.0f, -1.0f, 1.0f, 1.0f }; + private static final float[] CORNER_B = { -1.0f, 1.0f, 1.0f, -1.0f }; + + private static final int REF_STRIDE = 24; + + private static int referenceVao; + private static int referenceVbo; + private static int instanceVbo; + private static int checkerTexture; + + private ParticleParityFixture() {} + + public static float cornerA(int corner) { + return CORNER_A[corner]; + } + + public static float cornerB(int corner) { + return CORNER_B[corner]; + } + + public static Particle[] particles() { + return new Particle[] { + new Particle(-0.75f, 0.6f, 0f, 0.10f, 0f, 0f, 1f, 1f, 0xFF0000FF), + new Particle(-0.45f, -0.55f, 0f, 0.16f, 0f, 0f, 1f, 1f, 0xFF00FF00), + new Particle(-0.15f, 0.2f, 0f, 0.07f, 0f, 0f, 1f, 1f, 0xFFFF0000), + new Particle(0.1f, 0.75f, 0f, -0.12f, 0f, 0f, 1f, 1f, 0xFF00FFFF), + new Particle(0.35f, -0.3f, 0f, 0.20f, 0f, 0f, 1f, 1f, 0xFFFF00FF), + new Particle(0.6f, 0.45f, 0f, -0.08f, 0f, 0f, 1f, 1f, 0xFFFFFF00), + new Particle(0.8f, -0.7f, 0f, 0.13f, 0f, 0f, 1f, 1f, 0xFFFFFFFF), + new Particle(-0.8f, -0.1f, 0f, 0.09f, 0f, 0f, 1f, 1f, 0xFF0080FF), + }; + } + + private static int createCheckerTexture() { + final int id = GLStateManager.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); + 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); + final ByteBuffer texels = BufferUtils.createByteBuffer(2 * 2 * 4); + putTexel(texels, 255, 32, 32); + putTexel(texels, 32, 255, 32); + putTexel(texels, 32, 32, 255); + putTexel(texels, 255, 255, 32); + texels.flip(); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, 2, 2, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + return id; + } + + private static void putTexel(ByteBuffer buf, int r, int g, int b) { + buf.put((byte) r).put((byte) g).put((byte) b).put((byte) 255); + } + + public static void setupScene(boolean textureMatrix) { + GLStateManager.glDisable(GL11.GL_FOG); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + GLStateManager.glDisable(GL11.GL_DEPTH_TEST); + GLStateManager.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glDisable(GL11.GL_LIGHTING); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + + checkerTexture = createCheckerTexture(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, checkerTexture); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + if (textureMatrix) { + GLStateManager.glTranslatef(0.1f, 0.1f, 0.0f); + GLStateManager.glScalef(0.8f, 0.8f, 1.0f); + } + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + private static ByteBuffer buildReferenceData(Particle[] particles, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY) { + final ByteBuffer data = BufferUtils.createByteBuffer(particles.length * 4 * REF_STRIDE); + for (Particle p : particles) { + for (int i = 0; i < 4; i++) { + final float a = cornerA(i); + final float b = cornerB(i); + final float ox = a * rotX + b * rotYZ; + final float oy = b * rotXZ; + final float oz = a * rotZ + b * rotXY; + final float u = a < 0f ? p.u0() : p.u1(); + final float v = b < 0f ? p.v0() : p.v1(); + final int base = data.position(); + data.putFloat(base, p.cx() + ox * p.half()); + data.putFloat(base + 4, p.cy() + oy * p.half()); + data.putFloat(base + 8, p.cz() + oz * p.half()); + data.putInt(base + 12, p.colorABGR()); + data.putFloat(base + 16, u); + data.putFloat(base + 20, v); + data.position(base + REF_STRIDE); + } + } + data.flip(); + return data; + } + + public static void drawReference(Particle[] particles, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY) { + final ByteBuffer data = buildReferenceData(particles, rotX, rotXZ, rotZ, rotYZ, rotXY); + + if (referenceVao == 0) referenceVao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(referenceVao); + if (referenceVbo == 0) referenceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, referenceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STREAM_DRAW); + FfpFixture.attrib(0, 3, GL11.GL_FLOAT, false, REF_STRIDE, 0); + FfpFixture.attrib(1, 4, GL11.GL_UNSIGNED_BYTE, true, REF_STRIDE, 12); + FfpFixture.attrib(2, 2, GL11.GL_FLOAT, false, REF_STRIDE, 16); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + VAOManager.setCurrentVertexFlags(VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT); + + GLStateManager.glDrawArrays(GL11.GL_QUADS, 0, particles.length * 4); + GLStateManager.glBindVertexArray(0); + } + + public static void drawInstanced(Particle[] particles, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY) { + ParticleQuadMesh.update(rotX, rotXZ, rotZ, rotYZ, rotXY); + + final ByteBuffer records = BufferUtils.createByteBuffer(particles.length * ParticleInstancedAttribs.STRIDE); + final long records0 = memAddress0(records); + for (int i = 0; i < particles.length; i++) { + final Particle p = particles[i]; + final long ptr = records0 + (long) i * ParticleInstancedAttribs.STRIDE; + ParticleInstancedAttribs.writeInstance(ptr, p.cx(), p.cy(), p.cz(), p.half(), p.u0(), p.v0(), p.u1(), p.v1(), p.colorABGR(), 0); + } + records.position(0).limit(particles.length * ParticleInstancedAttribs.STRIDE); + + GLStateManager.glBindVertexArray(ParticleQuadMesh.vao()); + VAOManager.setCurrentVertexFlags(ParticleQuadMesh.VERTEX_FLAGS); + if (instanceVbo == 0) instanceVbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, records, GL15.GL_STREAM_DRAW); + ParticleInstancedAttribs.pointInstanceAttribs(0L); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + GLStateManager.ffpInstancing = Instancing.PARTICLE; + GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, ParticleQuadMesh.VERTEX_COUNT, particles.length); + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + } + + public static void assertPixelParity(int[] reference, int[] instanced, int size, int background, IntFunction describe) { + FfpFixture.assertPixelParity("instanced particles", reference, instanced, size, background, 16, 1, describe); + } + + public static void deleteResources() { + if (instanceVbo != 0) { + GLStateManager.glDeleteBuffers(instanceVbo); + instanceVbo = 0; + } + if (referenceVbo != 0) { + GLStateManager.glDeleteBuffers(referenceVbo); + referenceVbo = 0; + } + if (referenceVao != 0) { + GLStateManager.glDeleteVertexArrays(referenceVao); + referenceVao = 0; + } + if (checkerTexture != 0) { + GLStateManager.glDeleteTextures(checkerTexture); + checkerTexture = 0; + } + ParticleQuadMesh.delete(); + } +} diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java index 876931dda..30fe4b365 100644 --- a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/testutil/Reflect.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm.testutil; import com.gtnewhorizon.gtnhlib.reflect.Fields; import com.gtnewhorizon.gtnhlib.reflect.Fields.LookupType; +import sun.misc.Unsafe; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -99,6 +100,17 @@ public final class Reflect { } } + @SuppressWarnings("unchecked") + public static T allocate(Class type) { + try { + final Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (T) ((Unsafe) f.get(null)).allocateInstance(type); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + private static Method resolve(Class owner, String name, Class[] signature) throws NoSuchMethodException { for (Class c = owner; c != null; c = c.getSuperclass()) { try { diff --git a/scripts/flyby-bench.sh b/scripts/flyby-bench.sh index 8057c5bb6..d284a244f 100755 --- a/scripts/flyby-bench.sh +++ b/scripts/flyby-bench.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Usage: scripts/flyby-bench.sh ffp|pack [flyby-capture.sh args...] -# Env: FLYBY_SCENE, TIME_OF_DAY, QUICKPLAY_WORLD, TRACY_CAPTURE, SDLGPU, RENDER_DISTANCE. +# Env: FLYBY_SCENE, FLYBY_ORIGIN, TIME_OF_DAY, QUICKPLAY_WORLD, TRACY_CAPTURE, SDLGPU, RENDER_DISTANCE. # Forces particles:0 for the run and restores it after exit; the game rewrites options.txt on quit. # A worktree needs tracy-client/src/main/resources/natives copied in. @@ -40,6 +40,7 @@ fi export FLYBY_SCENE="${FLYBY_SCENE:-scripts/flyby-scenes/entities-x8.txt}" export QUICKPLAY_WORLD="${QUICKPLAY_WORLD:-Flat World - No Mods}" +if [ "$QUICKPLAY_WORLD" = "Flat World - No Mods" ]; then export FLYBY_ORIGIN="${FLYBY_ORIGIN-1509.5,-924.5,0}"; fi export TRACY_CAPTURE="${TRACY_CAPTURE:-$HOME/dev/mc/tracy/capture/build/tracy-capture}" export SDLGPU="${SDLGPU:-1}" diff --git a/scripts/flyby-capture.sh b/scripts/flyby-capture.sh index a91149d02..fc3e7b4ef 100755 --- a/scripts/flyby-capture.sh +++ b/scripts/flyby-capture.sh @@ -12,6 +12,7 @@ # # FLYBY_SPEED - blocks per tick. (0.5 ~= creative flight). # FLYBY_PACING - UNCAPPED | CONFIGURED. Passed through when set. +# FLYBY_ORIGIN - x,z[,yaw] flight start. Unset or empty starts where the player is. # QUICKPLAY_WORLD - save to auto-load (default: latest). # FLYBY_SCENE - server command file run at flyby start. # SDLGPU=0|1 - force OpenGL (0) or SDL-GPU (1); unset uses the build default. @@ -43,6 +44,9 @@ fi if [ -n "${FLYBY_PACING:-}" ]; then BACKEND_ARGS+=(-Dangelica.flyby.pacing="$FLYBY_PACING") fi +if [ -n "${FLYBY_ORIGIN:-}" ]; then + BACKEND_ARGS+=(-Dangelica.flyby.origin="$FLYBY_ORIGIN") +fi SCENE_ABS="" SCENE_ARGS=() diff --git a/scripts/flyby-compare.py b/scripts/flyby-compare.py index 54d977b8e..bb576c9de 100755 --- a/scripts/flyby-compare.py +++ b/scripts/flyby-compare.py @@ -8,12 +8,14 @@ import sys CSVEXPORT = os.environ.get("TRACY_CSVEXPORT", os.path.expanduser("~/dev/mc/tracy/csvexport/build/tracy-csvexport")) PLOTS = [ - "gl.drawCalls", "gl.listPlaybacks", "gl.streamDraws", "entitiesRendered", "blockEntitiesRendered", "tesr.modelParts", "tesr.retainedDraws", "tesr.cacheMisses", "tesr.instancedDraws", "tesr.instancedInstances", - "tesr.streamedInstances", "tesr.liveFallbacks", "tesr.bail.hurtFlash", "tesr.bail.foreignProgram", - "tesr.bail.material", "tesr.bail.texture", "sdl.renderPasses", "sdl.submits", "sdl.gpuWaitUs", + "gl.drawCalls", "gl.listPlaybacks", "gl.streamDraws", "entitiesRendered", "blockEntitiesRendered", "tesr.modelParts", "tesr.retainedDraws", "tesr.cacheMisses", "tesr.instancedDraws", "tesr.instancedInstances", "tesr.cubeInstances", + "tesr.streamedInstances", "tesr.texMatrixRuns", "tesr.liveFallbacks", "tesr.bail.foreignProgram", + "tesr.bail.material", "tesr.bail.texture", "entity.shadowQuads", "entity.shadowDraws", "items.instanced", "items.fallback", "items.glintInstanced", + "items.bail.ineligible", "items.bail.material", "items.bail.isbrh", "items.bail.blockState", "items.bail.notAllowed", "items.bail.template", "items.bail.queue", + "particles.direct", "particles.captured", "particles.spilled", "particles.undecodable", "particles.draws", "sdl.renderPasses", "sdl.submits", "sdl.gpuWaitUs", "sdl.acquireWaitUs", ] -ZONES = ["entityModelParts", "tesrBatch", "tesrInstanced", "tesrOpaque"] +ZONES = ["entityModelParts", "tesrBatch", "tesrInstanced", "entityLayerLoop", "tesrOpaque", "particlePass"] CLOCK = "gl.drawCalls" diff --git a/scripts/flyby-scenes/entities-x8.txt b/scripts/flyby-scenes/entities-x8.txt index 26c478532..df5ee6075 100644 --- a/scripts/flyby-scenes/entities-x8.txt +++ b/scripts/flyby-scenes/entities-x8.txt @@ -1,4 +1,4 @@ -# entities.txt at 8x density. Summons are relative to the player; start facing south (yaw 0). +# entities.txt at 8x density. Summons are relative to the flight start; start facing south (yaw 0). # gamerules difficulty 1 diff --git a/scripts/flyby-scenes/entities.txt b/scripts/flyby-scenes/entities.txt index 4c03d34e1..ae8215cc8 100644 --- a/scripts/flyby-scenes/entities.txt +++ b/scripts/flyby-scenes/entities.txt @@ -1,4 +1,4 @@ -# Summons are relative to the player; start facing south (yaw 0). +# Summons are relative to the flight start; start facing south (yaw 0). # gamerules difficulty 1 diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java index 513fd88b7..34f2737a7 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/SDLGPURenderBackend.java @@ -1011,6 +1011,7 @@ public class SDLGPURenderBackend extends RenderBackend { } @Override public void drawArrays(int mode, int first, int count) { + if (count <= 0) return; final FrameState f = frameManager.frame(); if (!f.frameActive) { f.droppedDrawsThisFrame++; return; } final ContextState st = s(); @@ -3969,6 +3970,7 @@ public class SDLGPURenderBackend extends RenderBackend { @Override public void drawArraysInstanced(int mode, int first, int count, int primcount) { + if (count <= 0 || primcount <= 0) return; if (!frameManager.isFrameActive()) return; final ContextState st = s(); drawDispatch.setPrimitiveTypeForDraw(st, FormatMap.mapPrimitiveType(mode)); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java index 5025f4383..f4ff43dcb 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/DrawDispatch.java @@ -109,6 +109,7 @@ public final class DrawDispatch { } public void issueIndexedDraw(ContextState st, long rp, int ebo, int indexType, int count, int instances, int firstIndex, int baseVertex) { + if (count <= 0 || instances <= 0) return; final EBOSplitScanner.EboSplit[] full; if (st.primitiveRestartEnabled) { full = resourceManager.getOrScanSplits(ebo, indexType, st.primitiveRestartSentinel); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java index 0034e39d7..8f4a3f573 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineApplier.java @@ -69,8 +69,11 @@ public final class PipelineApplier { private final IntOpenHashSet dummyVboZeroWarned = new IntOpenHashSet(); private final IntOpenHashSet staleFboWarned = new IntOpenHashSet(); private final LongOpenHashSet bogusScissorWarned = new LongOpenHashSet(); + private final LongOpenHashSet clampedScissorWarned = new LongOpenHashSet(); private final IntOpenHashSet pushUniformsNullCbWarned = new IntOpenHashSet(); + private final int[] scissorRect = new int[4]; + public PipelineApplier(FrameManager frameManager, ResourceManager resourceManager, ShaderManager shaderManager, PipelineStore pipelineStore, FBOClearTracker fboClearTracker, PersistentBufferSync persistentSync, SamplerBinder samplerBinder, StorageTextureBinder storageTextureBinder, StorageBufferBinder storageBufferBinder) { this.frameManager = frameManager; this.resourceManager = resourceManager; @@ -461,27 +464,40 @@ public final class PipelineApplier { } if (st.scissorDirty) { - final long addr = st.cachedScissor.address(); final int sx, sy, sw, sh; if (st.scissorEnabled) { sx = st.scissorX; sy = renderingToFbo ? st.scissorY : (fbo0Height(st) - st.scissorY - st.scissorH); sw = st.scissorW; sh = st.scissorH; - MemoryAccess.putInt(addr + SDL_Rect.X, sx); - MemoryAccess.putInt(addr + SDL_Rect.Y, sy); - MemoryAccess.putInt(addr + SDL_Rect.W, sw); - MemoryAccess.putInt(addr + SDL_Rect.H, sh); if ((sw <= 0 || sh <= 0) && bogusScissorWarned.add(Hashing.packHiLo(sw, sh))) { LOG.warn("applyPipelineAndState: scissor degenerate (x={} y={} w={} h={}) - all fragments clipped; boundProgram={} boundFbo={} scissorEn={} src=[{},{},{},{}]", sx, sy, sw, sh, st.boundProgram, st.boundFboId, st.scissorEnabled, st.scissorX, st.scissorY, st.scissorW, st.scissorH); } } else { - final int rectY = renderingToFbo ? (int) st.viewportY : (int) (fbo0Height(st) - st.viewportY - st.viewportH); - MemoryAccess.putInt(addr + SDL_Rect.X, (int) st.viewportX); - MemoryAccess.putInt(addr + SDL_Rect.Y, rectY); - MemoryAccess.putInt(addr + SDL_Rect.W, (int) st.viewportW); - MemoryAccess.putInt(addr + SDL_Rect.H, (int) st.viewportH); + sx = (int) st.viewportX; + sy = renderingToFbo ? (int) st.viewportY : (int) (fbo0Height(st) - st.viewportY - st.viewportH); + sw = (int) st.viewportW; + sh = (int) st.viewportH; } + + final boolean haveFboSize = renderingToFbo && fboState != null; + final int targetW = haveFboSize ? fboState.width : frameManager.getFbo0Width(); + final int targetH = haveFboSize ? fboState.height : frameManager.getFbo0Height(); + final boolean nonEmpty = ScissorClamp.clamp(sx, sy, sw, sh, targetW, targetH, scissorRect); + final int cx = scissorRect[ScissorClamp.X]; + final int cy = scissorRect[ScissorClamp.Y]; + final int cw = scissorRect[ScissorClamp.W]; + final int ch = scissorRect[ScissorClamp.H]; + if ((cx != sx || cy != sy || cw != sw || ch != sh) && clampedScissorWarned.add(Hashing.packHiLo(st.boundProgram, st.boundFboId))) { + LOG.warn("applyPipelineAndState: scissor (x={} y={} w={} h={}) is outside the {}x{} target - clamped to (x={} y={} w={} h={}); boundProgram={} boundFbo={} scissorEn={}", sx, sy, sw, sh, targetW, targetH, cx, cy, cw, ch, st.boundProgram, st.boundFboId, st.scissorEnabled); + } + if (!nonEmpty) return false; + + final long addr = st.cachedScissor.address(); + MemoryAccess.putInt(addr + SDL_Rect.X, cx); + MemoryAccess.putInt(addr + SDL_Rect.Y, cy); + MemoryAccess.putInt(addr + SDL_Rect.W, cw); + MemoryAccess.putInt(addr + SDL_Rect.H, ch); SDL_SetGPUScissor(rp, st.cachedScissor); st.scissorDirty = false; } @@ -535,7 +551,7 @@ public final class PipelineApplier { final long elemAddr = st.vboBindingsAddr + (long) i * bindingSize; if (vboHandle != 0) { MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, vboHandle); - MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, (int) vao.bindingOffset[b]); + MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, PipelineCache.vertexOffsetBase(vao.bindingOffset[b])); } else { MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, dummyVBO); MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, i * 16); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java index 94e651f19..8db49c651 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCache.java @@ -378,6 +378,7 @@ public final class PipelineCache { | (((long) vao.attribType[i] & 0xFFFFL) << 16) | ((vao.attribNormalized[i] ? 1L : 0L) << 32) | ((vao.attribIsInteger[i] ? 1L : 0L) << 33) + | (((long) vertexOffsetMisalign(vao.bindingOffset[b]) & 3L) << 34) | (((long) b & 0xFF) << 40) | (((long) vao.attribStride[i] & 0xFFFFL) << 48); final long w1 = @@ -662,6 +663,16 @@ public final class PipelineCache { private static final int GL_TYPE_BASE = GL11.GL_BYTE; static final int INVALID_FMT = -1; + + public static final int VERTEX_BUFFER_OFFSET_ALIGN = 4; + + public static int vertexOffsetBase(long bindingOffset) { + return (int) (bindingOffset & ~(VERTEX_BUFFER_OFFSET_ALIGN - 1)); + } + + public static int vertexOffsetMisalign(long bindingOffset) { + return (int) (bindingOffset & (VERTEX_BUFFER_OFFSET_ALIGN - 1)); + } private static final int[][] VTX_FMT = buildVertexFormatTable(); private static int[] fmtSame(int s1, int s2, int s3, int s4) { @@ -839,7 +850,7 @@ public final class PipelineCache { final int boundStride = vao.bindingStride[b]; final int stride = boundStride != 0 ? boundStride : (vao.attribStride[i] != 0 ? vao.attribStride[i] : vao.attribSize[i] * GLTypes.sizeBytes(vao.attribType[i])); final int divisor = vao.bindingDivisor[b]; - final int relOff = vao.attribRelativeOffset[i]; + final int relOff = vao.attribRelativeOffset[i] + vertexOffsetMisalign(vao.bindingOffset[b]); final int attribAlign = GLTypes.sizeBytes(vao.attribType[i]); if (attribAlign > 0 && (stride % attribAlign) != 0) { LOG.warn("[PipelineCache] unaligned vertex stride: location={} stride={} type=0x{} size={} -- attribAddress will not satisfy format alignment; fix producer", i, stride, Integer.toHexString(vao.attribType[i]), vao.attribSize[i]); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClamp.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClamp.java new file mode 100644 index 000000000..8f08e6985 --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClamp.java @@ -0,0 +1,30 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +public final class ScissorClamp { + + public static final int X = 0; + public static final int Y = 1; + public static final int W = 2; + public static final int H = 3; + + private ScissorClamp() {} + + public static boolean clamp(int x, int y, int w, int h, int targetW, int targetH, int[] out) { + if (targetW <= 0 || targetH <= 0) { + out[X] = x; + out[Y] = y; + out[W] = w; + out[H] = h; + return w > 0 && h > 0; + } + final int x0 = Math.max(x, 0); + final int y0 = Math.max(y, 0); + final int x1 = (int) Math.min((long) x + w, targetW); + final int y1 = (int) Math.min((long) y + h, targetH); + out[X] = x0; + out[Y] = y0; + out[W] = Math.max(x1 - x0, 0); + out[H] = Math.max(y1 - y0, 0); + return out[W] > 0 && out[H] > 0; + } +} diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java index a12ba2e7c..49dd71e3c 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjector.java @@ -31,6 +31,8 @@ public final class PerFrameBlockInjector { private PerFrameBlockInjector() {} public static String inject(String source, PerFrameUniformBlock perFrame, PerFrameUniformBlock perPass) { + if (normalize(perFrame) == null && normalize(perPass) == null) return source; + final GLSLParser.Translation_unitContext root; try { root = GlslTransformUtils.parseFullQuiet(source); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java index 5718596ee..073f930f9 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/SamplerStripper.java @@ -26,6 +26,8 @@ public final class SamplerStripper { private SamplerStripper() {} public static String stripUnused(String source) { + if (!source.contains("sampler")) return source; + final GLSLParser.Translation_unitContext root; try { root = GlslTransformUtils.parseFullQuiet(source); diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java index 80ed5ee12..886560a43 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderManager.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.sdlgpu.shader; import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter; import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit; @@ -88,8 +89,14 @@ public final class ShaderManager { private static final int PREWARM_CACHE_MAX = 256; private static final Object2ObjectLinkedOpenHashMap PREWARM_CACHE = new Object2ObjectLinkedOpenHashMap<>(); + private record TransformKey(String source, int glShaderType, PerFrameUniformBlock perFrame, PerFrameUniformBlock perPass) {} + private record TransformEntry(String source, Set boolUniforms) {} + private static final int TRANSFORM_CACHE_MAX = 256; + private static final Object2ObjectLinkedOpenHashMap TRANSFORM_CACHE = new Object2ObjectLinkedOpenHashMap<>(); + public static void clearPrewarmCache() { synchronized (PREWARM_CACHE) { PREWARM_CACHE.clear(); } + synchronized (TRANSFORM_CACHE) { TRANSFORM_CACHE.clear(); } } private static PrewarmHit lookupPrewarm(String src, int glShaderType) { @@ -133,24 +140,35 @@ public final class ShaderManager { return; } - final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, obj.type, "shader" + shader, true); - obj.boolUniforms = pre != null ? pre.boolUniforms() : Set.of(); - String src = pre != null ? pre.rewrittenSource() : raw; - if (obj.isVertex()) { - src = ClipZRemap.injectGLToVulkanClipZ(src); + final TransformKey transformKey = new TransformKey(raw, obj.type, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + TransformEntry transformed; + synchronized (TRANSFORM_CACHE) { + transformed = TRANSFORM_CACHE.getAndMoveToFirst(transformKey); } - src = SamplerStripper.stripUnused(src); - if (obj.type == GL20.GL_VERTEX_SHADER || obj.type == GL20.GL_FRAGMENT_SHADER) { - src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + if (transformed == null) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, obj.type, "shader" + shader, true); + String src = pre != null ? pre.rewrittenSource() : raw; + if (obj.isVertex()) { + src = ClipZRemap.injectGLToVulkanClipZ(src); + } + src = SamplerStripper.stripUnused(src); + if (obj.type == GL20.GL_VERTEX_SHADER || obj.type == GL20.GL_FRAGMENT_SHADER) { + src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + } + transformed = new TransformEntry(src, pre != null ? pre.boolUniforms() : Set.of()); + synchronized (TRANSFORM_CACHE) { + TRANSFORM_CACHE.putAndMoveToFirst(transformKey, transformed); + while (TRANSFORM_CACHE.size() > TRANSFORM_CACHE_MAX) TRANSFORM_CACHE.removeLast(); + } } - - obj.source = src; + obj.boolUniforms = transformed.boolUniforms(); + obj.source = transformed.source(); final ShaderWorkSubmitter submitter = GLSMHooks.shaderWorkSubmitter; if (submitter != null) { final int shaderKind = shaderKindFor(obj); final int glType = obj.type; - final String finalSrc = src; + final String finalSrc = obj.source; obj.spirvFuture = submitter.submit(() -> { final SpirvCompiler.Result r = SpirvCompiler.compile(finalSrc, shaderKind, "shader" + shader, SpirvCompiler.Options.vulkanForced460Core()); if (r.spirv() != null && (glType == GL20.GL_VERTEX_SHADER || glType == GL20.GL_FRAGMENT_SHADER)) { diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlDegenerateDrawTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlDegenerateDrawTest.java new file mode 100644 index 000000000..733ffde64 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlDegenerateDrawTest.java @@ -0,0 +1,34 @@ +package com.gtnewhorizons.angelica.sdlgpu.glsm; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.opengl.GL11; + +@Tag("glsm-sdl") +@ExtendWith(GlsmSdlFrameExtension.class) +class GlsmSdlDegenerateDrawTest { + + private static final int RED = 0xFFFF0000; + + @BeforeAll + static void boot() { + GlsmSdlHeadlessRig.boot(); + } + + @Test + void zeroCountDrawArraysLeavesTheFollowingDrawIntact() { + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 0); + GlsmSdlHeadlessRig.solidQuad(1.0f, 0.0f, 0.0f); + GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(), RED, "after a zero-count drawArrays"); + } + + @Test + void negativeCountDrawArraysLeavesTheFollowingDrawIntact() { + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, -3); + GlsmSdlHeadlessRig.solidQuad(1.0f, 0.0f, 0.0f); + GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(), RED, "after a negative-count drawArrays"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFbo0ViewportTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFbo0ViewportTest.java index 9aae0cc84..445249c3e 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFbo0ViewportTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFbo0ViewportTest.java @@ -62,6 +62,13 @@ class GlsmSdlFbo0ViewportTest { GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); } + private static void bindFbo0WithFullViewport() { + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glViewport(0, 0, FBO0_W, FBO0_H); + GLStateManager.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + } + private static int createCopyTarget() { final int id = GLStateManager.glGenTextures(); GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); @@ -88,6 +95,33 @@ class GlsmSdlFbo0ViewportTest { GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(0, FBO0_H - VIEW, VIEW, VIEW), BLUE, "above the viewport"); } + @Test + void scissorLargerThanFbo0StillCoversTheWholeTarget() { + bindFbo0WithFullViewport(); + GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + try { + GLStateManager.glScissor(0, 0, FBO0_W + 16, FBO0_H + 16); + GlsmSdlHeadlessRig.solidQuad(1.0f, 0.0f, 0.0f); + GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(0, 0, FBO0_W, FBO0_H), RED, "inside an oversize scissor"); + } finally { + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + } + } + + @Test + void scissorRunningPastTheRightEdgeClipsToTheTarget() { + bindFbo0WithFullViewport(); + GLStateManager.glEnable(GL11.GL_SCISSOR_TEST); + try { + GLStateManager.glScissor(FBO0_W - 8, 0, 32, FBO0_H); + GlsmSdlHeadlessRig.solidQuad(1.0f, 0.0f, 0.0f); + GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(FBO0_W - 8, 0, 8, FBO0_H), RED, "inside the clipped scissor"); + GlsmSdlHeadlessRig.assertUniform(GlsmSdlHeadlessRig.readTarget(0, 0, FBO0_W - 8, FBO0_H), BLUE, "left of the scissor"); + } finally { + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + } + } + @Test void copyTexSubImage2DFromAPartialViewportKeepsGlOrientation() { bindFbo0WithSmallViewport(); diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFfpTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFfpTest.java index 4c99306c8..4fe454cbc 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFfpTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlFfpTest.java @@ -1,6 +1,11 @@ package com.gtnewhorizons.angelica.sdlgpu.glsm; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParityFixture; +import com.gtnewhorizons.angelica.glsm.ffp.FfpFixture; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.ParticleParityFixture; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -40,6 +45,14 @@ class GlsmSdlFfpTest { GlsmSdlHeadlessRig.endFrame(); } + @AfterEach + void cleanupInstancing() { + GLStateManager.ffpInstancing = Instancing.NONE; + CubeParityFixture.deleteResources(); + ParticleParityFixture.deleteResources(); + FfpFixture.IntegerInstances.delete(); + } + private static int createLightmapTexture() { final int id = GLStateManager.glGenTextures(); GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); @@ -146,9 +159,7 @@ class GlsmSdlFfpTest { GLStateManager.glCallList(list); assertTexelEverywhere("two units, glCallList"); - GlsmSdlHeadlessRig.beginFrame(); - GlsmSdlHeadlessRig.bindTarget(); - GlsmSdlHeadlessRig.clearTo(0.0f, 0.0f, 0.0f, 1.0f); + GlsmSdlHeadlessRig.beginFrameAndClear(); final IntBuffer lists = BufferUtils.createIntBuffer(1); lists.put(0, list); @@ -172,6 +183,54 @@ class GlsmSdlFfpTest { assertTrue(red < ((TEXEL >> 16) & 0xFF), () -> "lit quad is not attenuated: " + describe(center)); } + @Test + void unitCubeMatchesBakedQuadsWithLightmap() { + CubeParityFixture.setupScene(true, false); + + final CubeParityFixture.Spec[] specs = CubeParityFixture.specs(); + + CubeParityFixture.drawReference(specs, true); + final int[] reference = GlsmSdlHeadlessRig.readTarget(); + + GlsmSdlHeadlessRig.beginFrameAndClear(); + CubeParityFixture.drawInstanced(specs); + final int[] instanced = GlsmSdlHeadlessRig.readTarget(); + + CubeParityFixture.assertPixelParity(reference, instanced, SIZE, 0xFF000000, GlsmSdlHeadlessRig::describe); + } + + @Test + void particleFirstPersonRotationMatchesReference() { + final ParticleParityFixture.Rotation rot = ParticleParityFixture.Rotation.of(35f, -12f, false); + ParticleParityFixture.setupScene(false); + + final ParticleParityFixture.Particle[] particles = ParticleParityFixture.particles(); + + ParticleParityFixture.drawReference(particles, rot.x(), rot.xz(), rot.z(), rot.yz(), rot.xy()); + final int[] reference = GlsmSdlHeadlessRig.readTarget(); + + GlsmSdlHeadlessRig.beginFrameAndClear(); + ParticleParityFixture.drawInstanced(particles, rot.x(), rot.xz(), rot.z(), rot.yz(), rot.xy()); + final int[] instanced = GlsmSdlHeadlessRig.readTarget(); + + ParticleParityFixture.assertPixelParity(reference, instanced, SIZE, 0xFF000000, GlsmSdlHeadlessRig::describe); + } + + @Test + void entityAttribSelectsColorPerInstance() { + FfpFixture.IntegerInstances.build(0.6f); + + GlsmSdlHeadlessRig.beginFrameAndClear(); + + FfpFixture.IntegerInstances.draw(); + + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + + GlsmSdlHeadlessRig.assertPixel(pixels, SIZE, 13, SIZE / 2, 0xFFFF0000, "entity -1 must render red"); + GlsmSdlHeadlessRig.assertPixel(pixels, SIZE, 32, SIZE / 2, 0xFF00FF00, "entity 7 must render green"); + GlsmSdlHeadlessRig.assertPixel(pixels, SIZE, 51, SIZE / 2, 0xFF0000FF, "entity 42 must render blue"); + } + private static void enableGuiStandardItemLighting() { GLStateManager.glPushMatrix(); GLStateManager.glRotatef(-30.0f, 0.0f, 1.0f, 0.0f); diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlHeadlessRig.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlHeadlessRig.java index 08db84ca7..68c2c3b5f 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlHeadlessRig.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlHeadlessRig.java @@ -122,6 +122,12 @@ public final class GlsmSdlHeadlessRig { GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); } + public static void beginFrameAndClear() { + beginFrame(); + bindTarget(); + clearTo(0.0f, 0.0f, 0.0f, 1.0f); + } + public static void beginFrameAndReset() { beginFrame(); resetState(); diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlUnalignedAttribTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlUnalignedAttribTest.java new file mode 100644 index 000000000..6cf58936e --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlUnalignedAttribTest.java @@ -0,0 +1,137 @@ +package com.gtnewhorizons.angelica.sdlgpu.glsm; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("glsm-sdl") +@ExtendWith(GlsmSdlFrameExtension.class) +class GlsmSdlUnalignedAttribTest { + + private static final int STRIDE = 24; + private static final int FACTOR = 204; + private static final int DECOY = 64; + + private static final String VERT = """ + #version 330 core + layout(location = 0) in vec3 a_Position; + layout(location = 5) in float a_Factor; + out float v_Factor; + void main() { + gl_Position = vec4(a_Position, 1.0); + v_Factor = a_Factor; + } + """; + + private static final String FRAG = """ + #version 330 core + in float v_Factor; + out vec4 fragColor; + void main() { + fragColor = vec4(v_Factor, v_Factor, v_Factor, 1.0); + } + """; + + private static int program; + + @BeforeAll + static void boot() { + GlsmSdlHeadlessRig.boot(); + } + + private static int buildProgram() { + if (program != 0) return program; + final int vs = GLStateManager.glCreateShader(GL20.GL_VERTEX_SHADER); + GLStateManager.glShaderSource(vs, VERT); + GLStateManager.glCompileShader(vs); + assertTrue(GLStateManager.glGetShaderi(vs, GL20.GL_COMPILE_STATUS) != 0, + () -> "vertex shader: " + GLStateManager.glGetShaderInfoLog(vs)); + + final int fs = GLStateManager.glCreateShader(GL20.GL_FRAGMENT_SHADER); + GLStateManager.glShaderSource(fs, FRAG); + GLStateManager.glCompileShader(fs); + assertTrue(GLStateManager.glGetShaderi(fs, GL20.GL_COMPILE_STATUS) != 0, + () -> "fragment shader: " + GLStateManager.glGetShaderInfoLog(fs)); + + final int p = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(p, vs); + GLStateManager.glAttachShader(p, fs); + GLStateManager.glLinkProgram(p); + assertTrue(GLStateManager.glGetProgrami(p, GL20.GL_LINK_STATUS) != 0, "program did not link"); + program = p; + return p; + } + + private static int redChannelForFactorAt(int factorOffset, int decoyOffset) { + final int p = buildProgram(); + final int vao = GLStateManager.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + + final int vbo = GLStateManager.glGenBuffers(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + final ByteBuffer data = MemoryUtil.memAlloc(3 * STRIDE); + try { + for (int i = 0; i < 3 * STRIDE; i++) data.put(i, (byte) 0); + final float[][] corners = {{-1.0f, -1.0f}, {3.0f, -1.0f}, {-1.0f, 3.0f}}; + for (int v = 0; v < 3; v++) { + final int base = v * STRIDE; + data.putFloat(base, corners[v][0]); + data.putFloat(base + 4, corners[v][1]); + data.putFloat(base + 8, 0.0f); + if (decoyOffset >= 0) data.put(base + decoyOffset, (byte) DECOY); + data.put(base + factorOffset, (byte) FACTOR); + } + data.position(0).limit(3 * STRIDE); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW); + } finally { + MemoryUtil.memFree(data); + } + + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, STRIDE, 0L); + GLStateManager.glEnableVertexAttribArray(5); + GLStateManager.glVertexAttribPointer(5, 1, GL11.GL_UNSIGNED_BYTE, true, STRIDE, factorOffset); + + GLStateManager.glUseProgram(p); + try { + GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + } finally { + GLStateManager.glUseProgram(0); + } + + final int[] pixels = GlsmSdlHeadlessRig.readTarget(GlsmSdlHeadlessRig.SIZE / 2, GlsmSdlHeadlessRig.SIZE / 2, 1, 1); + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + return (pixels[0] >> 16) & 0xFF; + } + + @Test + void byteAttribAtAnAlignedOffsetReadsItsOwnByte() { + assertEquals(FACTOR, redChannelForFactorAt(20, -1), 1); + } + + @Test + void byteAttribAtAnUnalignedOffsetReadsItsOwnByte() { + assertEquals(FACTOR, redChannelForFactorAt(23, 20), 1); + } + + @Test + void byteAttribAtEveryMisalignmentReadsItsOwnByte() { + for (int offset = 20; offset <= 23; offset++) { + final int decoy = offset == 20 ? -1 : 20; + final int got = redChannelForFactorAt(offset, decoy); + assertEquals(FACTOR, got, 1, "factor byte at offset " + offset + " read back as " + got); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClampTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClampTest.java new file mode 100644 index 000000000..74f5a58ec --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/ScissorClampTest.java @@ -0,0 +1,68 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ScissorClampTest { + + private final int[] out = new int[4]; + + @Test + void rectInsideTheTargetIsUnchanged() { + assertTrue(ScissorClamp.clamp(4, 8, 16, 32, 64, 96, out)); + assertArrayEquals(new int[]{4, 8, 16, 32}, out); + } + + @Test + void overhangPastTheRightAndBottomEdgesShrinks() { + assertTrue(ScissorClamp.clamp(0, 0, 1710, 960, 1708, 960, out)); + assertArrayEquals(new int[]{0, 0, 1708, 960}, out); + + assertTrue(ScissorClamp.clamp(60, 90, 16, 32, 64, 96, out)); + assertArrayEquals(new int[]{60, 90, 4, 6}, out); + } + + @Test + void negativeOriginShrinksTheRectInsteadOfShiftingIt() { + assertTrue(ScissorClamp.clamp(-6, -10, 16, 32, 64, 96, out)); + assertArrayEquals(new int[]{0, 0, 10, 22}, out); + } + + @Test + void rectStraddlingBothEdgesIsClampedToTheWholeTarget() { + assertTrue(ScissorClamp.clamp(-8, -8, 128, 128, 64, 96, out)); + assertArrayEquals(new int[]{0, 0, 64, 96}, out); + } + + @Test + void rectFullyOutsideTheTargetIsEmpty() { + assertFalse(ScissorClamp.clamp(64, 0, 16, 32, 64, 96, out)); + assertArrayEquals(new int[]{64, 0, 0, 32}, out); + + assertFalse(ScissorClamp.clamp(-40, 0, 16, 32, 64, 96, out)); + assertArrayEquals(new int[]{0, 0, 0, 32}, out); + } + + @Test + void degenerateSourceRectIsEmpty() { + assertFalse(ScissorClamp.clamp(0, 0, 0, 32, 64, 96, out)); + assertFalse(ScissorClamp.clamp(0, 0, 16, -4, 64, 96, out)); + } + + @Test + void unknownTargetSizeLeavesTheRectAlone() { + assertTrue(ScissorClamp.clamp(-6, 4, 1710, 32, 0, 0, out)); + assertArrayEquals(new int[]{-6, 4, 1710, 32}, out); + + assertFalse(ScissorClamp.clamp(0, 0, 0, 32, 0, 96, out)); + } + + @Test + void largeRectDoesNotOverflow() { + assertTrue(ScissorClamp.clamp(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 64, 96, out)); + assertArrayEquals(new int[]{0, 0, 64, 96}, out); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java index d827f4a92..21e323dbb 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PerFrameBlockInjectorTest.java @@ -14,6 +14,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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.lwjgl.system.MemoryUtil.memFree; @@ -80,6 +81,13 @@ class PerFrameBlockInjectorTest { assertEquals(src, PerFrameBlockInjector.inject(src, new PerFrameUniformBlock(List.of()), null)); } + @Test + void noBlocksReturnsTheSourceInstance() { + final String src = "#version 330 core\nuniform float frameTimeCounter;\nvoid main() {}\n"; + assertSame(src, PerFrameBlockInjector.inject(src, null, null)); + assertSame(src, PerFrameBlockInjector.inject(src, new PerFrameUniformBlock(List.of()), new PerFrameUniformBlock(List.of()))); + } + @Test void memberShadowedByAPackDeclarationIsRenamedNotRedeclared() { final String out = PerFrameBlockInjector.inject(""" diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java index a199ace0d..c86738bb3 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/PrewarmSingleParseEquivalenceTest.java @@ -23,22 +23,9 @@ class PrewarmSingleParseEquivalenceTest { GLSMHooks.perPassUniformBlock = null; } - private static String legacy(String source, int glShaderType) { - final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, "test", true); - String src = pre != null ? pre.rewrittenSource() : source; - if (glShaderType == GL20.GL_VERTEX_SHADER) { - src = ClipZRemap.injectGLToVulkanClipZ(src); - } - src = SamplerStripper.stripUnused(src); - if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) { - src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); - } - return src; - } - private static void assertEquivalent(String label, String source, int glShaderType) { GlslVulkanPreprocess.clearCache(); - final String legacyOut = legacy(source, glShaderType); + final String legacyOut = ShaderTransformChain.run(source, glShaderType); GlslVulkanPreprocess.clearCache(); final String parseOnceOut = ShaderManager.applyPrewarmTransforms(source, glShaderType); assertEquals(legacyOut, parseOnceOut, "single-parse vs chained pipeline diverged for " + label); @@ -46,7 +33,7 @@ class PrewarmSingleParseEquivalenceTest { private static void assertEquivalentIgnoringWhitespace(String label, String source, int glShaderType) { GlslVulkanPreprocess.clearCache(); - final String legacyOut = legacy(source, glShaderType); + final String legacyOut = ShaderTransformChain.run(source, glShaderType); GlslVulkanPreprocess.clearCache(); final String parseOnceOut = ShaderManager.applyPrewarmTransforms(source, glShaderType); assertEquals(legacyOut.replaceAll("\\s+", " "), parseOnceOut.replaceAll("\\s+", " "), "single-parse vs chained pipeline diverged beyond whitespace for " + label); diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java index 436409b31..36fe6e4e2 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/SdlSamplerStripperPreprocessorTest.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.sdlgpu.shader; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; class SdlSamplerStripperPreprocessorTest { @@ -104,6 +105,16 @@ class SdlSamplerStripperPreprocessorTest { assertFalse(out.contains("uniform sampler2D u_S"), "a comment mention must not keep the decl; output:\n" + out); } + @Test + void sourceWithoutSamplersReturnsTheSourceInstance() { + final String src = "#version 460 core\n" + + "in vec3 v_Position;\n" + + "void main() {\n" + + " gl_Position = vec4(v_Position, 1.0);\n" + + "}\n"; + assertSame(src, SamplerStripper.stripUnused(src)); + } + @Test void samplerOnlyInMacroBody_isPreserved() { final String src = "#version 460 core\n" diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderSourceTransformCacheTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderSourceTransformCacheTest.java new file mode 100644 index 000000000..d06a94ba8 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderSourceTransformCacheTest.java @@ -0,0 +1,116 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock; +import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import com.gtnewhorizons.angelica.glsm.shader.UniformType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL20; + +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ShaderSourceTransformCacheTest { + + private static final String FRAG = """ + #version 460 core + uniform sampler2D u_Unused; + uniform sampler2D u_Used; + layout(location = 0) out vec4 fragColor; + void main() { + fragColor = texture(u_Used, vec2(0.5)); + } + """; + + private static final String VERT = """ + #version 460 core + layout(location = 0) in vec3 a_Position; + in vec2 a_TexCoord; + out vec2 v_TexCoord; + void main() { + v_TexCoord = a_TexCoord; + gl_Position = vec4(a_Position, 1.0); + } + """; + + private static final String PFB_FRAG = """ + #version 460 core + uniform float frameTimeCounter; + layout(location = 0) out vec4 fragColor; + void main() { + fragColor = vec4(frameTimeCounter); + } + """; + + private static final String CLIP_Z = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;"; + + @BeforeEach + void reset() { + ShaderManager.clearPrewarmCache(); + GlslVulkanPreprocess.clearCache(); + } + + @AfterEach + void clearBlocks() { + ShaderManager.clearPrewarmCache(); + GlslVulkanPreprocess.clearCache(); + GLSMHooks.perFrameUniformBlock = null; + GLSMHooks.perPassUniformBlock = null; + } + + @Test + void repeatedSourceReusesTheChainedTransform() { + final String expected = ShaderTransformChain.run(FRAG, GL20.GL_FRAGMENT_SHADER); + GlslVulkanPreprocess.clearCache(); + + final ShaderManager sm = new ShaderManager(null); + final int a = sm.createShader(GL20.GL_FRAGMENT_SHADER); + final int b = sm.createShader(GL20.GL_FRAGMENT_SHADER); + sm.shaderSource(a, FRAG); + sm.shaderSource(b, FRAG); + + assertEquals(expected, sm.getShaderSource(a)); + assertSame(sm.getShaderSource(a), sm.getShaderSource(b)); + } + + @Test + void vertexSourceMatchesTheChainAndCarriesClipZ() { + final String expected = ShaderTransformChain.run(VERT, GL20.GL_VERTEX_SHADER); + GlslVulkanPreprocess.clearCache(); + + final ShaderManager sm = new ShaderManager(null); + final int v = sm.createShader(GL20.GL_VERTEX_SHADER); + sm.shaderSource(v, VERT); + + assertEquals(expected, sm.getShaderSource(v)); + assertTrue(sm.getShaderSource(v).contains(CLIP_Z)); + } + + @Test + void blockChangeMissesTheCache() { + GLSMHooks.perFrameUniformBlock = new PerFrameUniformBlock(List.of(new Member("frameTimeCounter", UniformType.FLOAT))); + + final ShaderManager sm = new ShaderManager(null); + final int withBlock = sm.createShader(GL20.GL_FRAGMENT_SHADER); + sm.shaderSource(withBlock, PFB_FRAG); + assertTrue(sm.getShaderSource(withBlock).contains("AngelicaPerFrame")); + + GLSMHooks.perFrameUniformBlock = null; + GlslVulkanPreprocess.clearCache(); + final String expected = ShaderTransformChain.run(PFB_FRAG, GL20.GL_FRAGMENT_SHADER); + GlslVulkanPreprocess.clearCache(); + + final int withoutBlock = sm.createShader(GL20.GL_FRAGMENT_SHADER); + sm.shaderSource(withoutBlock, PFB_FRAG); + + assertEquals(expected, sm.getShaderSource(withoutBlock)); + assertFalse(sm.getShaderSource(withoutBlock).contains("AngelicaPerFrame")); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderTransformChain.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderTransformChain.java new file mode 100644 index 000000000..cddc09d31 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/shader/ShaderTransformChain.java @@ -0,0 +1,23 @@ +package com.gtnewhorizons.angelica.sdlgpu.shader; + +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess; +import org.lwjgl.opengl.GL20; + +final class ShaderTransformChain { + + private ShaderTransformChain() {} + + static String run(String source, int glShaderType) { + final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, "test", true); + String src = pre != null ? pre.rewrittenSource() : source; + if (glShaderType == GL20.GL_VERTEX_SHADER) { + src = ClipZRemap.injectGLToVulkanClipZ(src); + } + src = SamplerStripper.stripUnused(src); + if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) { + src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock); + } + return src; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java index 25f5cb989..b9c035779 100644 --- a/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/TesrMaterial.java @@ -21,7 +21,7 @@ public final class TesrMaterial { private static final ConcurrentHashMap INTERNED = new ConcurrentHashMap<>(); - public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, Transparency.OPAQUE, SpecialRender.NONE, null)); + public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, false, Transparency.OPAQUE, SpecialRender.NONE, null)); private static TesrMaterial intern(TesrMaterial material) { final TesrMaterial existing = INTERNED.putIfAbsent(material, material); @@ -39,6 +39,7 @@ public final class TesrMaterial { private final boolean isStream; private final float cutoutAlpha; private final boolean isDepthEqual; + private final boolean isUnfilteredAtlas; private final Transparency transparency; private final SpecialRender special; private final TesrShader shader; @@ -59,6 +60,7 @@ public final class TesrMaterial { private boolean stream; private float cutoutAlpha; private boolean depthEqual; + private boolean unfilteredAtlas; private Transparency transparency = Transparency.OPAQUE; private SpecialRender special = SpecialRender.NONE; private TesrShader shader; @@ -119,6 +121,11 @@ public final class TesrMaterial { return this; } + public Builder unfilteredAtlas() { + this.unfilteredAtlas = true; + return this; + } + /** Standard alpha blending (glass, liquids). SRC_ALPHA, ONE_MINUS_SRC_ALPHA */ public Builder translucent() { this.transparency = Transparency.TRANSLUCENT; @@ -158,7 +165,7 @@ public final class TesrMaterial { if (special != SpecialRender.NONE && shader != null) { throw new IllegalStateException("special() and shader() are mutually exclusive"); } - return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, transparency, special, shader)); + return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, unfilteredAtlas, transparency, special, shader)); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java b/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java index 3c2f73c0a..7f01acc09 100644 --- a/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java +++ b/src/main/java/com/gtnewhorizons/angelica/api/tesr/package-info.java @@ -1,5 +1,5 @@ /** TESR mesh cache/batch API (Render thread only) */ -@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "1") +@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "2") package com.gtnewhorizons.angelica.api.tesr; import cpw.mods.fml.common.API; diff --git a/src/main/java/com/gtnewhorizons/angelica/client/rendering/DeferredBatchTessellator.java b/src/main/java/com/gtnewhorizons/angelica/client/rendering/DeferredBatchTessellator.java index 9fe51b3cb..b7cebe5c8 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/rendering/DeferredBatchTessellator.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/rendering/DeferredBatchTessellator.java @@ -5,7 +5,6 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.ITessellatorInstance; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; -import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.renderer.Tessellator; import org.joml.Matrix4f; import org.joml.Matrix4fc; @@ -28,8 +27,7 @@ class DeferredBatchTessellator extends DirectTessellator { record DrawRange(long stateKey, int byteOffset, int byteLength, int vertexCount, int drawMode, int flags) {} private final List ranges = new ArrayList<>(); - private final Matrix4f defaultModelview = new Matrix4f(); - private final Matrix4f defaultModelviewInverse = new Matrix4f(); + private final ModelViewDelta modelViewDelta = new ModelViewDelta(); private final Matrix4f deltaMatrix = new Matrix4f(); // reusable scratch private final Vector3f scratch = new Vector3f(); private Matrix4fc currentTransform; @@ -68,22 +66,14 @@ class DeferredBatchTessellator extends DirectTessellator { /** Snapshot the current modelview as the "default" for this bracket. */ void snapshotDefaultModelview() { - defaultModelview.set(GLStateManager.getModelViewMatrix()); - defaultModelview.invert(defaultModelviewInverse); + modelViewDelta.snapshot(); } @Override protected int interceptDraw(Tessellator tess) { inIntercept = true; try { - // Compute delta: if current MV differs from default, pre-transform vertices - final Matrix4f currentMV = GLStateManager.getModelViewMatrix(); - if (!currentMV.equals(defaultModelview)) { - defaultModelviewInverse.mul(currentMV, deltaMatrix); - this.currentTransform = deltaMatrix; - } else { - this.currentTransform = null; - } + this.currentTransform = modelViewDelta.deltaOrNull(deltaMatrix); final int byteOffsetBefore = bufferLimit(); final int vertCount = tess.vertexCount; diff --git a/src/main/java/com/gtnewhorizons/angelica/client/rendering/ModelViewDelta.java b/src/main/java/com/gtnewhorizons/angelica/client/rendering/ModelViewDelta.java new file mode 100644 index 000000000..e1ff9888c --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/rendering/ModelViewDelta.java @@ -0,0 +1,22 @@ +package com.gtnewhorizons.angelica.client.rendering; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +public final class ModelViewDelta { + + private final Matrix4f base = new Matrix4f(); + private final Matrix4f baseInverse = new Matrix4f(); + + public void snapshot() { + base.set(GLStateManager.getModelViewMatrix()); + base.invert(baseInverse); + } + + public Matrix4fc deltaOrNull(Matrix4f scratch) { + final Matrix4f current = GLStateManager.getModelViewMatrix(); + if (current.equals(base)) return null; + return baseInverse.mul(current, scratch); + } +} 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 135669928..15d51470e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderLayer.java @@ -14,6 +14,7 @@ import net.coderbot.batchedentityrendering.impl.BatchVertexFormats; import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; +import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.layer.PassOverride; import net.minecraft.util.ResourceLocation; @@ -69,9 +70,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return TRANSLUCENT; } - private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) { + private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) { final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder(); - b.texture(texture != null ? new RenderPhase.Texture(texture, false, false) : NO_TEXTURE); + b.texture(texture != null ? new RenderPhase.Texture(texture, false, false, material.isUnfilteredAtlas()) : NO_TEXTURE); if (material.isNoCull()) { b.cull(DISABLE_CULLING); } @@ -95,7 +96,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris } boolean shaderPhaseTaken = true; switch (material.special()) { - case GLINT -> b.shader(SPECIAL_GLINT); + case GLINT -> b.shader(glintShader(glintSlot)); case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM); case NONE -> { final TesrShader shader = material.shader(); @@ -113,19 +114,35 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris return b; } - private static final RenderPhase.Shader SPECIAL_GLINT = new RenderPhase.Shader("angelica_special_glint", - () -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT), - GbufferPrograms::teardownSpecialRenderCondition); + private static final RenderPhase.Shader[] GLINT_SHADERS = new RenderPhase.Shader[ShaderGlint.TINT_SLOTS + 1]; + + private static RenderPhase.Shader glintShader(int slot) { + RenderPhase.Shader shader = GLINT_SHADERS[slot + 1]; + if (shader == null) { + shader = new RenderPhase.Shader("angelica_special_glint_" + slot, + () -> { + GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT); + ShaderGlint.bindTintedGlint(slot); + }, + GbufferPrograms::teardownSpecialRenderCondition); + GLINT_SHADERS[slot + 1] = shader; + } + return shader; + } private static final RenderPhase.Shader SPECIAL_BEACON_BEAM = new RenderPhase.Shader("angelica_special_beacon_beam", () -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM), GbufferPrograms::teardownSpecialRenderCondition); public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) { - return tesr(texture, material, PassOverride.NONE, 0.0f, 0.0f); + return tesr(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT); } public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) { - final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material, pass, offsetFactor, offsetUnits).shadeModel(SMOOTH_SHADE_MODEL); + return tesr(texture, material, pass, offsetFactor, offsetUnits, ShaderGlint.NO_TINT); + } + + public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) { + final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material, pass, offsetFactor, offsetUnits, glintSlot).shadeModel(SMOOTH_SHADE_MODEL); final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE; return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT) + pass.nameSuffix() + (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits), @@ -135,7 +152,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) { return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT), BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false, - tesrMaterialPhases(texture, material, PassOverride.NONE, 0.0f, 0.0f).build(false)); + tesrMaterialPhases(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT).build(false)); } public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) { diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java index 37c70685c..a1f8a803a 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/RenderPhase.java @@ -5,6 +5,7 @@ import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -406,18 +407,30 @@ public abstract class RenderPhase { private final Optional id; protected boolean bilinear; protected boolean mipmap; + protected boolean unfilteredAtlas; public Texture(ResourceLocation id, boolean bilinear, boolean mipmap) { + this(id, bilinear, mipmap, false); + } + + public Texture(ResourceLocation id, boolean bilinear, boolean mipmap, boolean unfilteredAtlas) { super("texture", () -> { GLStateManager.enableTexture(); TextureManager lv = Minecraft.getMinecraft().getTextureManager(); lv.bindTexture(id); //GLStateManager.setFilter(bilinear, mipmap); // breaks textures. TODO find out why + if (unfilteredAtlas) { + TextureUtil.func_152777_a(false, false, 1.0F); + } }, () -> { + if (unfilteredAtlas) { + TextureUtil.func_147945_b(); + } }); this.id = Optional.of(id); this.bilinear = bilinear; this.mipmap = mipmap; + this.unfilteredAtlas = unfilteredAtlas; } public Texture() { @@ -425,6 +438,7 @@ public abstract class RenderPhase { this.id = Optional.empty(); this.bilinear = false; this.mipmap = false; + this.unfilteredAtlas = false; } @Override @@ -433,7 +447,7 @@ public abstract class RenderPhase { return true; } else if (object != null && this.getClass() == object.getClass()) { Texture lv = (Texture)object; - return this.id.equals(lv.id) && this.bilinear == lv.bilinear && this.mipmap == lv.mipmap; + return this.id.equals(lv.id) && this.bilinear == lv.bilinear && this.mipmap == lv.mipmap && this.unfilteredAtlas == lv.unfilteredAtlas; } else { return false; } @@ -446,7 +460,7 @@ public abstract class RenderPhase { @Override public String toString() { - return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ")]"; + return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ", unfilteredAtlas=" + this.unfilteredAtlas + ")]"; } protected Optional getId() { diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index bc533c776..0399ed0d2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -127,11 +127,16 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean enableTESRChestCache; - @Config.Comment("Batch and instance living-entity model parts on FFP-managed passes") + @Config.Comment("Batch and instance entity model parts, items, and shadows on FFP-managed passes") @Config.DefaultBoolean(true) @Config.RequiresMcRestart public static boolean enableEntityBatching; + @Config.Comment("Draw cuboid model parts from a shared unit cube (requires entity batching)") + @Config.DefaultBoolean(true) + @Config.RequiresMcRestart + public static boolean enableCubeInstancing; + @Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.") @Config.DefaultBoolean(true) @Config.RequiresMcRestart @@ -251,7 +256,7 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean optimizeInWorldItemRendering; - @Config.Comment("Upper limit for the amount of VBO's to cache for optimized item rendering. Higher number can potentially use more VRAM.") + @Config.Comment("Upper limit for the amount of cached item meshes (VBOs and batched item templates) for optimized item rendering. Higher number can potentially use more memory and VRAM.") @Config.DefaultInt(512) @Config.RangeInt(min = 256, max = 1024) public static int itemRendererCacheSize; @@ -463,6 +468,10 @@ public class AngelicaConfig { GpuCulling.setMode(gpuCullingMode == null ? GpuCullingMode.CPU_ONLY : gpuCullingMode); } + public static boolean cubeInstancingEnabled() { + return enableEntityBatching && enableCubeInstancing; + } + public static GLProfile getEffectiveGlProfile() { final String sys = SystemProperties.GL_PROFILE.trim().toUpperCase(); if ("GLES".equals(sys)) return GLProfile.ES; diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyCommandSender.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyCommandSender.java index b89a07523..6e7ede2b4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyCommandSender.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyCommandSender.java @@ -15,9 +15,11 @@ final class FlybyCommandSender implements ICommandSender { private static final String NAME = "Flyby"; private final EntityPlayerMP player; + private final ChunkCoordinates anchor; - FlybyCommandSender(EntityPlayerMP player) { + FlybyCommandSender(EntityPlayerMP player, ChunkCoordinates anchor) { this.player = player; + this.anchor = anchor; } @Override @@ -42,7 +44,7 @@ final class FlybyCommandSender implements ICommandSender { @Override public ChunkCoordinates getPlayerCoordinates() { - return this.player.getPlayerCoordinates(); + return this.anchor; } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyOrigin.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyOrigin.java new file mode 100644 index 000000000..9991731e6 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyOrigin.java @@ -0,0 +1,15 @@ +package com.gtnewhorizons.angelica.debug.flyby; + +record FlybyOrigin(double x, double z, float yaw) { + + static FlybyOrigin parse(String raw) { + if (raw == null || raw.isBlank()) return null; + final String[] parts = raw.split(",", -1); + if (parts.length != 2 && parts.length != 3) throw new IllegalArgumentException("Expected x,z[,yaw] but got '" + raw + "'"); + try { + return new FlybyOrigin(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()), parts.length == 3 ? Float.parseFloat(parts[2].trim()) : 0.0F); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Expected x,z[,yaw] but got '" + raw + "'", e); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java index f0aa4c758..26f5324db 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyRunner.java @@ -15,19 +15,23 @@ import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.MathHelper; import net.minecraft.world.MinecraftException; import net.minecraft.world.WorldServer; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunkProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.Display; import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; /** Flies a deterministic camera path */ public final class FlybyRunner { - public static final FlybyRunner INSTANCE = new FlybyRunner(); - private static final Logger LOGGER = LogManager.getLogger("Angelica/Flyby"); private static final long[] NO_FRAMES = new long[0]; private static final double[] NO_PATH = new double[0]; @@ -36,7 +40,9 @@ public final class FlybyRunner { private static final String[] NO_COMMANDS = new String[0]; private static final int MAX_RECORDED_FRAMES = 200_000; - private enum State { IDLE, WAITING, WARMUP, RUNNING, SETTLE, EXITING, DONE } + public static final FlybyRunner INSTANCE = new FlybyRunner(); + + private enum State { IDLE, WAITING, PREPARING, WARMUP, RUNNING, SETTLE, EXITING, DONE } private static final int EXIT_TICKS = 20; private static final int SETTLE_TICKS = 40; @@ -52,10 +58,9 @@ public final class FlybyRunner { private boolean waitForFocus; private boolean exitWhenDone; private boolean startedFromProperties; - private volatile boolean freezeRequested; + private final AtomicReference pendingRequest = new AtomicReference<>(); + private FlybyRequest activeRequest; private String[] sceneCommands = NO_COMMANDS; - private String scenePlayerName; - private volatile boolean sceneRequested; private volatile boolean sceneClearRequested; private int sceneSpawnTotal; private boolean pauseOnLostFocusSaved; @@ -65,8 +70,13 @@ public final class FlybyRunner { private static volatile boolean sceneGuarded; private static volatile boolean worldChangesDiscarded; - private double originX, originY, originZ; - private float originYaw, originPitch; + private double parkedX, parkedY, parkedZ; + private float parkedYaw, parkedPitch; + private double originX, originZ; + private float originYaw; + private FlybyOrigin fixedOrigin; + private float eyeOffset; + private double flightY; private double[] pathX = NO_PATH; private double[] pathZ = NO_PATH; @@ -111,8 +121,17 @@ public final class FlybyRunner { return; } + final FlybyOrigin origin; + try { + origin = FlybyOrigin.parse(SystemProperties.FLYBY_ORIGIN); + } catch (IllegalArgumentException e) { + LOGGER.error("Invalid flyby origin '{}', expected x,z[,yaw]", SystemProperties.FLYBY_ORIGIN); + return; + } + this.startedFromProperties = true; this.start(configured, SystemProperties.FLYBY_LENGTH, SystemProperties.FLYBY_WARMUP_TICKS, SystemProperties.FLYBY_SPEED); + this.fixedOrigin = origin; this.waitForTracy = SystemProperties.FLYBY_WAIT_FOR_TRACY; this.waitForFocus = SystemProperties.FLYBY_WAIT_FOR_FOCUS; this.exitWhenDone = SystemProperties.FLYBY_EXIT_WHEN_DONE; @@ -137,6 +156,7 @@ public final class FlybyRunner { this.waitForTracy = false; this.waitForFocus = false; this.exitWhenDone = false; + this.fixedOrigin = null; sceneGuarded = false; this.state = State.WAITING; } @@ -160,7 +180,7 @@ public final class FlybyRunner { } if (this.state == State.IDLE || this.state == State.DONE) return; - if (mc.theWorld == null && (this.state == State.WARMUP || this.state == State.RUNNING || this.state == State.SETTLE)) { + if (mc.theWorld == null && (this.state == State.PREPARING || this.state == State.WARMUP || this.state == State.RUNNING || this.state == State.SETTLE)) { this.cancel(); return; } @@ -182,6 +202,12 @@ public final class FlybyRunner { if (this.waitForFocus && !Display.isActive()) return; this.begin(mc, player); } + case PREPARING -> { + final Double feetY = this.activeRequest.feetY().getNow(null); + if (feetY == null) return; + this.flightY = feetY + this.eyeOffset; + this.startRun(mc); + } case WARMUP -> { this.applyPosition(player, 0); if (++this.tick >= this.warmupTicks) { @@ -231,25 +257,49 @@ public final class FlybyRunner { mc.gameSettings.pauseOnLostFocus = false; } - this.originX = player.posX; - this.originY = player.posY; - this.originZ = player.posZ; - this.originPitch = player.rotationPitch; + this.parkedX = player.posX; + this.parkedY = player.posY; + this.parkedZ = player.posZ; + this.parkedYaw = player.rotationYaw; + this.parkedPitch = player.rotationPitch; + this.eyeOffset = player.yOffset; - this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F; - if (this.originYaw != player.rotationYaw) { - LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw); + final boolean creative = player.capabilities.isCreativeMode; + if (!creative) { + LOGGER.warn("Flyby: player is not in creative mode, flying at the player height{}", this.fixedOrigin != null ? " and ignoring the pinned origin" : ""); + } + + if (creative && this.fixedOrigin != null) { + this.originX = this.fixedOrigin.x(); + this.originZ = this.fixedOrigin.z(); + this.originYaw = this.fixedOrigin.yaw(); + } else { + this.originX = player.posX; + this.originZ = player.posZ; + this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F; + if (this.originYaw != player.rotationYaw) { + LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw); + } } this.buildPath(); - this.freezeTimeAndWeather(mc); - if (this.sceneCommands.length > 0 && mc.getIntegratedServer() != null) { - this.scenePlayerName = player.getCommandSenderName(); - this.sceneRequested = true; - } - this.suppressPacing(); + this.tick = 0; + if (mc.getIntegratedServer() != null) { + final FlybyRequest request = new FlybyRequest(this.pathX, this.pathZ, this.originX, this.originZ, player.posY - this.eyeOffset, player.getCommandSenderName(), creative, this.sceneCommands.length > 0, new CompletableFuture<>()); + this.activeRequest = request; + sceneGuarded = true; + this.pendingRequest.set(request); + this.state = State.PREPARING; + } else { + LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather or sample terrain - flying at the player height, results may not be comparable"); + this.flightY = player.posY; + this.startRun(mc); + } + } + + private void startRun(Minecraft mc) { this.tick = 0; if (this.warmupTicks > 0) { this.state = State.WARMUP; @@ -258,8 +308,7 @@ public final class FlybyRunner { this.beginMeasuring(mc); } - LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(), - this.originX, this.originY, this.originZ, this.originYaw); + LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(), this.originX, this.flightY, this.originZ, this.originYaw); } private void suppressPacing() { @@ -393,12 +442,12 @@ public final class FlybyRunner { player.ySize = 0.0F; player.prevPosX = player.lastTickPosX = this.pathX[last]; - player.prevPosY = player.lastTickPosY = this.originY; + player.prevPosY = player.lastTickPosY = this.flightY; player.prevPosZ = player.lastTickPosZ = this.pathZ[last]; player.prevRotationYaw = player.rotationYaw = this.pathYaw[last]; player.prevRotationYawHead = player.rotationYawHead = this.pathYaw[last]; - player.prevRotationPitch = player.rotationPitch = this.originPitch; - player.setPosition(this.pathX[last], this.originY, this.pathZ[last]); + player.prevRotationPitch = player.rotationPitch = this.parkedPitch; + player.setPosition(this.pathX[last], this.flightY, this.pathZ[last]); } private void applyPosition(EntityClientPlayerMP player, int index) { @@ -418,37 +467,23 @@ public final class FlybyRunner { player.ySize = 0.0F; player.prevPosX = player.lastTickPosX = prevX; - player.prevPosY = player.lastTickPosY = this.originY; + player.prevPosY = player.lastTickPosY = this.flightY; player.prevPosZ = player.lastTickPosZ = prevZ; player.prevRotationYaw = prevYaw; player.rotationYaw = yaw; player.prevRotationYawHead = prevYaw; player.rotationYawHead = yaw; - player.prevRotationPitch = player.rotationPitch = this.originPitch; + player.prevRotationPitch = player.rotationPitch = this.parkedPitch; - player.setPosition(x, this.originY, z); - } - - /** Requests the freeze; the write happens on the server thread in {@link #onServerTick}. */ - private void freezeTimeAndWeather(Minecraft mc) { - final MinecraftServer server = mc.getIntegratedServer(); - if (server == null) { - LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather - results may not be comparable"); - return; - } - - sceneGuarded = true; - this.freezeRequested = true; + player.setPosition(x, this.flightY, z); } @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase != TickEvent.Phase.END) return; final boolean clear = this.sceneClearRequested; - final boolean freeze = this.freezeRequested; - final boolean scene = this.sceneRequested; - if (!clear && !freeze && !scene) return; + if (!clear && this.pendingRequest.get() == null) return; final MinecraftServer server = MinecraftServer.getServer(); if (server == null) return; @@ -457,16 +492,16 @@ public final class FlybyRunner { this.sceneClearRequested = false; this.clearScene(server); } - if (freeze || scene) { - this.discardWorldChanges(server); - } - if (freeze) { - this.freezeRequested = false; - this.applyFreeze(server); - } - if (scene) { - this.sceneRequested = false; - this.runScene(server); + + final FlybyRequest request = this.pendingRequest.getAndSet(null); + if (request == null) return; + + this.discardWorldChanges(server); + final double feetY = this.flightFeetY(server, request); + request.feetY().complete(feetY); + this.applyFreeze(server); + if (request.scene()) { + this.runScene(server, request, feetY); } } @@ -511,16 +546,52 @@ public final class FlybyRunner { } } - private void runScene(MinecraftServer server) { - final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(this.scenePlayerName); + private double flightFeetY(MinecraftServer server, FlybyRequest request) { + if (!request.sampleTerrain()) return request.parkedFeetY(); + + final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(request.playerName()); if (player == null) { - LOGGER.warn("Flyby scene: no server player named '{}', skipping scene", this.scenePlayerName); + LOGGER.warn("Flyby terrain: no server player named '{}', flying at the parked feet Y {}", request.playerName(), request.parkedFeetY()); + return request.parkedFeetY(); + } + + final WorldServer world = player.getServerForPlayer(); + if (world.provider.hasNoSky) { + LOGGER.info("Flyby terrain: dimension has a ceiling, flying at the parked feet Y {}", request.parkedFeetY()); + return request.parkedFeetY(); + } + + final IChunkProvider chunks = world.getChunkProvider(); + final int floor = FlybyTerrain.routeFloor(request.pathX(), request.pathZ(), FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> precipitationHeight(chunks, x, z)); + if (floor < 1) { + LOGGER.info("Flyby terrain: no ground within {} blocks of the path, flying at the parked feet Y {}", FlybyTerrain.CORRIDOR_RADIUS, request.parkedFeetY()); + return request.parkedFeetY(); + } + + final double feetY = floor + FlybyTerrain.HOVER_BLOCKS; + LOGGER.info("Flyby terrain: route floor {} within {} blocks of the path, flight feet Y {}", floor, FlybyTerrain.CORRIDOR_RADIUS, feetY); + if (Tracy.ENABLED) Tracy.message("flyby terrain floor=" + floor + " radius=" + FlybyTerrain.CORRIDOR_RADIUS + " feetY=" + feetY); + return feetY; + } + + private static int precipitationHeight(IChunkProvider chunks, int x, int z) { + final int chunkX = x >> 4; + final int chunkZ = z >> 4; + Chunk chunk = chunks.loadChunk(chunkX, chunkZ); + if (chunk == null) chunk = chunks.provideChunk(chunkX, chunkZ); + return chunk == null ? Integer.MIN_VALUE : chunk.getPrecipitationHeight(x & 15, z & 15); + } + + private void runScene(MinecraftServer server, FlybyRequest request, double feetY) { + final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(request.playerName()); + if (player == null) { + LOGGER.warn("Flyby scene: no server player named '{}', skipping scene", request.playerName()); return; } this.clearScene(server); - final FlybyCommandSender sender = new FlybyCommandSender(player); + final FlybyCommandSender sender = new FlybyCommandSender(player, new ChunkCoordinates(MathHelper.floor_double(request.originX()), MathHelper.floor_double(feetY + 0.5D), MathHelper.floor_double(request.originZ()))); for (String line : this.sceneCommands) { if (server.getCommandManager().executeCommand(sender, line) == 0) { LOGGER.warn("flyby scene command did not execute: {}", line); @@ -603,11 +674,11 @@ public final class FlybyRunner { player.motionY = 0.0D; player.motionZ = 0.0D; player.ySize = 0.0F; - player.setPositionAndRotation(this.originX, this.originY, this.originZ, this.originYaw, this.originPitch); - player.lastTickPosX = this.originX; - player.lastTickPosY = this.originY; - player.lastTickPosZ = this.originZ; - LOGGER.info("Flyby returned to origin {} {} {}", this.originX, this.originY, this.originZ); + player.setPositionAndRotation(this.parkedX, this.parkedY, this.parkedZ, this.parkedYaw, this.parkedPitch); + player.lastTickPosX = this.parkedX; + player.lastTickPosY = this.parkedY; + player.lastTickPosZ = this.parkedZ; + LOGGER.info("Flyby returned to {} {} {}", this.parkedX, this.parkedY, this.parkedZ); } private String summarise(long elapsedNs, EntityClientPlayerMP player) { @@ -656,8 +727,8 @@ public final class FlybyRunner { FramePacer.endStats(); final Minecraft mc = Minecraft.getMinecraft(); this.restorePauseOnLostFocus(mc); - this.freezeRequested = false; - this.sceneRequested = false; + this.pendingRequest.set(null); + this.activeRequest = null; sceneGuarded = false; this.sceneClearRequested = this.sceneCommands.length > 0; this.restorePacing(mc); @@ -667,4 +738,6 @@ public final class FlybyRunner { public boolean startedFromProperties() { return this.startedFromProperties; } + + private record FlybyRequest(double[] pathX, double[] pathZ, double originX, double originZ, double parkedFeetY, String playerName, boolean sampleTerrain, boolean scene, CompletableFuture feetY) {} } diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrain.java b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrain.java new file mode 100644 index 000000000..8f6c0d954 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrain.java @@ -0,0 +1,30 @@ +package com.gtnewhorizons.angelica.debug.flyby; + +import java.util.function.IntBinaryOperator; + +final class FlybyTerrain { + + static final int CORRIDOR_RADIUS = 2; + static final int HOVER_BLOCKS = 2; + + private FlybyTerrain() {} + + static int routeFloor(double[] pathX, double[] pathZ, int radius, IntBinaryOperator heights) { + int floor = Integer.MIN_VALUE; + int prevCellX = 0; + int prevCellZ = 0; + for (int i = 0; i < pathX.length; i++) { + final int cellX = (int) Math.floor(pathX[i]); + final int cellZ = (int) Math.floor(pathZ[i]); + if (i > 0 && cellX == prevCellX && cellZ == prevCellZ) continue; + prevCellX = cellX; + prevCellZ = cellZ; + for (int x = cellX - radius; x <= cellX + radius; x++) { + for (int z = cellZ - radius; z <= cellZ + radius; z++) { + floor = Math.max(floor, heights.applyAsInt(x, z)); + } + } + } + return floor; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/helpers/RendererLivingEntityHelper.java b/src/main/java/com/gtnewhorizons/angelica/helpers/RendererLivingEntityHelper.java index e5036da0f..981d99972 100644 --- a/src/main/java/com/gtnewhorizons/angelica/helpers/RendererLivingEntityHelper.java +++ b/src/main/java/com/gtnewhorizons/angelica/helpers/RendererLivingEntityHelper.java @@ -2,6 +2,9 @@ package com.gtnewhorizons.angelica.helpers; import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR; +import net.minecraft.client.renderer.entity.RenderDragon; +import net.minecraft.client.renderer.entity.RenderEnderman; +import net.minecraft.client.renderer.entity.RenderSpider; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -11,6 +14,10 @@ public final class RendererLivingEntityHelper { private RendererLivingEntityHelper() {} + public static boolean hasEyePass(Object renderer) { + return renderer instanceof RenderSpider || renderer instanceof RenderEnderman || renderer instanceof RenderDragon; + } + public static String getUpsideDownName(EntityLivingBase entity) { if (entity instanceof EntityLiving living) { return living.hasCustomNameTag() ? entity.getCommandSenderName() : ""; diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/ImmediateExtendedAttribs.java b/src/main/java/com/gtnewhorizons/angelica/iris/ImmediateExtendedAttribs.java index a15376f10..a5f26ee1e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/ImmediateExtendedAttribs.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/ImmediateExtendedAttribs.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.iris; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; import com.gtnewhorizons.angelica.rendering.items.ItemRenderListManager; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; @@ -81,6 +82,7 @@ public final class ImmediateExtendedAttribs implements ImmediateExtendedAttribHa @Override public boolean wantsExtended() { + GLSMHooks.resolvePendingProgram(); return Iris.enabled && currentProgramWants != 0 && GLStateManager.getActiveProgram() != 0; } diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java index 79baf95b3..022fd9783 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java @@ -42,10 +42,6 @@ public class IrisGLSMBridge { private static Runnable fogDensityListener = null; private static Runnable colorModulatorListener = null; - private static boolean inputsDeferred = false; - - private static boolean blendDeferred = false; - private static boolean programRestoreDeferred = false; private static final Int2IntOpenHashMap programLastUpdatedFrame = new Int2IntOpenHashMap(); @@ -269,32 +265,19 @@ public class IrisGLSMBridge { } if (!updatePipeline) return; - if (GLStateManager.isForeignDraw()) { - inputsDeferred = true; - return; + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + if (pipeline != null) { + pipeline.setInputs(StateTracker.INSTANCE.getInputs()); } - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs())); }); GLSMHooks.VANILLA_BLEND_CHANGE.addListener(event -> { if (!Iris.enabled) return; - if (GLStateManager.isForeignDraw()) { - blendDeferred = true; - return; - } refreshBlendCondition(); }); GLSMHooks.FOREIGN_DRAW_END.addListener(event -> { if (!Iris.enabled) return; - if (inputsDeferred) { - inputsDeferred = false; - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs())); - } - if (blendDeferred) { - blendDeferred = false; - refreshBlendCondition(); - } if (programRestoreDeferred) { programRestoreDeferred = false; final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 3bd8a4446..3006f52b9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -64,6 +64,7 @@ public enum Mixins implements IMixins { , "angelica.ffp.MixinTessellator_CoreProfile" , "angelica.glsm.MixinSplashProgressCaching" , "angelica.gui.MixinGuiOptions" + , "angelica.optimizations.MixinRenderBiped_ArmorResource" , "angelica.optimizations.MixinRendererLivingEntity" , "angelica.rendering.MixinRenderGlobal_SelectionBox" , "angelica.gui.MixinGuiIngameForge_ModernF3" @@ -170,15 +171,29 @@ public enum Mixins implements IMixins { .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.enableEntityBatching) .addClientMixins( + "angelica.entity.MixinItemRenderer_Instanced", "angelica.entity.MixinModelRenderer", "angelica.entity.MixinRenderGlobal_EntityBatch", + "angelica.entity.MixinRenderItem_Instanced", "angelica.entity.MixinRenderManager_BatchEligibility", + "angelica.entity.MixinRendererLivingEntity_EquippedDraws", + "angelica.entity.MixinRendererLivingEntity_GlintClock", + "angelica.entity.MixinRendererLivingEntity_ModelPassDraws", "angelica.entity.MixinRender_BatchEligibility", + "angelica.entity.MixinRender_ShadowBatch", "angelica.entity.MixinTextureManager", "angelica.tesr.MixinTileEntitySpecialRenderer_BatchEligibility" ) ), + ANGELICA_CUBE_INSTANCING(new MixinBuilder("Capture cuboid parameters so model cubes can be drawn from a shared unit cube") + .setPhase(Phase.EARLY) + .setApplyIf(AngelicaConfig::cubeInstancingEnabled) + .addClientMixins( + "angelica.entity.MixinModelBox_CubeParams" + ) + ), + ANGELICA_SKIP_END_FRAME_FLUSH(new MixinBuilder("Skip the end-of-frame glFlush before the buffer swap") .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.skipEndOfFrameFlush) @@ -298,9 +313,9 @@ public enum Mixins implements IMixins { .setPhase(Phase.EARLY) .addClientMixins("angelica.optimizations.MixinGLAllocation")), - ANGELICA_DEFERRED_TESSELLATOR_BATCH(new MixinBuilder("Deferred tessellator batching for particles to reduce draw calls") + ANGELICA_PARTICLE_BATCH(new MixinBuilder("Particle instancing, with deferred tessellator batching as the fallback") .setPhase(Phase.EARLY) - .addClientMixins("angelica.particles.MixinEffectRenderer_DeferredBatch")), + .addClientMixins("angelica.particles.MixinEffectRenderer_ParticleBatch")), // Not compatible with the lwjgl debug callbacks, so disable if that's enabled ARCHAIC_SPLASH(new MixinBuilder() @@ -785,6 +800,11 @@ public enum Mixins implements IMixins { .setApplyIf(() -> AngelicaConfig.enableIris) .addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer") ), + DRAGONAPI_PARTICLE_BATCH(new MixinBuilder("Particle instancing for DragonAPI's replacement particle renderer") + .setPhase(Phase.LATE) + .addRequiredMod(TargetedMod.DRAGON_API) + .addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer_ParticleBatch") + ), MCPATCHER_FORGE(new MixinBuilder() .setPhase(Phase.EARLY) .setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures) diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ModelBoxData.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ModelBoxData.java new file mode 100644 index 000000000..886436e91 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ModelBoxData.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.mixins.interfaces; + +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; + +public interface ModelBoxData { + + CubeParams angelica$cubeParams(); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java b/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java index e9557af02..7fdd7764f 100644 --- a/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/BailClassCounts.java @@ -10,6 +10,7 @@ import net.minecraft.client.Minecraft; public final class BailClassCounts { public static final BailClassCounts MATERIAL = new BailClassCounts("tesr.bailCls.mat.", "BailMat"); public static final BailClassCounts TEMPLATE = new BailClassCounts("tesr.bailCls.tmpl.", "BailTmpl"); + public static final BailClassCounts PARTICLE_SPILL = new BailClassCounts("particles.spillCls.", "PartSpill"); private final String plotPrefix; private final String label; diff --git a/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java b/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java index 94120a624..d86e4ef83 100644 --- a/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java +++ b/src/main/java/com/gtnewhorizons/angelica/profiling/TracyFramePlots.java @@ -14,6 +14,8 @@ import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; import com.gtnewhorizons.angelica.rendering.celeritas.TerrainDrawStats; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink; +import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer; +import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer; import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; @@ -24,31 +26,21 @@ import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; public final class TracyFramePlots { - private static long lastChunkUpdates; - private static long lastDrawCalls, lastTexBindMisses, lastProgramSwitches, lastListPlaybacks; - private static long lastStreamedBytes, lastStreamDraws, lastOrphanFallbacks, lastStreamContiguous; - private static long lastRingWraps, lastVariantSwitches; - private static long lastTesrRebuilds, lastTesrRetainedDraws, lastTesrInstDraws, lastTesrInstInstances; - private static long lastTesrStreamedInstances, lastTesrPromotions, lastTesrCacheHits, lastTesrCacheMisses; - private static long lastBatcherParts, lastBatcherLiveFallbacks; - private static final long[] lastBails = new long[ModelPartBatcher.BailReason.VALUES.length]; - private static long lastSectionsUploaded, lastBytesUploaded, lastIndexBufferGrowths; - private static final long P_ALLOC_RATE = Tracy.plotHandle("allocRate", TracyBackend.PLOT_FORMAT_MEMORY); private static final long P_HEAP_USED = Tracy.plotHandle("heapUsed", TracyBackend.PLOT_FORMAT_MEMORY); - private static final long P_CHUNK_UPDATES = Tracy.plotHandle("chunkUpdates"); + private static final PlotDelta P_CHUNK_UPDATES = new PlotDelta("chunkUpdates"); private static final long P_ENTITIES_RENDERED = Tracy.plotHandle("entitiesRendered"); private static final long P_ENTITIES_TOTAL = Tracy.plotHandle("entitiesTotal"); - private static final long P_GL_DRAW_CALLS = Tracy.plotHandle("gl.drawCalls"); - private static final long P_GL_TEX_BIND_MISSES = Tracy.plotHandle("gl.texBindMisses"); - private static final long P_GL_PROGRAM_SWITCHES = Tracy.plotHandle("gl.programSwitches"); - private static final long P_GL_LIST_PLAYBACKS = Tracy.plotHandle("gl.listPlaybacks"); - private static final long P_GL_STREAMED_BYTES = Tracy.plotHandle("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY); - private static final long P_GL_STREAM_DRAWS = Tracy.plotHandle("gl.streamDraws"); - private static final long P_GL_ORPHAN_FALLBACKS = Tracy.plotHandle("gl.orphanFallbacks"); - private static final long P_GL_STREAM_CONTIGUOUS = Tracy.plotHandle("gl.streamContiguous"); - private static final long P_GL_RING_WRAPS = Tracy.plotHandle("gl.ringWraps"); + private static final PlotDelta P_GL_DRAW_CALLS = new PlotDelta("gl.drawCalls"); + private static final PlotDelta P_GL_TEX_BIND_MISSES = new PlotDelta("gl.texBindMisses"); + private static final PlotDelta P_GL_PROGRAM_SWITCHES = new PlotDelta("gl.programSwitches"); + private static final PlotDelta P_GL_LIST_PLAYBACKS = new PlotDelta("gl.listPlaybacks"); + private static final PlotDelta P_GL_STREAMED_BYTES = new PlotDelta("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final PlotDelta P_GL_STREAM_DRAWS = new PlotDelta("gl.streamDraws"); + private static final PlotDelta P_GL_ORPHAN_FALLBACKS = new PlotDelta("gl.orphanFallbacks"); + private static final PlotDelta P_GL_STREAM_CONTIGUOUS = new PlotDelta("gl.streamContiguous"); + private static final PlotDelta P_GL_RING_WRAPS = new PlotDelta("gl.ringWraps"); private static final long P_GL_SECTION_META_BYTES = Tracy.plotHandle("gl.sectionMetaBytes", TracyBackend.PLOT_FORMAT_MEMORY); private static final long P_SHADOW_RELAY_FRAMES = Tracy.plotHandle("shadow.relayFrames"); @@ -59,7 +51,7 @@ public final class TracyFramePlots { private static final long P_VOX_DISPATCHES = Tracy.plotHandle("voxelization.dispatches"); private static final long P_VOX_REGIONS = Tracy.plotHandle("voxelization.regions"); private static final long P_DRAW_BATCH_REBUILDS = Tracy.plotHandle("draw.batchRebuilds"); - private static final long P_DRAW_INDEX_BUFFER_GROWTHS = Tracy.plotHandle("draw.indexBufferGrowths"); + private static final PlotDelta P_DRAW_INDEX_BUFFER_GROWTHS = new PlotDelta("draw.indexBufferGrowths"); private static final long P_CULL_COMMANDS_SUBMITTED = Tracy.plotHandle("cull.commandsSubmitted"); private static final long P_CULL_REGIONS_DRAWN = Tracy.plotHandle("cull.regionsDrawn"); @@ -79,24 +71,37 @@ public final class TracyFramePlots { private static final long P_FFP_STAGED_CLIP_PLANES = Tracy.plotHandle("ffp.stagedClipPlanes"); private static final long P_FFP_STAGED_MISC = Tracy.plotHandle("ffp.stagedMisc"); private static final long P_FFP_PROGRAMS = Tracy.plotHandle("ffp.programs"); - private static final long P_FFP_VARIANT_SWITCHES = Tracy.plotHandle("ffp.variantSwitches"); + private static final PlotDelta P_FFP_VARIANT_SWITCHES = new PlotDelta("ffp.variantSwitches"); - private static final long P_TESR_REBUILDS = Tracy.plotHandle("tesr.rebuilds"); - private static final long P_TESR_RETAINED_DRAWS = Tracy.plotHandle("tesr.retainedDraws"); - private static final long P_TESR_INSTANCED_DRAWS = Tracy.plotHandle("tesr.instancedDraws"); - private static final long P_TESR_INSTANCED_INSTANCES = Tracy.plotHandle("tesr.instancedInstances"); - private static final long P_TESR_STREAMED_INSTANCES = Tracy.plotHandle("tesr.streamedInstances"); - private static final long P_TESR_VOLATILE_PROMOTIONS = Tracy.plotHandle("tesr.volatilePromotions"); + private static final PlotDelta P_TESR_REBUILDS = new PlotDelta("tesr.rebuilds"); + private static final PlotDelta P_TESR_RETAINED_DRAWS = new PlotDelta("tesr.retainedDraws"); + private static final PlotDelta P_TESR_INSTANCED_DRAWS = new PlotDelta("tesr.instancedDraws"); + private static final PlotDelta P_TESR_INSTANCED_INSTANCES = new PlotDelta("tesr.instancedInstances"); + private static final PlotDelta P_TESR_CUBE_INSTANCES = new PlotDelta("tesr.cubeInstances"); + private static final PlotDelta P_TESR_TEXMAT_RUNS = new PlotDelta("tesr.texMatrixRuns"); + private static final PlotDelta P_TESR_STREAMED_INSTANCES = new PlotDelta("tesr.streamedInstances"); + private static final PlotDelta P_TESR_VOLATILE_PROMOTIONS = new PlotDelta("tesr.volatilePromotions"); private static final long P_TESR_RETAINED_BYTES = Tracy.plotHandle("tesr.retainedBytes", TracyBackend.PLOT_FORMAT_MEMORY); private static final long P_TESR_BUFFER_SOURCE_BYTES = Tracy.plotHandle("tesr.bufferSourceBytes", TracyBackend.PLOT_FORMAT_MEMORY); - private static final long P_TESR_CACHE_HITS = Tracy.plotHandle("tesr.cacheHits"); - private static final long P_TESR_CACHE_MISSES = Tracy.plotHandle("tesr.cacheMisses"); - private static final long P_TESR_MODEL_PARTS = Tracy.plotHandle("tesr.modelParts"); - private static final long P_TESR_LIVE_FALLBACKS = Tracy.plotHandle("tesr.liveFallbacks"); - private static final long[] P_TESR_BAILS = bailHandles(); + private static final PlotDelta P_TESR_CACHE_HITS = new PlotDelta("tesr.cacheHits"); + private static final PlotDelta P_TESR_CACHE_MISSES = new PlotDelta("tesr.cacheMisses"); + private static final PlotDelta P_TESR_MODEL_PARTS = new PlotDelta("tesr.modelParts"); + private static final PlotDelta P_TESR_LIVE_FALLBACKS = new PlotDelta("tesr.liveFallbacks"); + private static final PlotDelta P_ITEMS_INSTANCED = new PlotDelta("items.instanced"); + private static final PlotDelta P_ITEMS_FALLBACK = new PlotDelta("items.fallback"); + private static final PlotDelta P_ITEMS_GLINT_INSTANCED = new PlotDelta("items.glintInstanced"); + private static final PlotDelta P_PARTICLES_DIRECT = new PlotDelta("particles.direct"); + private static final PlotDelta P_PARTICLES_CAPTURED = new PlotDelta("particles.captured"); + private static final PlotDelta P_PARTICLES_SPILLED = new PlotDelta("particles.spilled"); + private static final PlotDelta P_PARTICLES_UNDECODABLE = new PlotDelta("particles.undecodable"); + private static final PlotDelta P_PARTICLES_DRAWS = new PlotDelta("particles.draws"); + private static final PlotDelta[] TESR_BAILS = bailHandles(); + private static final PlotDelta[] ITEM_BAILS = itemBailHandles(); + private static final PlotDelta P_ENTITY_SHADOW_QUADS = new PlotDelta("entity.shadowQuads"); + private static final PlotDelta P_ENTITY_SHADOW_DRAWS = new PlotDelta("entity.shadowDraws"); - private static final long P_MESH_UPLOADED_SECTIONS = Tracy.plotHandle("mesh.uploadedSections"); - private static final long P_MESH_UPLOADED_BYTES = Tracy.plotHandle("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY); + private static final PlotDelta P_MESH_UPLOADED_SECTIONS = new PlotDelta("mesh.uploadedSections"); + private static final PlotDelta P_MESH_UPLOADED_BYTES = new PlotDelta("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY); private static final long P_MESH_META_SLOTS = Tracy.plotHandle("mesh.metaSlots"); private static final long P_MT_QUEUE_DEPTH = Tracy.plotHandle("mtQueue.depth"); private static final long P_MT_QUEUE_TASKS = Tracy.plotHandle("mtQueue.tasksRan"); @@ -110,10 +115,17 @@ public final class TracyFramePlots { private static final long P_DYN_UPDATES = Tracy.plotHandle("dyn.updates"); private static final long P_DYN_PENDING_REBUILDS = Tracy.plotHandle("dyn.pendingRebuilds"); - private static long[] bailHandles() { + private static PlotDelta[] bailHandles() { final ModelPartBatcher.BailReason[] reasons = ModelPartBatcher.BailReason.VALUES; - final long[] out = new long[reasons.length]; - for (int i = 0; i < reasons.length; i++) out[i] = Tracy.plotHandle(reasons[i].plotName); + final PlotDelta[] out = new PlotDelta[reasons.length]; + for (int i = 0; i < reasons.length; i++) out[i] = new PlotDelta(reasons[i].plotName); + return out; + } + + private static PlotDelta[] itemBailHandles() { + final DroppedItemInstancer.BailReason[] reasons = DroppedItemInstancer.BailReason.VALUES; + final PlotDelta[] out = new PlotDelta[reasons.length]; + for (int i = 0; i < reasons.length; i++) out[i] = new PlotDelta(reasons[i].plotName); return out; } @@ -153,9 +165,7 @@ public final class TracyFramePlots { Tracy.plotInt(P_PACER_LOCKED, FramePacer.locked() ? 1 : 0); Tracy.plotInt(P_PACER_PROBING, FramePacer.probing() ? 1 : 0); - final int chunksUpdated = WorldRenderer.chunksUpdated; - Tracy.plotInt(P_CHUNK_UPDATES, chunksUpdated - lastChunkUpdates); - lastChunkUpdates = chunksUpdated; + P_CHUNK_UPDATES.plot(WorldRenderer.chunksUpdated); if (mc.renderGlobal != null) { Tracy.plotInt(P_ENTITIES_RENDERED, mc.renderGlobal.countEntitiesRendered); } @@ -163,15 +173,15 @@ public final class TracyFramePlots { Tracy.plotInt(P_ENTITIES_TOTAL, mc.theWorld.loadedEntityList.size()); } - lastDrawCalls = delta(P_GL_DRAW_CALLS, GLStateManager.drawCalls, lastDrawCalls); - lastTexBindMisses = delta(P_GL_TEX_BIND_MISSES, GLStateManager.texBindMisses, lastTexBindMisses); - lastProgramSwitches = delta(P_GL_PROGRAM_SWITCHES, GLStateManager.programSwitches, lastProgramSwitches); - lastListPlaybacks = delta(P_GL_LIST_PLAYBACKS, DisplayListManager.listPlaybacks, lastListPlaybacks); - lastStreamedBytes = delta(P_GL_STREAMED_BYTES, TessellatorStreamingDrawer.streamedBytes, lastStreamedBytes); - lastStreamDraws = delta(P_GL_STREAM_DRAWS, TessellatorStreamingDrawer.streamDraws, lastStreamDraws); - lastOrphanFallbacks = delta(P_GL_ORPHAN_FALLBACKS, TessellatorStreamingDrawer.orphanFallbacks, lastOrphanFallbacks); - lastStreamContiguous = delta(P_GL_STREAM_CONTIGUOUS, TessellatorStreamingDrawer.streamContiguous, lastStreamContiguous); - lastRingWraps = delta(P_GL_RING_WRAPS, TessellatorStreamingDrawer.ringWraps(), lastRingWraps); + P_GL_DRAW_CALLS.plot(GLStateManager.drawCalls); + P_GL_TEX_BIND_MISSES.plot(GLStateManager.texBindMisses); + P_GL_PROGRAM_SWITCHES.plot(GLStateManager.programSwitches); + P_GL_LIST_PLAYBACKS.plot(DisplayListManager.listPlaybacks); + P_GL_STREAMED_BYTES.plot(TessellatorStreamingDrawer.streamedBytes); + P_GL_STREAM_DRAWS.plot(TessellatorStreamingDrawer.streamDraws); + P_GL_ORPHAN_FALLBACKS.plot(TessellatorStreamingDrawer.orphanFallbacks); + P_GL_STREAM_CONTIGUOUS.plot(TessellatorStreamingDrawer.streamContiguous); + P_GL_RING_WRAPS.plot(TessellatorStreamingDrawer.ringWraps()); Tracy.plotInt(P_GL_SECTION_META_BYTES, TerrainDrawStats.takeSectionMetaBytes()); Tracy.plotInt(P_SHADOW_RELAY_FRAMES, ShadowRenderer.SHADOW_TERRAIN_RELAID ? 1 : 0); Tracy.plotInt(P_TERRAIN_DRAW_COMMANDS, TerrainDrawStats.takeCommandsSubmitted()); @@ -199,33 +209,47 @@ public final class TracyFramePlots { Tracy.plotInt(P_FFP_STAGED_CLIP_PLANES, ffp.statLastFrameStagedClipPlanes()); Tracy.plotInt(P_FFP_STAGED_MISC, ffp.statLastFrameStagedMisc()); Tracy.plotInt(P_FFP_PROGRAMS, ffp.statProgramCount()); - lastVariantSwitches = delta(P_FFP_VARIANT_SWITCHES, ShaderManager.variantSwitches, lastVariantSwitches); + P_FFP_VARIANT_SWITCHES.plot(ShaderManager.variantSwitches); final TesrBatchRenderer tesr = TesrBatchRenderer.INSTANCE; final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE; - lastTesrRebuilds = delta(P_TESR_REBUILDS, tesr.statRebuilds(), lastTesrRebuilds); - lastTesrRetainedDraws = delta(P_TESR_RETAINED_DRAWS, tesr.statRetainedDraws(), lastTesrRetainedDraws); - lastTesrInstDraws = delta(P_TESR_INSTANCED_DRAWS, tesr.statInstancedDraws(), lastTesrInstDraws); - lastTesrInstInstances = delta(P_TESR_INSTANCED_INSTANCES, tesr.statInstancedInstances(), lastTesrInstInstances); - lastTesrStreamedInstances = delta(P_TESR_STREAMED_INSTANCES, tesr.statStreamedInstances(), lastTesrStreamedInstances); - lastTesrPromotions = delta(P_TESR_VOLATILE_PROMOTIONS, tesr.statVolatilePromotions(), lastTesrPromotions); + P_TESR_REBUILDS.plot(tesr.statRebuilds()); + P_TESR_RETAINED_DRAWS.plot(tesr.statRetainedDraws()); + P_TESR_INSTANCED_DRAWS.plot(tesr.statInstancedDraws() + batcher.statInstancedDraws()); + P_TESR_INSTANCED_INSTANCES.plot(tesr.statInstancedInstances() + batcher.statInstancedInstances()); + P_TESR_CUBE_INSTANCES.plot(batcher.statCubeInstances()); + P_TESR_TEXMAT_RUNS.plot(batcher.statTexMatrixRuns()); + P_TESR_STREAMED_INSTANCES.plot(tesr.statStreamedInstances()); + P_TESR_VOLATILE_PROMOTIONS.plot(tesr.statVolatilePromotions()); if (plots) { Tracy.plotInt(P_TESR_RETAINED_BYTES, tesr.statRetainedBytes()); Tracy.plotInt(P_TESR_BUFFER_SOURCE_BYTES, tesr.statBufferSourceBytes()); } - lastTesrCacheHits = delta(P_TESR_CACHE_HITS, AngelicaTesrMeshCache.cacheHits, lastTesrCacheHits); - lastTesrCacheMisses = delta(P_TESR_CACHE_MISSES, AngelicaTesrMeshCache.cacheMisses, lastTesrCacheMisses); - lastBatcherParts = delta(P_TESR_MODEL_PARTS, batcher.statParts(), lastBatcherParts); - lastBatcherLiveFallbacks = delta(P_TESR_LIVE_FALLBACKS, batcher.statLiveFallbacks(), lastBatcherLiveFallbacks); + P_TESR_CACHE_HITS.plot(AngelicaTesrMeshCache.cacheHits); + P_TESR_CACHE_MISSES.plot(AngelicaTesrMeshCache.cacheMisses); + P_TESR_MODEL_PARTS.plot(batcher.statParts()); + P_TESR_LIVE_FALLBACKS.plot(batcher.statLiveFallbacks()); + P_ITEMS_INSTANCED.plot(DroppedItemInstancer.statInstanced()); + P_ITEMS_FALLBACK.plot(DroppedItemInstancer.statFallback()); + P_ITEMS_GLINT_INSTANCED.plot(DroppedItemInstancer.statGlintInstanced()); + for (final DroppedItemInstancer.BailReason reason : DroppedItemInstancer.BailReason.VALUES) { + ITEM_BAILS[reason.ordinal()].plot(DroppedItemInstancer.statBail(reason)); + } + P_PARTICLES_DIRECT.plot(ParticleInstancer.getDirect()); + P_PARTICLES_CAPTURED.plot(ParticleInstancer.getCaptured()); + P_PARTICLES_SPILLED.plot(ParticleInstancer.getSpilled()); + P_PARTICLES_UNDECODABLE.plot(ParticleInstancer.getUndecodable()); + P_PARTICLES_DRAWS.plot(ParticleInstancer.getDraws()); + P_ENTITY_SHADOW_QUADS.plot(batcher.statShadowQuads()); + P_ENTITY_SHADOW_DRAWS.plot(batcher.statShadowDraws()); for (final ModelPartBatcher.BailReason reason : ModelPartBatcher.BailReason.VALUES) { - final int i = reason.ordinal(); - lastBails[i] = delta(P_TESR_BAILS[i], batcher.statBail(reason), lastBails[i]); + TESR_BAILS[reason.ordinal()].plot(batcher.statBail(reason)); } - lastSectionsUploaded = delta(P_MESH_UPLOADED_SECTIONS, RenderRegionManager.getSectionsUploaded(), lastSectionsUploaded); - lastBytesUploaded = delta(P_MESH_UPLOADED_BYTES, RenderRegionManager.getBytesUploaded(), lastBytesUploaded); - lastIndexBufferGrowths = delta(P_DRAW_INDEX_BUFFER_GROWTHS, SharedQuadIndexBuffer.getGrowths(), lastIndexBufferGrowths); + P_MESH_UPLOADED_SECTIONS.plot(RenderRegionManager.getSectionsUploaded()); + P_MESH_UPLOADED_BYTES.plot(RenderRegionManager.getBytesUploaded()); + P_DRAW_INDEX_BUFFER_GROWTHS.plot(SharedQuadIndexBuffer.getGrowths()); Tracy.plotInt(P_MESH_META_SLOTS, GpuCulling.sectionMeta().getHighWaterMark()); Tracy.plotInt(P_MT_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth()); Tracy.plotInt(P_MT_QUEUE_TASKS, AngelicaRenderQueue.getLastFrameTasksRan()); @@ -253,10 +277,24 @@ public final class TracyFramePlots { RenderClassTimings.TESR.flushFrame(plots); BailClassCounts.MATERIAL.flushFrame(plots); BailClassCounts.TEMPLATE.flushFrame(plots); + BailClassCounts.PARTICLE_SPILL.flushFrame(plots); } - private static long delta(long handle, long now, long last) { - Tracy.plotInt(handle, now - last); - return now; + private static final class PlotDelta { + private final long handle; + private long last; + + PlotDelta(String name) { + this(name, TracyBackend.PLOT_FORMAT_NUMBER); + } + + PlotDelta(String name, int format) { + handle = Tracy.plotHandle(name, format); + } + + void plot(long now) { + Tracy.plotInt(handle, now - last); + last = now; + } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/ArmorTexturePaths.java b/src/main/java/com/gtnewhorizons/angelica/rendering/ArmorTexturePaths.java new file mode 100644 index 000000000..6ea46fac1 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/ArmorTexturePaths.java @@ -0,0 +1,38 @@ +package com.gtnewhorizons.angelica.rendering; + +import java.util.Arrays; + +public final class ArmorTexturePaths { + private static final int STRIDE = 5; + private static String[] table = new String[0]; + + public static String path(String prefix, int renderIndex, int slot, String type) { + if (prefix == null || (type != null && !"overlay".equals(type))) return format(prefix, slot, type); + String[] t = table; + final int base = renderIndex * STRIDE; + if (base >= t.length) { + t = Arrays.copyOf(t, base + STRIDE); + table = t; + } + if (t[base] != prefix) { + t[base + 1] = null; + t[base + 2] = null; + t[base + 3] = null; + t[base + 4] = null; + t[base] = prefix; + } + final int k = base + 1 + (slot == 2 ? 1 : 0) + (type == null ? 0 : 2); + String p = t[k]; + if (p == null) { + p = format(prefix, slot, type); + t[k] = p; + } + return p; + } + + private static String format(String prefix, int slot, String type) { + return "textures/models/armor/" + prefix + (slot == 2 ? "_layer_2" : "_layer_1") + (type == null ? ".png" : "_" + type + ".png"); + } + + private ArmorTexturePaths() {} +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/GlintClock.java b/src/main/java/com/gtnewhorizons/angelica/rendering/GlintClock.java new file mode 100644 index 000000000..c39197c47 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/GlintClock.java @@ -0,0 +1,56 @@ +package com.gtnewhorizons.angelica.rendering; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.joml.Matrix4fc; + +public final class GlintClock { + + private static final double SPEED0 = 0.001; + private static final double SPEED1 = 0.001 + 0.003; + private static final double SIN0 = Math.sin(Math.toRadians(30.0)); + private static final double COS0 = Math.cos(Math.toRadians(30.0)); + private static final double SIN1 = Math.sin(Math.toRadians(-30.0)); + private static final double COS1 = Math.cos(Math.toRadians(-30.0)); + + private static long millis; + private static float armorU0, armorV0, armorU1, armorV1; + + public static void beginFrame(long nowMillis) { + millis = nowMillis; + final double ticks = nowMillis / 50.0; + + final double f0 = ticks * SPEED0 * 20.0; + final double du0 = frac(-f0 * SIN0 / 3.0); + final double dv0 = frac(f0 * COS0 / 3.0); + armorU0 = (float) (3.0 * (COS0 * du0 + SIN0 * dv0)); + armorV0 = (float) (3.0 * (-SIN0 * du0 + COS0 * dv0)); + + final double f1 = ticks * SPEED1 * 20.0; + final double du1 = frac(-f1 * SIN1 / 3.0); + final double dv1 = frac(f1 * COS1 / 3.0); + armorU1 = (float) (3.0 * (COS1 * du1 + SIN1 * dv1)); + armorV1 = (float) (3.0 * (-SIN1 * du1 + COS1 * dv1)); + } + + public static long millis() { + return millis; + } + + static boolean secondArmorLayer(Matrix4fc textureMatrix) { + return textureMatrix.m01() < 0f; + } + + public static void translateArmorGlint() { + if (secondArmorLayer(GLStateManager.getMatrixStack())) { + GLStateManager.glTranslatef(armorU1, armorV1, 0f); + } else { + GLStateManager.glTranslatef(armorU0, armorV0, 0f); + } + } + + private static double frac(double x) { + return x - Math.floor(x); + } + + private GlintClock() {} +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/OperationArgs.java b/src/main/java/com/gtnewhorizons/angelica/rendering/OperationArgs.java new file mode 100644 index 000000000..af013fc9a --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/OperationArgs.java @@ -0,0 +1,14 @@ +package com.gtnewhorizons.angelica.rendering; + +public final class OperationArgs { + + private OperationArgs() {} + + public static Object boxed(Object prev, float v) { + return prev instanceof Float f && Float.floatToRawIntBits(f) == Float.floatToRawIntBits(v) ? prev : Float.valueOf(v); + } + + public static Object boxed(Object prev, int v) { + return prev instanceof Integer i && i == v ? prev : Integer.valueOf(v); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/ParticleRunSplitter.java b/src/main/java/com/gtnewhorizons/angelica/rendering/ParticleRunSplitter.java index e8b170eae..2c26c5c31 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/ParticleRunSplitter.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/ParticleRunSplitter.java @@ -49,6 +49,10 @@ public final class ParticleRunSplitter { } } + public static boolean currentRunTranslucent() { + return runTranslucent; + } + public static boolean isTranslucent(EntityFX particle) { if (particle.particleIcon instanceof TextureAtlasSprite sprite) { return ((SpriteExtension) sprite).celeritas$getTransparencyLevel() == SpriteTransparencyLevel.TRANSLUCENT; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java index d03ee5921..5e6365a3e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java @@ -88,6 +88,7 @@ public class CeleritasDebugScreenHandler { addIfPresent(lines, RenderClassTimings.SHADOW_ENTITY.debugLine()); addIfPresent(lines, BailClassCounts.MATERIAL.debugLine()); addIfPresent(lines, BailClassCounts.TEMPLATE.debugLine()); + addIfPresent(lines, BailClassCounts.PARTICLE_SPILL.debugLine()); } } lines.add(""); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java index 4c34c7646..e2cbd84ee 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java @@ -54,6 +54,7 @@ import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; +import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer; import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; @@ -168,6 +169,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer icons = new ItemPropCache<>(() -> AngelicaConfig.itemRendererCacheSize, IconMesh::new, null); + private static final Object2ObjectOpenHashMap blocks = new Object2ObjectOpenHashMap<>(); + private static final BlockMeta blockKey = new BlockMeta(); + private static final AngelicaTesrMeshCache.GtnhMeshBackend iconBackend = new AngelicaTesrMeshCache.GtnhMeshBackend(); + private static final Object[] ICON_ARGS = new Object[8]; + private static final Object[] GLINT_ARGS = new Object[8]; + private static final Object[] BLOCK_ARGS = new Object[4]; + private static BakedTransformCapture blockBackend; + private static boolean basePart; + + private static long instanced; + private static long glintInstanced; + private static long fallback; + + public enum BailReason { + INELIGIBLE("items.bail.ineligible"), + NO_MATERIAL("items.bail.material"), + ISBRH("items.bail.isbrh"), + BLOCK_STATE("items.bail.blockState"), + NOT_ALLOWED("items.bail.notAllowed"), + TEMPLATE("items.bail.template"), + QUEUE("items.bail.queue"); + + public static final BailReason[] VALUES = values(); + public final String plotName; + + BailReason(String plotName) { + this.plotName = plotName; + } + } + + private static final long[] bails = new long[BailReason.VALUES.length]; + + private DroppedItemInstancer() {} + + public static long statInstanced() { + return instanced; + } + + public static long statGlintInstanced() { + return glintInstanced; + } + + public static long statFallback() { + return fallback; + } + + public static long statBail(BailReason reason) { + return bails[reason.ordinal()]; + } + + private static void bail(BailReason reason) { + bails[reason.ordinal()]++; + } + + private static boolean glintEligible(ItemStack stack) { + return stack != null && stack.getItem() != null && ModelPartBatcher.INSTANCE.isActive() && !GLStateManager.isRecordingDisplayList() && !TessellatorManager.isCurrentlyCapturing() && !TessellatorManager.shouldInterceptDraw(Tessellator.instance); + } + + static TesrMaterial material(ItemStack stack, boolean unfilteredAtlas) { + if (stack == null) return null; + if (!glintEligible(stack)) { + fallback++; + bail(BailReason.INELIGIBLE); + return null; + } + final TesrMaterial material = EntityMaterials.itemFromCurrentState(unfilteredAtlas); + if (material == null) { + fallback++; + bail(BailReason.NO_MATERIAL); + } + return material; + } + + public static void icon(ItemStack stack, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + final TesrMaterial material = material(stack, true); + if (material == null) { + basePart = false; + callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness); + return; + } + basePart = batchIcon(material, t, maxU, minV, minU, maxV, width, height, thickness, original); + } + + static boolean batchIcon(TesrMaterial material, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + final long drawsBefore = GLStateManager.drawCalls; + if (BatchEligibility.batchingAllowed()) { + final TemplateBuffer template = iconTemplate(ICON_ARGS, maxU, minV, minU, maxV, width, height, thickness, original); + if (template == null) { + callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness); + fallback++; + bail(BailReason.TEMPLATE); + return false; + } + if (ModelPartBatcher.INSTANCE.queueTemplate(template, material)) { + instanced++; + BatchEligibility.onPartQueued(); + return true; + } + fallback++; + bail(BailReason.QUEUE); + } else { + bail(BailReason.NOT_ALLOWED); + } + callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness); + BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls); + return true; + } + + public static void glint(Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + if (!basePart) { + callIcon(GLINT_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness); + return; + } + final boolean allowed = BatchEligibility.batchingAllowed(); + if (allowed && ModelPartBatcher.INSTANCE.isShadowPass()) { + BatchEligibility.onPartQueued(); + return; + } + final long drawsBefore = GLStateManager.drawCalls; + if (allowed) { + final TemplateBuffer template = iconTemplate(GLINT_ARGS, maxU, minV, minU, maxV, width, height, thickness, original); + if (template != null && ModelPartBatcher.INSTANCE.queueTemplate(template, EntityMaterials.GLINT)) { + glintInstanced++; + BatchEligibility.onPartQueued(); + return; + } + fallback++; + bail(template == null ? BailReason.TEMPLATE : BailReason.QUEUE); + } else { + bail(BailReason.NOT_ALLOWED); + } + callIcon(GLINT_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness); + BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls); + } + + public static void block(ItemStack stack, RenderBlocks rb, Block block, int meta, float brightness, boolean unfilteredAtlas, Operation original) { + final TesrMaterial material = material(stack, unfilteredAtlas); + if (material == null) { + callBlock(original, rb, block, meta, brightness); + return; + } + final BailReason stateBail = blockStateBail(rb, block, brightness); + if (stateBail != null) { + fallback++; + bail(stateBail); + callBlock(original, rb, block, meta, brightness); + return; + } + batchBlock(material, rb, block, meta, brightness, original); + } + + static void batchBlock(TesrMaterial material, RenderBlocks rb, Block block, int meta, float brightness, Operation original) { + final long drawsBefore = GLStateManager.drawCalls; + if (BatchEligibility.batchingAllowed()) { + BlockMesh mesh = lookupBlock(block, meta); + if (mesh == null) { + mesh = captureBlock(rb, block, meta, brightness, original); + } else if (mesh.template() != null) { + GLStateManager.glColor4f(mesh.red(), mesh.green(), mesh.blue(), mesh.alpha()); + } + if (mesh.template() == null) { + callBlock(original, rb, block, meta, brightness); + fallback++; + bail(BailReason.TEMPLATE); + return; + } + if (ModelPartBatcher.INSTANCE.queueTemplate(mesh.template(), material)) { + instanced++; + BatchEligibility.onPartQueued(); + return; + } + fallback++; + bail(BailReason.QUEUE); + } else { + bail(BailReason.NOT_ALLOWED); + } + callBlock(original, rb, block, meta, brightness); + BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls); + } + + public static void clear() { + icons.clear(); + blocks.clear(); + blockKey.block = null; + basePart = false; + if (blockBackend != null) { + blockBackend.delete(); + blockBackend = null; + } + } + + private static void callIcon(Object[] args, Operation original, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness) { + args[0] = t; + args[1] = OperationArgs.boxed(args[1], maxU); + args[2] = OperationArgs.boxed(args[2], minV); + args[3] = OperationArgs.boxed(args[3], minU); + args[4] = OperationArgs.boxed(args[4], maxV); + args[5] = OperationArgs.boxed(args[5], width); + args[6] = OperationArgs.boxed(args[6], height); + args[7] = OperationArgs.boxed(args[7], thickness); + try { + original.call(args); + } finally { + args[0] = null; + } + } + + private static void callBlock(Operation original, RenderBlocks rb, Block block, int meta, float brightness) { + final Object[] args = BLOCK_ARGS; + args[0] = rb; + args[1] = block; + args[2] = OperationArgs.boxed(args[2], meta); + args[3] = OperationArgs.boxed(args[3], brightness); + try { + original.call(args); + } finally { + args[0] = null; + args[1] = null; + } + } + + private static TemplateBuffer iconTemplate(Object[] args, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + final IconMesh hit = icons.get(maxU, minV, minU, maxV, width, height, thickness); + if (hit != null) return hit.template; + final Tessellator capture = iconBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL); + final TemplateBuffer template; + try { + callIcon(args, original, capture, maxU, minV, minU, maxV, width, height, thickness); + } finally { + template = iconBackend.endCaptureToTemplate(); + } + if (template == null) return null; + icons.insert().template = template; + return template; + } + + private static BlockMesh captureBlock(RenderBlocks rb, Block block, int meta, float brightness, Operation original) { + if (blockBackend == null) { + blockBackend = new BakedTransformCapture(CAPTURE_BYTES); + } + final TemplateBuffer template; + GLStateManager.glPushMatrix(); + try { + blockBackend.begin(); + try { + callBlock(original, rb, block, meta, brightness); + } finally { + template = blockBackend.end(); + } + } finally { + GLStateManager.glPopMatrix(); + } + final Color4 color = GLStateManager.getColor(); + final BlockMesh mesh = new BlockMesh(template, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + blocks.put(new BlockMeta(block, meta), mesh); + return mesh; + } + + private static BlockMesh lookupBlock(Block block, int meta) { + blockKey.block = block; + blockKey.meta = meta; + return blocks.get(blockKey); + } + + private static BailReason blockStateBail(RenderBlocks renderBlocks, Block block, float brightness) { + if (BlockRenderListManager.isISBRH(block.getRenderType())) return BailReason.ISBRH; + if (renderBlocks.enableAO || renderBlocks.overrideBlockTexture != null || brightness != 1.0F || !renderBlocks.useInventoryTint || renderBlocks.blockAccess != null || (renderBlocks.uvRotateEast | renderBlocks.uvRotateWest | renderBlocks.uvRotateSouth | renderBlocks.uvRotateNorth | renderBlocks.uvRotateTop | renderBlocks.uvRotateBottom) != 0) return BailReason.BLOCK_STATE; + return null; + } + + private static final class IconMesh { + TemplateBuffer template; + } + + private record BlockMesh(TemplateBuffer template, float red, float green, float blue, float alpha) {} +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemPropCache.java b/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemPropCache.java new file mode 100644 index 000000000..6787f358b --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemPropCache.java @@ -0,0 +1,113 @@ +package com.gtnewhorizons.angelica.rendering.items; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import lombok.Data; +import lombok.NoArgsConstructor; +import net.minecraft.client.Minecraft; + +import java.util.function.Consumer; +import java.util.function.IntSupplier; +import java.util.function.Supplier; + +public final class ItemPropCache { + + private static final int EXPIRY_TICKS = 1_200; + + private final Object2ObjectLinkedOpenHashMap> cache = new Object2ObjectLinkedOpenHashMap<>(64); + private final ItemProp key = new ItemProp(); + private final IntSupplier capacity; + private final Supplier factory; + private final Consumer disposer; + private int smallestExpiry; + + public ItemPropCache(IntSupplier capacity, Supplier factory, Consumer disposer) { + this.capacity = capacity; + this.factory = factory; + this.disposer = disposer; + } + + public V get(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { + key.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); + if (cache.isEmpty()) return null; + final Slot slot = cache.getAndMoveToLast(key); + if (slot == null) return null; + final int time = elapsedTicks(); + slot.expiry = time + EXPIRY_TICKS; + if (time > smallestExpiry && time > (smallestExpiry = cache.get(cache.firstKey()).expiry + 20)) { + dispose(cache.removeFirst()); + if (!cache.isEmpty()) { + smallestExpiry = cache.get(cache.firstKey()).expiry + 20; + } + } + return slot.value; + } + + public V insert() { + final Slot slot; + if (cache.size() >= capacity.getAsInt()) { + final ItemProp oldest = cache.firstKey(); + slot = cache.removeFirst(); + oldest.set(key); + cache.put(oldest, slot); + } else { + slot = new Slot<>(); + slot.value = factory.get(); + cache.put(new ItemProp(key), slot); + } + slot.expiry = elapsedTicks() + EXPIRY_TICKS; + return slot.value; + } + + public void clear() { + for (Slot slot : cache.values()) { + dispose(slot); + } + cache.clear(); + smallestExpiry = 0; + } + + private void dispose(Slot slot) { + if (disposer != null && slot.value != null) { + disposer.accept(slot.value); + } + } + + private static int elapsedTicks() { + return Minecraft.getMinecraft().thePlayer.ticksExisted; + } + + private static final class Slot { + private V value; + private int expiry; + } + + @NoArgsConstructor + @Data + static final class ItemProp { + private float minU; + private float minV; + private float maxU; + private float maxV; + private int widthSubdivisions; + private int heightSubdivisions; + private float thickness; + + ItemProp(ItemProp old) { + set(old); + } + + void set(ItemProp other) { + set(other.minU, other.minV, other.maxU, other.maxV, other.widthSubdivisions, other.heightSubdivisions, other.thickness); + } + + void set(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { + this.minU = minU; + this.minV = minV; + this.maxU = maxU; + this.maxV = maxV; + this.widthSubdivisions = widthSubdivisions; + this.heightSubdivisions = heightSubdivisions; + this.thickness = thickness; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemRenderListManager.java b/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemRenderListManager.java index 34612dab2..a749a5302 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemRenderListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/items/ItemRenderListManager.java @@ -37,9 +37,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import lombok.Data; -import lombok.NoArgsConstructor; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.IReloadableResourceManager; import org.lwjgl.opengl.GL11; @@ -52,52 +49,16 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCalloc; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; public class ItemRenderListManager { - // Least used element is at position 0. This is in theory slightly faster. - private static final Object2ObjectLinkedOpenHashMap vboCache = new Object2ObjectLinkedOpenHashMap<>(64); - // 1 minute - private static final int EXPIRY_TICKS = 1_200; - private static int smallestExpiry; - - private static final ItemProp prop = new ItemProp(); + private static final ItemPropCache vboCache = new ItemPropCache<>(() -> AngelicaConfig.itemRendererCacheSize, CachedVBO::new, CachedVBO::delete); public static CachedVBO pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { - prop.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); - - if (!vboCache.isEmpty()) { - - final CachedVBO vbo = vboCache.getAndMoveToLast(prop); - - if (vbo != null) { - final int time = getElapsedTicks(); - vbo.render(time); - - // Prevent constant map lookups by only storing the expiry of the least recently used entry - if (time > smallestExpiry && time > (smallestExpiry = (vboCache.get(vboCache.firstKey()).expiry + 20))) { - vboCache.removeFirst().delete(); - if (!vboCache.isEmpty()) { - smallestExpiry = vboCache.get(vboCache.firstKey()).expiry + 20; - } - } - - return null; - } + final CachedVBO hit = vboCache.get(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness); + if (hit != null) { + hit.render(); + return null; } - - final CachedVBO vbo; - if (vboCache.size() >= AngelicaConfig.itemRendererCacheSize) { - final ItemProp oldestProp = vboCache.firstKey(); - vbo = vboCache.removeFirst(); - oldestProp.set(prop); - vboCache.put(oldestProp, vbo); - } else { - vbo = new CachedVBO(); - vboCache.put(new ItemProp(prop), vbo); - } - - vbo.expiry = getElapsedTicks() + EXPIRY_TICKS; - - return vbo; + return vboCache.insert(); } public static void post(DirectTessellator tessellator, CachedVBO vbo) { @@ -106,10 +67,6 @@ public class ItemRenderListManager { vbo.vertexBuffer.render(); } - private static int getElapsedTicks() { - return Minecraft.getMinecraft().thePlayer.ticksExisted; - } - public static void registerReloadListener(){ IReloadableResourceManager resourceManager = (IReloadableResourceManager) Minecraft.getMinecraft() .getResourceManager(); @@ -117,16 +74,12 @@ public class ItemRenderListManager { } public static void clearCache() { - for (CachedVBO value : vboCache.values()) { - value.delete(); - } vboCache.clear(); } public static final class CachedVBO { private final IVertexArrayObject vertexBuffer; private final IndexBuffer ebo; - private int expiry; private int extVbo = 0; public CachedVBO() { @@ -195,9 +148,8 @@ public class ItemRenderListManager { extVbo = 0; } - private void render(int elapsedTicks) { + private void render() { vertexBuffer.render(); - expiry = elapsedTicks + EXPIRY_TICKS; } private void delete() { @@ -210,43 +162,4 @@ public class ItemRenderListManager { } } - @NoArgsConstructor - @Data - private static final class ItemProp { - private float minU; - private float minV; - private float maxU; - private float maxV; - private int widthSubdivisions; - private int heightSubdivisions; - private float thickness; - - public ItemProp(ItemProp old) { - set( - old.minU, old.minV, - old.maxU, old.maxV, - old.widthSubdivisions, old.heightSubdivisions, - old.thickness - ); - } - - public void set(ItemProp other) { - set( - other.minU, other.minV, - other.maxU, other.maxV, - other.widthSubdivisions, other.heightSubdivisions, - other.thickness - ); - } - - public void set(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) { - this.minU = minU; - this.minV = minV; - this.maxU = maxU; - this.maxV = maxV; - this.widthSubdivisions = widthSubdivisions; - this.heightSubdivisions = heightSubdivisions; - this.thickness = thickness; - } - } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/BopParticleDescriptors.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/BopParticleDescriptors.java new file mode 100644 index 000000000..660637aaa --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/BopParticleDescriptors.java @@ -0,0 +1,68 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.ITextureObject; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.util.ResourceLocation; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; + +public final class BopParticleDescriptors { + + private static final Logger LOG = LogManager.getLogger("Angelica"); + + private static final String PIXIE_TRAIL_CLASS = "biomesoplenty.client.particles.EntityPixieTrailFX"; + private static final ResourceLocation PIXIE_TRAIL_TEXTURE = new ResourceLocation("biomesoplenty:textures/particles/pixietrail.png"); + + private static final int UNRESOLVED = -1; + + private static int pixieTrailTexture = UNRESOLVED; + + public static final ParticleDescriptor PIXIE_TRAIL = (fx, partialTicks, out, state) -> { + final int texture = pixieTrailTexture(); + if (texture == 0) return false; + fx.particleScale = fx.particleScale * ParticleQuads.ramp(fx.particleAge, fx.particleMaxAge, partialTicks); + ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out); + out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, 1.0F); + out.brightness = 175; + state.texture = texture; + state.blend = true; + state.blendSrc = GL11.GL_SRC_ALPHA; + state.blendDst = GL11.GL_ONE; + state.blendSrcAlpha = GL11.GL_SRC_ALPHA; + state.blendDstAlpha = GL11.GL_ONE; + state.depthMask = false; + return true; + }; + + private BopParticleDescriptors() {} + + public static void registerAll() { + ParticleDescriptorRegistry.register(PIXIE_TRAIL_CLASS, PIXIE_TRAIL); + } + + public static void invalidate() { + pixieTrailTexture = UNRESOLVED; + } + + private static int pixieTrailTexture() { + int id = pixieTrailTexture; + if (id != UNRESOLVED) return id; + final TextureManager manager = Minecraft.getMinecraft().getTextureManager(); + ITextureObject texture = manager.getTexture(PIXIE_TRAIL_TEXTURE); + if (texture == null) { + final int previous = GLStateManager.getBoundTextureForServerState(); + manager.bindTexture(PIXIE_TRAIL_TEXTURE); + texture = manager.getTexture(PIXIE_TRAIL_TEXTURE); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous); + } + id = texture == null ? 0 : texture.getGlTextureId(); + if (id == 0) LOG.warn("Pixie trail texture {} is unavailable; those particles will not draw", PIXIE_TRAIL_TEXTURE); + pixieTrailTexture = id; + return id; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCaptureTessellator.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCaptureTessellator.java new file mode 100644 index 000000000..39e771140 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCaptureTessellator.java @@ -0,0 +1,231 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.minecraft.client.renderer.Tessellator; +import org.joml.Matrix4fc; +import org.lwjgl.opengl.GL11; + +public final class ParticleCaptureTessellator extends Tessellator { + + public static final int MAX_VERTICES = 4; + + private final float[] verts = new float[MAX_VERTICES * 5]; + private final ParticleRenderState state = new ParticleRenderState(); + private final ParticleRenderState scratch = new ParticleRenderState(); + private int captured; + private boolean spilled; + private boolean uvSet; + private float pendingU; + private float pendingV; + private boolean closed; + private Matrix4fc layerModelView; + private Tessellator run; + + public void begin(int startBrightness, Tessellator runTessellator, Matrix4fc layerModelView) { + this.layerModelView = layerModelView; + this.run = runTessellator; + this.captured = 0; + this.spilled = false; + this.closed = false; + this.uvSet = false; + this.pendingU = 0.0f; + this.pendingV = 0.0f; + this.brightness = startBrightness; + this.hasBrightness = true; + this.color = runTessellator.hasColor ? runTessellator.color : 0xFFFFFFFF; + this.hasColor = runTessellator.hasColor; + this.hasTexture = false; + this.hasNormals = false; + this.isColorDisabled = false; + this.xOffset = 0.0D; + this.yOffset = 0.0D; + this.zOffset = 0.0D; + } + + public void release() { + run = null; + layerModelView = null; + captured = 0; + } + + public boolean spilled() { + return spilled; + } + + public void propagateColor() { + if (spilled || closed || !hasColor || run == null) return; + run.color = color; + run.hasColor = true; + } + + public int captured() { + return captured; + } + + public float[] vertices() { + return verts; + } + + public int capturedBrightness() { + return brightness; + } + + public ParticleRenderState state() { + return state; + } + + public int capturedColor() { + return color; + } + + public void replayInto(Tessellator t) { + t.setBrightness(brightness); + if (hasColor) { + t.setColorRGBA(color & 255, (color >> 8) & 255, (color >> 16) & 255, (color >>> 24) & 255); + } + if (uvSet) { + t.setTextureUV(pendingU, pendingV); + } + for (int i = 0, o = 0; i < captured; i++, o += 5) { + t.addVertexWithUV(verts[o], verts[o + 1], verts[o + 2], verts[o + 3], verts[o + 4]); + } + } + + private void spill() { + if (spilled) return; + spilled = true; + if (closed) { + scratch.sample(); + state.apply(); + final boolean wasDrawing = run.isDrawing; + if (!wasDrawing) run.startDrawingQuads(); + replayInto(run); + run.draw(); + if (wasDrawing) run.startDrawingQuads(); + scratch.apply(); + } else { + replayInto(run); + } + captured = 0; + } + + @Override + public void setTextureUV(double u, double v) { + if (spilled) { + run.setTextureUV(u, v); + return; + } + if (closed) { + run.setTextureUV(u, v); + pendingU = (float) u; + pendingV = (float) v; + return; + } + hasTexture = true; + uvSet = true; + pendingU = (float) u; + pendingV = (float) v; + } + + @Override + public void addVertexWithUV(double x, double y, double z, double u, double v) { + setTextureUV(u, v); + addVertex(x, y, z); + } + + @Override + public void addVertex(double x, double y, double z) { + if (spilled) { + run.addVertex(x, y, z); + return; + } + boolean overflow = !uvSet || closed || captured == MAX_VERTICES; + if (!overflow && captured == 0) { + if (GLStateManager.getModelViewMatrix().equals(layerModelView)) state.sample(); + else overflow = true; + } + if (overflow) { + spill(); + if (uvSet) run.addVertexWithUV(x, y, z, pendingU, pendingV); + else run.addVertex(x, y, z); + return; + } + final int o = captured * 5; + verts[o] = (float) (x + xOffset); + verts[o + 1] = (float) (y + yOffset); + verts[o + 2] = (float) (z + zOffset); + verts[o + 3] = pendingU; + verts[o + 4] = pendingV; + captured++; + } + + @Override + public void setColorRGBA(int red, int green, int blue, int alpha) { + if (spilled || closed) { + run.setColorRGBA(red, green, blue, alpha); + return; + } + final int r = Math.clamp(red, 0, 255); + final int g = Math.clamp(green, 0, 255); + final int b = Math.clamp(blue, 0, 255); + final int a = Math.clamp(alpha, 0, 255); + final int packed = (a << 24) | (b << 16) | (g << 8) | r; + if (hasColor && packed != color && captured > 0) { + spill(); + run.setColorRGBA(red, green, blue, alpha); + return; + } + hasColor = true; + color = packed; + } + + @Override + public void setBrightness(int value) { + if (spilled || closed) { + run.setBrightness(value); + return; + } + hasBrightness = true; + brightness = value; + } + + @Override + public void setNormal(float x, float y, float z) { + if (!closed) spill(); + run.setNormal(x, y, z); + } + + @Override + public void disableColor() { + if (!closed) spill(); + run.disableColor(); + } + + @Override + public void startDrawingQuads() { + if (!spilled && !closed && captured != 0) spill(); + run.startDrawingQuads(); + } + + @Override + public void startDrawing(int mode) { + if (mode == GL11.GL_QUADS) { + startDrawingQuads(); + return; + } + spill(); + run.startDrawing(mode); + } + + @Override + public int draw() { + if (!spilled && !closed) { + if (captured == MAX_VERTICES) { + closed = true; + } else if (captured != 0) { + spill(); + } + } + return run.draw(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCulling.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCulling.java new file mode 100644 index 000000000..5b5b58160 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleCulling.java @@ -0,0 +1,12 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; + +public final class ParticleCulling { + + private ParticleCulling() {} + + public static boolean visible(CeleritasWorldRenderer renderer, double x, double y, double z) { + return renderer == null || renderer.isPointVisible(x, y, z); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptor.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptor.java new file mode 100644 index 000000000..ca64bd003 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptor.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import net.minecraft.client.particle.EntityFX; + +public interface ParticleDescriptor { + + boolean describe(EntityFX fx, float partialTicks, ParticleParams out, ParticleRenderState state); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptorRegistry.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptorRegistry.java new file mode 100644 index 000000000..57a19c494 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleDescriptorRegistry.java @@ -0,0 +1,80 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Method; + +public final class ParticleDescriptorRegistry { + + private static final Logger LOGGER = LogManager.getLogger("Angelica/Particles"); + + private static final String[] RENDER_PARTICLE_NAMES = { "renderParticle", "func_70539_a" }; + + public static final ParticleDescriptor CAPTURE = (fx, partialTicks, out, state) -> false; + public static final ParticleDescriptor VANILLA = (fx, partialTicks, out, state) -> { + ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out); + return true; + }; + + private static final Object2ObjectOpenHashMap BY_NAME = new Object2ObjectOpenHashMap<>(); + private static final Reference2ObjectOpenHashMap, ParticleDescriptor> BY_CLASS = new Reference2ObjectOpenHashMap<>(); + + private static Class lastClass; + private static ParticleDescriptor lastDescriptor; + + static { + VanillaParticleDescriptors.registerAll(); + BopParticleDescriptors.registerAll(); + } + + private ParticleDescriptorRegistry() {} + + public static void register(String className, ParticleDescriptor descriptor) { + BY_NAME.put(className, descriptor); + clearCache(); + } + + public static ParticleDescriptor forClass(Class cls) { + if (cls == lastClass) return lastDescriptor; + ParticleDescriptor d = BY_CLASS.get(cls); + if (d == null) { + d = resolve(cls); + BY_CLASS.put(cls, d); + } + lastClass = cls; + lastDescriptor = d; + return d; + } + + public static void clearCache() { + BY_CLASS.clear(); + lastClass = null; + lastDescriptor = null; + } + + private static ParticleDescriptor resolve(Class cls) { + final ParticleDescriptor registered = BY_NAME.get(cls.getName()); + if (registered != null) return registered; + + final Method render = renderParticleMethod(cls); + if (render == null) { + LOGGER.warn("Could not locate renderParticle on particle class {}, using the capture path", cls.getName()); + return CAPTURE; + } + return render.getDeclaringClass() == EntityFX.class ? VANILLA : CAPTURE; + } + + private static Method renderParticleMethod(Class cls) { + for (String name : RENDER_PARTICLE_NAMES) { + try { + return cls.getMethod(name, Tessellator.class, float.class, float.class, float.class, float.class, float.class, float.class); + } catch (NoSuchMethodException ignored) {} + } + return null; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancer.java new file mode 100644 index 000000000..5d530897f --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancer.java @@ -0,0 +1,357 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.ParticleInstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.ParticleQuadMesh; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.profiling.BailClassCounts; +import com.gtnewhorizons.angelica.proxy.ClientProxy; +import com.gtnewhorizons.angelica.rendering.OperationArgs; +import com.gtnewhorizons.angelica.rendering.ParticleRunSplitter; +import com.gtnewhorizons.angelica.rendering.tesr.InstanceRing; +import com.gtnewhorizons.angelica.rendering.tesr.MeshBuffer; +import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; +import net.coderbot.iris.Iris; +import net.coderbot.iris.layer.GbufferPrograms; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; + +public final class ParticleInstancer { + + private static final int STRIDE = ParticleInstancedAttribs.STRIDE; + private static final int INITIAL_BYTES = 256 * STRIDE; + + private static final ParticleCaptureTessellator CAPTURE = new ParticleCaptureTessellator(); + private static final ParticleParams SCRATCH = new ParticleParams(); + private static final ParticleRenderState STATE = new ParticleRenderState(); + private static final ParticleRenderState RESTORE = new ParticleRenderState(); + private static final Matrix4f LAYER_MV = new Matrix4f(); + private static final Object[] ORIGINAL_ARGS = new Object[8]; + + private static final ObjectArrayList GROUP_POOL = new ObjectArrayList<>(); + private static int groupCount; + + private static final class Group { + final ParticleRenderState state = new ParticleRenderState(); + ByteBuffer list; + boolean translucent; + } + + private static boolean layerActive; + private static boolean layerStarted; + private static DeferredWorldRenderingPipeline unavailableFor; + private static DeferredWorldRenderingPipeline deferred; + private static Tessellator run; + + private static float rotX; + private static float rotXZ; + private static float rotZ; + private static float rotYZ; + private static float rotXY; + + private static long direct; + private static long captured; + private static long spilled; + private static long undecodable; + private static long draws; + + private ParticleInstancer() {} + + public static long getDirect() { + return direct; + } + + public static long getCaptured() { + return captured; + } + + public static long getDraws() { + return draws; + } + + public static long getSpilled() { + return spilled; + } + + public static long getUndecodable() { + return undecodable; + } + + private static void beginLayer() { + layerActive = false; + layerStarted = true; + final SodiumGameOptions options = ClientProxy.options(); + if (options == null || !options.advanced.enableDeferredBatching) return; + + deferred = pipeline(); + if (available()) { + layerActive = true; + groupCount = 0; + LAYER_MV.set(GLStateManager.getModelViewMatrix()); + } else { + deferred = null; + DeferredDrawBatcher.enter(); + } + } + + public static void renderParticle(EntityFX fx, Tessellator runTessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation original) { + if (!layerStarted) beginLayer(); + if (!layerActive) { + call(fx, runTessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original); + return; + } + renderActive(fx, runTessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original); + } + + private static void renderActive(EntityFX fx, Tessellator runTessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation original) { + + run = runTessellator; + rotX = rotationX; + rotXZ = rotationXZ; + rotZ = rotationZ; + rotYZ = rotationYZ; + rotXY = rotationXY; + + final ParticleDescriptor descriptor = ParticleDescriptorRegistry.forClass(fx.getClass()); + if (descriptor != ParticleDescriptorRegistry.CAPTURE) { + STATE.sample(); + SCRATCH.brightness = runTessellator.brightness; + if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return; + + runTessellator.color = SCRATCH.colorABGR; + runTessellator.hasColor = true; + emit(groupFor(STATE, deferred != null && ParticleRunSplitter.currentRunTranslucent())); + direct++; + return; + } + + CAPTURE.begin(runTessellator.brightness, runTessellator, LAYER_MV); + call(fx, CAPTURE, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original); + CAPTURE.propagateColor(); + + if (CAPTURE.spilled()) { + spilled++; + if (Tracy.ENABLED) BailClassCounts.PARTICLE_SPILL.add(fx.getClass()); + return; + } + if (CAPTURE.captured() == 0) return; + + if (!ParticleQuadDecoder.decode(CAPTURE.vertices(), CAPTURE.captured(), rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, SCRATCH)) { + CAPTURE.replayInto(runTessellator); + undecodable++; + return; + } + + SCRATCH.colorABGR = CAPTURE.capturedColor(); + SCRATCH.brightness = CAPTURE.capturedBrightness(); + emit(groupFor(CAPTURE.state(), deferred != null && ParticleRunSplitter.currentRunTranslucent())); + captured++; + } + + private static void emit(Group group) { + final ByteBuffer list = MeshBuffer.ensureCapacity(group.list, STRIDE, true); + group.list = list; + ParticleInstancedAttribs.writeInstance(memAddress0(list) + list.position(), SCRATCH.centerX, SCRATCH.centerY, SCRATCH.centerZ, SCRATCH.half, SCRATCH.u0, SCRATCH.v0, SCRATCH.u1, SCRATCH.v1, SCRATCH.colorABGR, SCRATCH.brightness); + list.position(list.position() + STRIDE); + } + + public static void endLayer() { + layerStarted = false; + if (!layerActive) { + if (DeferredDrawBatcher.isActive()) DeferredDrawBatcher.exitAndFlush(); + return; + } + layerActive = false; + + if (groupCount > 0) { + RESTORE.sample(); + for (int i = 0; i < groupCount; i++) { + final Group group = GROUP_POOL.get(i); + if (!group.translucent) flush(group); + } + for (int i = 0; i < groupCount; i++) { + final Group group = GROUP_POOL.get(i); + if (group.translucent) flush(group); + } + RESTORE.apply(); + if (deferred != null) { + GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent()); + } + ring().postDraw(); + groupCount = 0; + } + + deferred = null; + run = null; + } + + private static Group groupFor(ParticleRenderState state, boolean translucent) { + for (int i = 0; i < groupCount; i++) { + final Group g = GROUP_POOL.get(i); + if (g.translucent == translucent && g.state.matches(state)) return g; + } + if (groupCount == GROUP_POOL.size()) GROUP_POOL.add(new Group()); + final Group g = GROUP_POOL.get(groupCount++); + g.state.set(state); + g.translucent = translucent; + if (g.list != null) g.list.clear(); + g.list = MeshBuffer.ensureCapacity(g.list, INITIAL_BYTES, true); + return g; + } + + public static void clear() { + layerActive = false; + layerStarted = false; + deferred = null; + run = null; + unavailableFor = null; + groupCount = 0; + for (int i = 0; i < GROUP_POOL.size(); i++) { + GROUP_POOL.get(i).list = null; + } + GROUP_POOL.clear(); + CAPTURE.release(); + ParticleQuadMesh.delete(); + ParticleDescriptorRegistry.clearCache(); + } + + private static void call(EntityFX fx, Tessellator target, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation original) { + final Object[] args = ORIGINAL_ARGS; + args[0] = fx; + args[1] = target; + args[2] = OperationArgs.boxed(args[2], partialTicks); + args[3] = OperationArgs.boxed(args[3], rotationX); + args[4] = OperationArgs.boxed(args[4], rotationXZ); + args[5] = OperationArgs.boxed(args[5], rotationZ); + args[6] = OperationArgs.boxed(args[6], rotationYZ); + args[7] = OperationArgs.boxed(args[7], rotationXY); + try { + original.call(args); + } finally { + args[0] = null; + args[1] = null; + } + } + + private static boolean available() { + if (deferred != null && deferred == unavailableFor) return false; + if (!ShaderManager.getInstance().isEnabled()) return false; + return deferred == null || deferred.supportsInstancing(Instancing.PARTICLE); + } + + private static DeferredWorldRenderingPipeline pipeline() { + if (!Iris.enabled) return null; + return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline pipeline ? pipeline : null; + } + + private static InstanceRing ring() { + return TesrBatchRenderer.INSTANCE.instanceRing(); + } + + private static void flush(Group group) { + final ByteBuffer list = group.list; + final boolean listTranslucent = group.translucent; + final int count = list.position() / STRIDE; + if (count == 0) return; + group.state.apply(); + list.flip(); + + if (deferred != null) { + GbufferPrograms.setTranslucencyDeclaration(listTranslucent); + deferred.rebindCurrentPass(); + if (!deferred.hasInstancedVariant(Instancing.PARTICLE)) { + unavailableFor = deferred; + drawInstancesCpu(group.state, list, count, listTranslucent); + list.clear(); + return; + } + } + + final long base = ring().upload(list, STRIDE); + list.clear(); + + if (deferred != null) { + deferred.bindInstancedVariant(Instancing.PARTICLE); + issueDraw(base, count, false); + deferred.rebindCurrentPass(); + } else { + issueDraw(base, count, true); + } + } + + private static void issueDraw(long base, int count, boolean ffp) { + ParticleQuadMesh.update(rotX, rotXZ, rotZ, rotYZ, rotXY); + final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler; + if (extHandler != null && extHandler.wantsExtended()) { + FfpExtendedAttribs.setNeutralCurrentValues(); + } + GLStateManager.glBindVertexArray(ParticleQuadMesh.vao()); + VAOManager.setCurrentVertexFlags(ParticleQuadMesh.VERTEX_FLAGS); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ring().bufferId()); + ParticleInstancedAttribs.pointInstanceAttribs(base); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + if (ffp) GLStateManager.ffpInstancing = Instancing.PARTICLE; + GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, ParticleQuadMesh.VERTEX_COUNT, count); + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + draws++; + } + + private static void drawInstancesCpu(ParticleRenderState state, ByteBuffer list, int count, boolean listTranslucent) { + final Tessellator t = run; + RESTORE.apply(); + GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent()); + t.draw(); + t.startDrawingQuads(); + GbufferPrograms.setTranslucencyDeclaration(listTranslucent); + state.apply(); + for (int i = 0; i < count; i++) { + final int base = i * STRIDE; + final float cx = list.getFloat(base); + final float cy = list.getFloat(base + 4); + final float cz = list.getFloat(base + 8); + final float half = list.getFloat(base + 12); + final float u0 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV); + final float v0 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 4); + final float u1 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 8); + final float v1 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 12); + final int color = list.getInt(base + ParticleInstancedAttribs.OFFSET_COLOR); + final int light = (int) list.getFloat(base + ParticleInstancedAttribs.OFFSET_LIGHTMAP) | ((int) list.getFloat(base + ParticleInstancedAttribs.OFFSET_LIGHTMAP + 4) << 16); + + t.setBrightness(light); + t.setColorRGBA(color & 255, (color >> 8) & 255, (color >> 16) & 255, (color >>> 24) & 255); + for (int c = 0; c < ParticleQuadMesh.VERTEX_COUNT; c++) { + final float a = ParticleQuadMesh.cornerA(c); + final float b = ParticleQuadMesh.cornerB(c); + emitCorner(t, cx, cy, cz, half, a, b, a < 0.0f ? u0 : u1, b < 0.0f ? v0 : v1); + } + } + t.draw(); + t.startDrawingQuads(); + } + + private static void emitCorner(Tessellator t, float cx, float cy, float cz, float half, float a, float b, float u, float v) { + final float ah = a * half; + final float bh = b * half; + t.addVertexWithUV(cx + ParticleQuadMesh.offsetX(ah, bh, rotX, rotYZ), cy + ParticleQuadMesh.offsetY(bh, rotXZ), cz + ParticleQuadMesh.offsetZ(ah, bh, rotZ, rotXY), u, v); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleParams.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleParams.java new file mode 100644 index 000000000..9244ddec8 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleParams.java @@ -0,0 +1,15 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +public final class ParticleParams { + + public float centerX; + public float centerY; + public float centerZ; + public float half; + public float u0; + public float v0; + public float u1; + public float v1; + public int colorABGR; + public int brightness; +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuadDecoder.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuadDecoder.java new file mode 100644 index 000000000..c896a154d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuadDecoder.java @@ -0,0 +1,50 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.ffp.ParticleQuadMesh; + +public final class ParticleQuadDecoder { + + private ParticleQuadDecoder() {} + + public static boolean decode(float[] verts, int count, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY, ParticleParams out) { + if (count != 4) return false; + + final float sx = rotX + rotYZ; + final float sy = rotXZ; + final float sz = rotZ + rotXY; + final float denom = sx * sx + sy * sy + sz * sz; + if (denom <= 1.0e-12f) return false; + + final float cx = (verts[0] + verts[10]) * 0.5f; + final float cy = (verts[1] + verts[11]) * 0.5f; + final float cz = (verts[2] + verts[12]) * 0.5f; + final float dx = verts[10] - verts[0]; + final float dy = verts[11] - verts[1]; + final float dz = verts[12] - verts[2]; + final float half = (dx * sx + dy * sy + dz * sz) / (2.0f * denom); + + final float scale = Math.max(Math.abs(cx), Math.max(Math.abs(cy), Math.abs(cz))); + final float tol = 1.0e-5f * (1.0f + Math.abs(half) + scale); + for (int i = 0, o = 0; i < ParticleQuadMesh.VERTEX_COUNT; i++, o += 5) { + final float a = ParticleQuadMesh.cornerA(i) * half; + final float b = ParticleQuadMesh.cornerB(i) * half; + if (Math.abs(verts[o] - (cx + ParticleQuadMesh.offsetX(a, b, rotX, rotYZ))) > tol) return false; + if (Math.abs(verts[o + 1] - (cy + ParticleQuadMesh.offsetY(b, rotXZ))) > tol) return false; + if (Math.abs(verts[o + 2] - (cz + ParticleQuadMesh.offsetZ(a, b, rotZ, rotXY))) > tol) return false; + } + + if (verts[3] != verts[8] || verts[9] != verts[14] || verts[18] != verts[13] || verts[19] != verts[4]) { + return false; + } + + out.centerX = cx; + out.centerY = cy; + out.centerZ = cz; + out.half = half; + out.u0 = verts[3]; + out.v0 = verts[4]; + out.u1 = verts[13]; + out.v1 = verts[14]; + return true; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuads.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuads.java new file mode 100644 index 000000000..8027d7414 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleQuads.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import net.minecraft.client.particle.EntityFX; + +public final class ParticleQuads { + + private ParticleQuads() {} + + public static void vanillaQuad(EntityFX fx, float partialTicks, float scale, ParticleParams out) { + out.half = 0.1F * scale; + center(fx, partialTicks, out); + iconUv(fx, out); + out.colorABGR = packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, fx.particleAlpha); + } + + static void center(EntityFX fx, float partialTicks, ParticleParams out) { + out.centerX = (float) (fx.prevPosX + (fx.posX - fx.prevPosX) * partialTicks - EntityFX.interpPosX); + out.centerY = (float) (fx.prevPosY + (fx.posY - fx.prevPosY) * partialTicks - EntityFX.interpPosY); + out.centerZ = (float) (fx.prevPosZ + (fx.posZ - fx.prevPosZ) * partialTicks - EntityFX.interpPosZ); + } + + static void iconUv(EntityFX fx, ParticleParams out) { + float minU = fx.particleTextureIndexX / 16.0F; + float maxU = minU + 0.0624375F; + float minV = fx.particleTextureIndexY / 16.0F; + float maxV = minV + 0.0624375F; + if (fx.particleIcon != null) { + minU = fx.particleIcon.getMinU(); + maxU = fx.particleIcon.getMaxU(); + minV = fx.particleIcon.getMinV(); + maxV = fx.particleIcon.getMaxV(); + } + out.u0 = maxU; + out.v0 = maxV; + out.u1 = minU; + out.v1 = minV; + } + + static float ramp(int age, int maxAge, float partialTicks) { + return Math.clamp((age + partialTicks) / maxAge * 32.0F, 0.0F, 1.0F); + } + + public static int packColor(float r, float g, float b, float a) { + return (Math.clamp((int) (a * 255.0F), 0, 255) << 24) | (Math.clamp((int) (b * 255.0F), 0, 255) << 16) | (Math.clamp((int) (g * 255.0F), 0, 255) << 8) | Math.clamp((int) (r * 255.0F), 0, 255); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleRenderState.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleRenderState.java new file mode 100644 index 000000000..5e2249768 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/ParticleRenderState.java @@ -0,0 +1,52 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack; +import org.lwjgl.opengl.GL11; + +public final class ParticleRenderState { + + public int texture; + public boolean blend; + public int blendSrc; + public int blendDst; + public int blendSrcAlpha; + public int blendDstAlpha; + public boolean depthMask; + + public void sample() { + texture = GLStateManager.getBoundTextureForServerState(); + blend = GLStateManager.getBlendMode().isEnabled(); + final BlendStateStack blendState = GLStateManager.getBlendState(); + blendSrc = blendState.getSrcRgb(); + blendDst = blendState.getDstRgb(); + blendSrcAlpha = blendState.getSrcAlpha(); + blendDstAlpha = blendState.getDstAlpha(); + depthMask = GLStateManager.getDepthState().isEnabled(); + } + + public void set(ParticleRenderState other) { + texture = other.texture; + blend = other.blend; + blendSrc = other.blendSrc; + blendDst = other.blendDst; + blendSrcAlpha = other.blendSrcAlpha; + blendDstAlpha = other.blendDstAlpha; + depthMask = other.depthMask; + } + + public boolean matches(ParticleRenderState other) { + return texture == other.texture && blend == other.blend && blendSrc == other.blendSrc && blendDst == other.blendDst && blendSrcAlpha == other.blendSrcAlpha && blendDstAlpha == other.blendDstAlpha && depthMask == other.depthMask; + } + + public void apply() { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + if (blend) { + GLStateManager.glEnable(GL11.GL_BLEND); + GLStateManager.glBlendFuncSeparate(blendSrc, blendDst, blendSrcAlpha, blendDstAlpha); + } else { + GLStateManager.glDisable(GL11.GL_BLEND); + } + GLStateManager.glDepthMask(depthMask); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/particles/VanillaParticleDescriptors.java b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/VanillaParticleDescriptors.java new file mode 100644 index 000000000..ee99499e8 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/particles/VanillaParticleDescriptors.java @@ -0,0 +1,135 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import net.minecraft.client.particle.EntityBlockDustFX; +import net.minecraft.client.particle.EntityBreakingFX; +import net.minecraft.client.particle.EntityCloudFX; +import net.minecraft.client.particle.EntityCrit2FX; +import net.minecraft.client.particle.EntityCritFX; +import net.minecraft.client.particle.EntityDiggingFX; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.particle.EntityFireworkOverlayFX; +import net.minecraft.client.particle.EntityFireworkSparkFX; +import net.minecraft.client.particle.EntityFlameFX; +import net.minecraft.client.particle.EntityHeartFX; +import net.minecraft.client.particle.EntityHugeExplodeFX; +import net.minecraft.client.particle.EntityLavaFX; +import net.minecraft.client.particle.EntityNoteFX; +import net.minecraft.client.particle.EntityPortalFX; +import net.minecraft.client.particle.EntityReddustFX; +import net.minecraft.client.particle.EntitySmokeFX; +import net.minecraft.client.particle.EntitySnowShovelFX; +import net.minecraft.client.particle.EntitySpellParticleFX; +import net.minecraft.util.MathHelper; + +public final class VanillaParticleDescriptors { + + private interface BaseScale { + + float of(EntityFX fx); + } + + private interface ScaleFactor { + + float factor(int age, int maxAge, float partialTicks); + } + + private static final ScaleFactor RAMP = ParticleQuads::ramp; + + private static final ScaleFactor FLAME = (age, maxAge, partialTicks) -> { + final float f = (age + partialTicks) / maxAge; + return 1.0F - f * f * 0.5F; + }; + + private static final ScaleFactor LAVA = (age, maxAge, partialTicks) -> { + final float f = (age + partialTicks) / maxAge; + return 1.0F - f * f; + }; + + private static final ScaleFactor PORTAL = (age, maxAge, partialTicks) -> { + float f = (age + partialTicks) / maxAge; + f = 1.0F - f; + f *= f; + return 1.0F - f; + }; + + private static final ParticleDescriptor EMPTY = (fx, partialTicks, out, state) -> false; + + private static final ParticleDescriptor DIGGING = (fx, partialTicks, out, state) -> { + out.half = 0.1F * fx.particleScale; + ParticleQuads.center(fx, partialTicks, out); + out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, 1.0F); + final float jitterU = fx.particleTextureJitterX; + final float jitterV = fx.particleTextureJitterY; + if (fx.particleIcon != null) { + out.u0 = fx.particleIcon.getInterpolatedU(jitterU / 4.0F * 16.0F); + out.u1 = fx.particleIcon.getInterpolatedU((jitterU + 1.0F) / 4.0F * 16.0F); + out.v1 = fx.particleIcon.getInterpolatedV(jitterV / 4.0F * 16.0F); + out.v0 = fx.particleIcon.getInterpolatedV((jitterV + 1.0F) / 4.0F * 16.0F); + } else { + out.u0 = (fx.particleTextureIndexX + jitterU / 4.0F) / 16.0F; + out.u1 = out.u0 + 0.015609375F; + out.v1 = (fx.particleTextureIndexY + jitterV / 4.0F) / 16.0F; + out.v0 = out.v1 + 0.015609375F; + } + return true; + }; + + private static final ParticleDescriptor FIREWORK_OVERLAY = (fx, partialTicks, out, state) -> { + final float t = fx.particleAge + partialTicks - 1.0F; + fx.particleAlpha = 0.6F - t * 0.25F * 0.5F; + ParticleQuads.center(fx, partialTicks, out); + out.half = 7.1F * MathHelper.sin(t * 0.25F * (float) Math.PI); + out.u0 = 0.25F + 0.25F; + out.v0 = 0.125F + 0.25F; + out.u1 = 0.25F; + out.v1 = 0.125F; + out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, fx.particleAlpha); + return true; + }; + + private record BaseScaled(BaseScale base, ScaleFactor factor) implements ParticleDescriptor { + + @Override + public boolean describe(EntityFX fx, float partialTicks, ParticleParams out, ParticleRenderState state) { + fx.particleScale = base.of(fx) * factor.factor(fx.particleAge, fx.particleMaxAge, partialTicks); + ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out); + return true; + } + } + + private static final ParticleDescriptor FIREWORK_SPARK = (fx, partialTicks, out, state) -> { + final int age = fx.particleAge; + final int maxAge = fx.particleMaxAge; + if (((EntityFireworkSparkFX) fx).field_92048_ay && age >= maxAge / 3 && (age + maxAge) / 3 % 2 != 0) return false; + ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out); + return true; + }; + + private VanillaParticleDescriptors() {} + + public static void registerAll() { + registerScaled(EntityFlameFX.class, fx -> ((EntityFlameFX) fx).flameScale, FLAME); + registerScaled(EntityLavaFX.class, fx -> ((EntityLavaFX) fx).lavaParticleScale, LAVA); + registerScaled(EntityPortalFX.class, fx -> ((EntityPortalFX) fx).portalParticleScale, PORTAL); + registerScaled(EntitySmokeFX.class, fx -> ((EntitySmokeFX) fx).smokeParticleScale, RAMP); + registerScaled(EntityCloudFX.class, fx -> ((EntityCloudFX) fx).field_70569_a, RAMP); + registerScaled(EntityCritFX.class, fx -> ((EntityCritFX) fx).initialParticleScale, RAMP); + registerScaled(EntityHeartFX.class, fx -> ((EntityHeartFX) fx).particleScaleOverTime, RAMP); + registerScaled(EntityNoteFX.class, fx -> ((EntityNoteFX) fx).noteParticleScale, RAMP); + registerScaled(EntityReddustFX.class, fx -> ((EntityReddustFX) fx).reddustParticleScale, RAMP); + registerScaled(EntitySnowShovelFX.class, fx -> ((EntitySnowShovelFX) fx).snowDigParticleScale, RAMP); + + ParticleDescriptorRegistry.register(EntitySpellParticleFX.class.getName(), ParticleDescriptorRegistry.VANILLA); + ParticleDescriptorRegistry.register(EntityDiggingFX.class.getName(), DIGGING); + ParticleDescriptorRegistry.register(EntityBlockDustFX.class.getName(), DIGGING); + ParticleDescriptorRegistry.register(EntityBreakingFX.class.getName(), DIGGING); + ParticleDescriptorRegistry.register(EntityFireworkOverlayFX.class.getName(), FIREWORK_OVERLAY); + ParticleDescriptorRegistry.register(EntityCrit2FX.class.getName(), EMPTY); + ParticleDescriptorRegistry.register(EntityHugeExplodeFX.class.getName(), EMPTY); + ParticleDescriptorRegistry.register(EntityFireworkSparkFX.class.getName(), FIREWORK_SPARK); + } + + private static void registerScaled(Class cls, BaseScale base, ScaleFactor factor) { + ParticleDescriptorRegistry.register(cls.getName(), new BaseScaled(base, factor)); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java index 216607c32..14cb91214 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/AngelicaTesrMeshCache.java @@ -8,9 +8,11 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider; import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer; +import com.gtnewhorizons.angelica.rendering.particles.BopParticleDescriptors; import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; -import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform; +import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; @@ -22,13 +24,10 @@ import net.minecraftforge.client.event.TextureStitchEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.function.LongSupplier; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; public final class AngelicaTesrMeshCache { @@ -192,6 +191,9 @@ public final class AngelicaTesrMeshCache { @SubscribeEvent public void onTextureStitchPost(TextureStitchEvent.Post event) { INSTANCE.clear(); + DroppedItemInstancer.clear(); + BopParticleDescriptors.invalidate(); + ShaderGlint.invalidate(); } } @@ -228,7 +230,7 @@ public final class AngelicaTesrMeshCache { return entries.containsKey(key); } - static final class GtnhMeshBackend implements MeshBackend { + public static final class GtnhMeshBackend implements MeshBackend { private DirectTessellator direct; @Override @@ -241,20 +243,10 @@ public final class AngelicaTesrMeshCache { @Override public TemplateBuffer endCaptureToTemplate() { - final int vertexCount = direct.getVertexCount(); - if (vertexCount == 0) { - TessellatorManager.stopCapturingDirect(); - direct = null; - return null; - } - final int drawMode = direct.getDrawMode(); - final VertexFormat format = direct.getVertexFormat(); - final ByteBuffer copy = direct.allocateBufferCopy(); - final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode); - memFree(copy); + final TemplateBuffer template = TemplateCapture.toTemplate(direct); TessellatorManager.stopCapturingDirect(); direct = null; - return new TemplateBuffer(data, vertexCount, drawMode); + return template; } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BakedTransformCapture.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BakedTransformCapture.java new file mode 100644 index 000000000..20d0de831 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BakedTransformCapture.java @@ -0,0 +1,69 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.client.rendering.ModelViewDelta; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.Color4; +import net.minecraft.client.renderer.Tessellator; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector3f; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; + +public final class BakedTransformCapture extends DirectTessellator { + + private final ModelViewDelta delta = new ModelViewDelta(); + private final Matrix4f deltaMatrix = new Matrix4f(); + private final Vector3f scratch = new Vector3f(); + private Matrix4fc transform; + private int firstColor; + private boolean sawRun; + private boolean colorUniform = true; + + public BakedTransformCapture(int capacity) { + super(memAlloc(capacity)); + } + + public void begin() { + TessellatorManager.startCapturingDirect(this); + delta.snapshot(); + sawRun = false; + colorUniform = true; + } + + public TemplateBuffer end() { + final TemplateBuffer template = colorUniform ? TemplateCapture.toTemplate(this) : null; + TessellatorManager.stopCapturingDirect(); + return template; + } + + @Override + protected int interceptDraw(Tessellator tessellator) { + final Color4 color = GLStateManager.getColor(); + final int packed = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + if (!sawRun) { + sawRun = true; + firstColor = packed; + } else if (packed != firstColor) { + colorUniform = false; + } + transform = delta.deltaOrNull(deltaMatrix); + try { + return super.interceptDraw(tessellator); + } finally { + transform = null; + } + } + + @Override + protected long writeVertexData(VertexFormat format, int[] rawBuffer, int rawBufferIndex) { + if (transform != null) { + return format.writeToBuffer0(writePtr, rawBuffer, rawBufferIndex, transform, scratch); + } + return super.writeVertexData(format, rawBuffer, rawBufferIndex); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java index adf1d807e..147bec802 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibility.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.tesr; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; /** Excludes renderers that mix batched model parts with their own draws, which reorders their geometry. */ public final class BatchEligibility { @@ -13,6 +14,10 @@ public final class BatchEligibility { private static boolean allowed; private static long drawsAtStart; private static long expectedDraws; + private static long foreignDraws; + private static long bracketDrawsAtStart; + private static long bracketExpectedAtStart; + private static int bracketDepth; private static int parts; private BatchEligibility() {} @@ -21,6 +26,7 @@ public final class BatchEligibility { if (depth++ > 0) return allowed; drawsAtStart = drawCount; expectedDraws = 0L; + foreignDraws = 0L; parts = 0; allowed = state == SAFE; return allowed; @@ -29,9 +35,13 @@ public final class BatchEligibility { public static byte end(byte state, long drawCount) { if (--depth > 0) return state; allowed = false; + GLSMHooks.resolvePendingProgram(); if (parts == 0) return state; final long foreign = (drawCount - drawsAtStart) - expectedDraws; - if (foreign > 0L) return DENIED; + if (foreign > 0L) { + foreignDraws = foreign; + return DENIED; + } return state == UNKNOWN ? SAFE : state; } @@ -50,9 +60,21 @@ public final class BatchEligibility { } } + public static void beginExpectedDraws(long drawCount) { + if (bracketDepth++ > 0) return; + bracketDrawsAtStart = drawCount; + bracketExpectedAtStart = expectedDraws; + } + + public static void endExpectedDraws(long drawCount) { + if (--bracketDepth > 0) return; + final long alreadyExpected = expectedDraws - bracketExpectedAtStart; + expectedDraws += (drawCount - bracketDrawsAtStart) - alreadyExpected; + } + public static void onStateChange(Object renderer, byte state) { if (state != DENIED) return; final String name = renderer.getClass().getName(); - GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts - excluding it from model part batching", name); + GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts ({} foreign draws) - excluding it from model part batching", name, foreignDraws); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java index f53fa682f..ab1ae041a 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterials.java @@ -1,8 +1,8 @@ package com.gtnewhorizons.angelica.rendering.tesr; -import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.AlphaState; import com.gtnewhorizons.angelica.glsm.states.BlendState; import org.lwjgl.opengl.GL11; @@ -17,21 +17,43 @@ public final class EntityMaterials { static final TesrMaterial ADDITIVE_NO_DEPTH_WRITE = TesrMaterial.builder().additive().noDepthWrite().stream().build(); static final TesrMaterial ADDITIVE_ALPHA = TesrMaterial.builder().additiveAlpha().stream().build(); static final TesrMaterial ADDITIVE_ALPHA_NO_DEPTH_WRITE = TesrMaterial.builder().additiveAlpha().noDepthWrite().stream().build(); + static final TesrMaterial SHADOW = TesrMaterial.builder().translucent().cutout(0.1f).noDepthWrite().unlit().stream().build(); + public static final TesrMaterial DROPPED_ITEM_CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().unfilteredAtlas().build(); + public static final TesrMaterial DROPPED_ITEM_TRANSLUCENT = TesrMaterial.builder().translucent().cutout(0.1f).unfilteredAtlas().stream().build(); + public static final TesrMaterial HELD_BLOCK_CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().build(); + public static final TesrMaterial HELD_BLOCK_TRANSLUCENT = TesrMaterial.builder().translucent().cutout(0.1f).stream().build(); static final TesrMaterial OVERLAY = TesrMaterial.builder().translucent().depthEqual().stream().build(); - static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream() + public static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream() .special(TesrMaterial.SpecialRender.GLINT).build(); + private static final BlendState effectiveBlend = new BlendState(); + private static final AlphaState effectiveAlpha = new AlphaState(); + private EntityMaterials() {} - static TesrMaterial fromCurrentState() { + static TesrMaterial fromCurrentState(boolean texIdentity) { final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled(); - final boolean texAnimated = textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)); - final BlendState blend = GLStateManager.getBlendState(); - return fromState(textured, texAnimated, - GLStateManager.getBlendMode().isEnabled(), blend.getSrcRgb(), blend.getDstRgb(), - GLStateManager.getAlphaTest().isEnabled(), - GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(), - GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled()); + final BlendState blend = GLStateManager.getEffectiveBlendState(effectiveBlend); + final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha); + return fromState(textured, textured && !texIdentity, GLStateManager.isEffectiveBlendEnabled(), blend.getSrcRgb(), blend.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alpha.getFunction(), alpha.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled()); + } + + public static TesrMaterial itemFromCurrentState(boolean unfilteredAtlas) { + final BlendState blend = GLStateManager.getEffectiveBlendState(effectiveBlend); + final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha); + return itemFromState(unfilteredAtlas, GLStateManager.isEffectiveBlendEnabled(), blend.getSrcRgb(), blend.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alpha.getFunction(), alpha.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled()); + } + + static TesrMaterial itemFromState(boolean unfilteredAtlas, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) { + if (depthFunc != GL11.GL_LEQUAL && depthFunc != GL11.GL_LESS) return null; + if (!depthMask) return null; + if (!alphaTest) return null; + if (alphaFunc != GL11.GL_GREATER || Math.abs(alphaRef - 0.1f) > 1.0e-4f) return null; + if (blend) { + if (srcRgb != GL11.GL_SRC_ALPHA || dstRgb != GL11.GL_ONE_MINUS_SRC_ALPHA) return null; + return unfilteredAtlas ? DROPPED_ITEM_TRANSLUCENT : HELD_BLOCK_TRANSLUCENT; + } + return unfilteredAtlas ? DROPPED_ITEM_CUTOUT : HELD_BLOCK_CUTOUT; } static TesrMaterial fromState(boolean textured, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java new file mode 100644 index 000000000..2b87517d1 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/EntityShadowBatcher.java @@ -0,0 +1,169 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; +import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder; +import net.coderbot.iris.Iris; +import net.coderbot.iris.layer.PassOverride; +import net.coderbot.iris.pipeline.PipelineManager; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.vertices.NormI8; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLiving; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL11; + +import java.util.Arrays; + +final class EntityShadowBatcher { + + private static final ResourceLocation SHADOW_TEXTURE = new ResourceLocation("textures/misc/shadow.png"); + private static final int PACKED_UP = NormI8.pack(0f, 1f, 0f, 0f); + + private static final int INITIAL_QUADS = 256; + private static final int INITIAL_MVS = 8; + + private int[] records = new int[INITIAL_QUADS * ShadowQuadMath.RECORD_SIZE]; + private int[] recordMv = new int[INITIAL_QUADS]; + private int count; + private Matrix4f[] mvs = new Matrix4f[INITIAL_MVS]; + private int mvCount; + private final int[] packedScratch = new int[4 * ModelQuadUtil.VERTEX_SIZE]; + private final int[] ijk = new int[6]; + private final Matrix4f mvScratch = new Matrix4f(); + private final Vector3f scratch = new Vector3f(); + private int lastMvGeneration; + private RenderLayer layer; + + private long quads; + private long draws; + + long statQuads() { return quads; } + + long statDraws() { return draws; } + + boolean record(World world, Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, float shadowSize) { + if (world == null || !ModelPartBatcher.INSTANCE.entityPassActive()) return false; + if (Iris.enabled) { + final PipelineManager manager = Iris.getPipelineManagerNullable(); + if (manager != null) { + final WorldRenderingPipeline pipeline = manager.getPipelineNullable(); + if (pipeline != null && pipeline.shouldDisableVanillaEntityShadows()) return false; + } + } + + float size = shadowSize; + if (entity instanceof EntityLiving living) { + size *= living.getRenderSizeModifier(); + if (living.isChild()) { + size *= 0.5F; + } + } + + final double ss = entity.getShadowSize(); + final double ex = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + final double ey = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks + ss; + final double ez = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + final double ox = x - ex; + final double oy = y - ey; + final double oz = z - ez; + + final int cells = ShadowQuadMath.box(ex, ey, ez, size, ijk); + ensureCapacity(cells); + final int mvIndex = currentMvIndex(); + + final int packedLight = GLSMConfig.packedLastBrightness(); + final float[] brightnessTable = world.provider.lightBrightnessTable; + final double yParam = y + ss; + final double oyParam = oy + ss; + + for (int bx = ijk[0]; bx <= ijk[1]; ++bx) { + for (int by = ijk[2]; by <= ijk[3]; ++by) { + for (int bz = ijk[4]; bz <= ijk[5]; ++bz) { + final Block block = world.getBlock(bx, by - 1, bz); + if (block.getMaterial() == Material.air) continue; + final int light = world.getBlockLightValue(bx, by, bz); + if (light <= 3 || !block.renderAsNormalBlock()) continue; + if (ShadowQuadMath.project(records, count * ShadowQuadMath.RECORD_SIZE, x, yParam, z, bx, by, bz, shadowAlpha, size, ox, oyParam, oz, block.getBlockBoundsMinX(), block.getBlockBoundsMaxX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxZ(), brightnessTable[light], packedLight)) { + recordMv[count] = mvIndex; + count++; + } + } + } + } + + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDepthMask(true); + return true; + } + + void flush(AngelicaBufferSource source) { + if (count == 0) { + mvCount = 0; + return; + } + final SegmentedBufferBuilder builder = source.getBuffer(layer(), 0); + for (int i = 0; i < count; i++) { + ShadowQuadMath.expand(packedScratch, records, i * ShadowQuadMath.RECORD_SIZE, PACKED_UP); + builder.addPackedVertices(packedScratch, 4, mvs[recordMv[i]], scratch); + } + draws++; + quads += count; + count = 0; + mvCount = 0; + } + + void reset() { + count = 0; + mvCount = 0; + records = new int[INITIAL_QUADS * ShadowQuadMath.RECORD_SIZE]; + recordMv = new int[INITIAL_QUADS]; + mvs = new Matrix4f[INITIAL_MVS]; + layer = null; + } + + private int currentMvIndex() { + final int mvGen = GLStateManager.getMvGeneration(); + if (mvCount > 0 && mvGen == lastMvGeneration) return mvCount - 1; + lastMvGeneration = mvGen; + mvScratch.set(GLStateManager.getModelViewMatrix()); + if (mvCount > 0 && mvs[mvCount - 1].equals(mvScratch)) return mvCount - 1; + if (mvCount == mvs.length) mvs = Arrays.copyOf(mvs, mvs.length * 2); + Matrix4f slot = mvs[mvCount]; + if (slot == null) { + slot = new Matrix4f(); + mvs[mvCount] = slot; + } + slot.set(mvScratch); + return mvCount++; + } + + private void ensureCapacity(int additionalQuads) { + final int neededQuads = count + additionalQuads; + if (neededQuads * ShadowQuadMath.RECORD_SIZE > records.length) { + records = Arrays.copyOf(records, Math.max(neededQuads * ShadowQuadMath.RECORD_SIZE, records.length * 2)); + } + if (neededQuads > recordMv.length) { + recordMv = Arrays.copyOf(recordMv, Math.max(neededQuads, recordMv.length * 2)); + } + } + + private RenderLayer layer() { + RenderLayer l = layer; + if (l == null) { + l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F); + layer = l; + } + return l; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstanceRing.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstanceRing.java new file mode 100644 index 000000000..432b55b19 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstanceRing.java @@ -0,0 +1,59 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer; +import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; + +import java.nio.ByteBuffer; + +public final class InstanceRing { + + private PersistentStreamingBuffer persistentRing; + private OrphanStreamingBuffer orphanRing; + private boolean initialized; + private boolean usedThisFrame; + private int bufferId; + + public long upload(ByteBuffer data, int stride) { + if (!initialized) { + initialized = true; + persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY); + } + usedThisFrame = true; + if (persistentRing != null) { + final int index = persistentRing.upload(data, stride); + if (index >= 0) { + bufferId = persistentRing.getBufferId(); + return (long) index * stride; + } + } + if (orphanRing == null) orphanRing = new OrphanStreamingBuffer(); + orphanRing.upload(data); + bufferId = orphanRing.getBufferId(); + return 0; + } + + public int bufferId() { + return bufferId; + } + + public void postDraw() { + if (usedThisFrame && persistentRing != null) { + persistentRing.postDraw(); + } + usedThisFrame = false; + } + + public void delete() { + if (persistentRing != null) { + persistentRing.destroy(); + persistentRing = null; + } + if (orphanRing != null) { + orphanRing.destroy(); + orphanRing = null; + } + initialized = false; + usedThisFrame = false; + bufferId = 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java index 0b1c5aa0f..1fb62aa1d 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/InstancedTemplateRenderer.java @@ -4,12 +4,15 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.ffp.CubeInstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.UnitCubeMesh; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; -import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer; -import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer; -import it.unimi.dsi.fastutil.floats.FloatArrayList; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.TexRun; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectIterator; @@ -26,8 +29,6 @@ import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.CO import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; final class InstancedTemplateRenderer { @@ -36,6 +37,8 @@ final class InstancedTemplateRenderer { private static final int TEMPLATE_STRIDE = VERTEX_SIZE * 4; private static final int TEMPLATE_FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT; + private static long bucketEpochSource; + private static final class TemplateMesh { int vao; int vbo; @@ -51,69 +54,58 @@ final class InstancedTemplateRenderer { } private final Reference2ObjectOpenHashMap meshes = new Reference2ObjectOpenHashMap<>(); - private final Reference2ObjectOpenHashMap buckets = new Reference2ObjectOpenHashMap<>(); private final ObjectArrayList bucketPool = new ObjectArrayList<>(); private final ObjectArrayList liveBuckets = new ObjectArrayList<>(); - private final float[] matScratch = new float[16]; - private PersistentStreamingBuffer persistentRing; - private OrphanStreamingBuffer orphanRing; - private boolean ringInitialized; - private boolean ringUsedThisFrame; - private int uploadBufferId; + private final InstanceRing ring; private ByteBuffer staging; - int drawGroup(ObjectArrayList templates, FloatArrayList matrices, IntArrayList lights, IntArrayList colors, int count, long nowMs) { - for (int i = 0; i < count; i++) { - final TemplateBuffer template = templates.get(i); - Bucket bucket = buckets.get(template); - if (bucket == null) { - bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop(); - bucket.mesh = meshFor(template, nowMs); - buckets.put(template, bucket); - liveBuckets.add(bucket); + InstancedTemplateRenderer(InstanceRing ring) { + this.ring = ring; + } + + int drawTemplates(InstanceColumns cols, TexRun run, long nowMs) { + final long epoch = ++bucketEpochSource; + for (TexRun seg = run; seg != null; seg = seg.next) { + for (int i = seg.start, end = seg.end; i < end; i++) { + final TemplateBuffer template = cols.templates.get(i); + final Bucket bucket; + if (template.bucketEpoch == epoch) { + bucket = liveBuckets.get(template.bucketIndex); + } else { + bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop(); + bucket.mesh = meshFor(template, nowMs); + template.bucketEpoch = epoch; + template.bucketIndex = liveBuckets.size(); + liveBuckets.add(bucket); + } + bucket.indices.add(i); } - bucket.indices.add(i); } - staging = MeshBuffer.ensureCapacity(staging, count * InstancedAttribs.STRIDE, false); + staging = MeshBuffer.ensureCapacity(staging, run.parts * InstancedAttribs.STRIDE, false); final long base = memAddress0(staging); long ptr = base; for (int b = 0, n = liveBuckets.size(); b < n; b++) { final IntArrayList indices = liveBuckets.get(b).indices; for (int j = 0, m = indices.size(); j < m; j++) { final int i = indices.getInt(j); - matrices.getElements(i * 16, matScratch, 0, 16); - for (int k = 0; k < 16; k++) { - memPutFloat(ptr + k * 4L, matScratch[k]); - } - memPutInt(ptr + InstancedAttribs.OFFSET_COLOR, colors.getInt(i)); - final int light = lights.getInt(i); - memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP, light & 0xFFFF); - memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP + 4, (light >>> 16) & 0xFFFF); + InstancedAttribs.writeHead(ptr, cols.matrices, i * 16, cols.colors.getInt(i), cols.overlays.getInt(i), cols.infos.getLong(i)); + InstancedAttribs.writeLightmap(ptr + InstancedAttribs.OFFSET_LIGHTMAP, cols.lights.getInt(i)); ptr += InstancedAttribs.STRIDE; } } - staging.position(0); - staging.limit((int) (ptr - base)); - final long ringBase = uploadInstances(staging); - staging.clear(); + final long ringBase = uploadStaging(base, ptr, InstancedAttribs.STRIDE); int draws = 0; long recordOffset = ringBase; - final int ringId = uploadBufferId; - final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler; - if (extHandler != null && extHandler.wantsExtended()) { - FfpExtendedAttribs.setNeutralCurrentValues(); - } - GLStateManager.instancedFfpDrawActive = true; + neutralizeExtendedAttribs(); + GLStateManager.ffpInstancing = Instancing.TEMPLATE; for (int b = 0, n = liveBuckets.size(); b < n; b++) { final Bucket bucket = liveBuckets.get(b); final TemplateMesh mesh = bucket.mesh; - GLStateManager.glBindVertexArray(mesh.vao); - VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS); - GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ringId); - pointInstanceAttribs(recordOffset); + bindRingTo(mesh.vao, TEMPLATE_FLAGS); + InstancedAttribs.pointTemplate(recordOffset); GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLStateManager.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, bucket.indices.size()); draws++; @@ -122,41 +114,66 @@ final class InstancedTemplateRenderer { bucket.mesh = null; bucketPool.add(bucket); } - GLStateManager.instancedFfpDrawActive = false; + GLStateManager.ffpInstancing = Instancing.NONE; GLStateManager.glBindVertexArray(0); liveBuckets.clear(); - buckets.clear(); return draws; } - private static void pointInstanceAttribs(long base) { - for (int c = 0; c < 4; c++) { - GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_MATRIX_COL0 + c, 4, GL11.GL_FLOAT, false, - InstancedAttribs.STRIDE, base + c * 16L); - } - GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true, - InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_COLOR); - GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false, - InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_LIGHTMAP); - } - - private long uploadInstances(ByteBuffer data) { - if (!ringInitialized) { - ringInitialized = true; - persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY); - } - ringUsedThisFrame = true; - if (persistentRing != null) { - final int index = persistentRing.upload(data, InstancedAttribs.STRIDE); - if (index >= 0) { - uploadBufferId = persistentRing.getBufferId(); - return (long) index * InstancedAttribs.STRIDE; + void drawCubes(InstanceColumns cols, TexRun run) { + staging = MeshBuffer.ensureCapacity(staging, run.instances * CubeInstancedAttribs.STRIDE, false); + final long base = memAddress0(staging); + long ptr = base; + for (TexRun seg = run; seg != null; seg = seg.next) { + for (int i = seg.start, end = seg.end; i < end; i++) { + final int off = i * 16; + final CubeParams[] partCubes = cols.cubes.get(i); + final float scale = cols.scales.getFloat(i); + final int color = cols.colors.getInt(i); + final int light = cols.lights.getInt(i); + final int overlay = cols.overlays.getInt(i); + final long info = cols.infos.getLong(i); + for (int p = 0, n = partCubes.length; p < n; p++) { + final CubeParams cube = partCubes[p]; + cube.writeRows(ptr, cols.matrices, off, scale); + InstancedAttribs.writeTail(ptr, color, overlay, info); + InstancedAttribs.writeLightmap(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE, light); + cube.writeTexture(ptr); + ptr += CubeInstancedAttribs.STRIDE; + } } } - if (orphanRing == null) orphanRing = new OrphanStreamingBuffer(); - orphanRing.upload(data); - uploadBufferId = orphanRing.getBufferId(); - return 0; + final long ringBase = uploadStaging(base, ptr, CubeInstancedAttribs.STRIDE); + + neutralizeExtendedAttribs(); + bindRingTo(UnitCubeMesh.vao(), UnitCubeMesh.VERTEX_FLAGS); + CubeInstancedAttribs.pointInstanceAttribs(ringBase); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.ffpInstancing = Instancing.CUBE; + GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, run.instances); + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + } + + private long uploadStaging(long base, long end, int stride) { + staging.position(0); + staging.limit((int) (end - base)); + final long ringBase = ring.upload(staging, stride); + staging.clear(); + return ringBase; + } + + private void bindRingTo(int vao, int vertexFlags) { + GLStateManager.glBindVertexArray(vao); + VAOManager.setCurrentVertexFlags(vertexFlags); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ring.bufferId()); + } + + private static void neutralizeExtendedAttribs() { + final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler; + if (extHandler != null && extHandler.wantsExtended()) { + FfpExtendedAttribs.setNeutralCurrentValues(); + } } private TemplateMesh meshFor(TemplateBuffer template, long nowMs) { @@ -196,10 +213,7 @@ final class InstancedTemplateRenderer { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } - for (int loc = InstancedAttribs.LOC_MATRIX_COL0; loc <= InstancedAttribs.LOC_LIGHTMAP; loc++) { - GLStateManager.glEnableVertexAttribArray(loc); - GLStateManager.glVertexAttribDivisor(loc, 1); - } + InstancedAttribs.enableHeadArrays(); VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS); GLStateManager.glBindVertexArray(0); return mesh; @@ -225,10 +239,7 @@ final class InstancedTemplateRenderer { } void endFrame() { - if (ringUsedThisFrame && persistentRing != null) { - persistentRing.postDraw(); - } - ringUsedThisFrame = false; + ring.postDraw(); } void sweep(long now) { @@ -247,6 +258,10 @@ final class InstancedTemplateRenderer { delete(mesh); } meshes.clear(); + liveBuckets.clear(); + bucketPool.clear(); + staging = null; + UnitCubeMesh.delete(); } private static void delete(TemplateMesh mesh) { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCapture.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCapture.java new file mode 100644 index 000000000..ee6c0ab91 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCapture.java @@ -0,0 +1,46 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.UnitCubeMesh; +import net.minecraft.client.model.PositionTextureVertex; +import net.minecraft.client.model.TexturedQuad; + +public final class ModelBoxCapture { + + private static final float EPSILON = 1.0e-4f; + + private ModelBoxCapture() {} + + public static CubeParams capture(TexturedQuad[] quads, float texWidth, float texHeight, boolean mirror, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate) { + if (quads == null || quads.length != UnitCubeMesh.FACE_COUNT) return null; + final CubeParams params = CubeParams.of(texWidth, texHeight, mirror, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + if (params == null) return null; + + final float lowX = mirror ? params.minX() + params.spanX() : params.minX(); + final float spanX = mirror ? -params.spanX() : params.spanX(); + for (int face = 0; face < UnitCubeMesh.FACE_COUNT; face++) { + final TexturedQuad quad = quads[face]; + if (quad == null || quad.vertexPositions == null || quad.vertexPositions.length != 4) return null; + final int[] corners = UnitCubeMesh.FACES[face].corners(); + final UnitCubeMesh.Net net = UnitCubeMesh.FACES[face].net(); + for (int corner = 0; corner < 4; corner++) { + final PositionTextureVertex vertex = quad.vertexPositions[mirror ? 3 - corner : corner]; + if (vertex == null || vertex.vector3D == null) return null; + final float[] unit = UnitCubeMesh.CORNERS[corners[corner]]; + if (!near((float) vertex.vector3D.xCoord, lowX + unit[0] * spanX) || !near((float) vertex.vector3D.yCoord, params.minY() + unit[1] * params.spanY()) || !near((float) vertex.vector3D.zCoord, params.minZ() + unit[2] * params.spanZ())) { + return null; + } + final int u = texU + net.u(corner).texels(sizeX, sizeZ); + final int v = texV + net.v(corner).texels(sizeY, sizeZ); + if (!near(vertex.texturePositionX, u / texWidth) || !near(vertex.texturePositionY, v / texHeight)) { + return null; + } + } + } + return params; + } + + private static boolean near(float a, float b) { + return Math.abs(a - b) < EPSILON; + } +} 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 953375112..10c591c69 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ModelPartBatcher.java @@ -1,7 +1,6 @@ package com.gtnewhorizons.angelica.rendering.tesr; import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.api.tesr.ModelPartMeshBuilder; @@ -11,12 +10,17 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.states.AlphaState; import com.gtnewhorizons.angelica.glsm.states.BlendState; import com.gtnewhorizons.angelica.glsm.states.Color4; import com.gtnewhorizons.angelica.glsm.states.PolygonState; +import com.gtnewhorizons.angelica.mixins.interfaces.ModelBoxData; import com.gtnewhorizons.angelica.profiling.BailClassCounts; +import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; @@ -31,7 +35,9 @@ import net.coderbot.iris.uniforms.CapturedRenderingState; import net.minecraft.client.model.ModelBox; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; @@ -50,7 +56,6 @@ public final class ModelPartBatcher { MATERIAL("tesr.bail.material"), TEXTURE("tesr.bail.texture"), TEMPLATE("tesr.bail.template"), - HURT_FLASH("tesr.bail.hurtFlash"), FOREIGN_PROGRAM("tesr.bail.foreignProgram"), MIXED_RENDERER("tesr.bail.mixedRenderer"); @@ -64,7 +69,10 @@ public final class ModelPartBatcher { private static final long SWEEP_INTERVAL_MS = 5_000L; + private static final Tracy.ZoneId Z_ENTITY_LAYER_LOOP = Tracy.zoneId("entityLayerLoop", Tracy.COLOR_CLIENT); + private final AngelicaBufferSource bufferSource = new AngelicaBufferSource(); + private final EntityShadowBatcher shadows = new EntityShadowBatcher(); private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource); private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource); private RetainedTesrGroups activeGroups = groups; @@ -75,6 +83,9 @@ public final class ModelPartBatcher { private final Matrix4f texMatrixScratch = new Matrix4f(); private int lastMvGeneration; private boolean mvCaptured; + private int texGeneration; + private boolean texCaptured; + private boolean texIdentity; private boolean active; private Mode mode = Mode.BLOCK_ENTITIES; private boolean instancedThisCycle; @@ -88,7 +99,13 @@ public final class ModelPartBatcher { public long statParts() { return parts; } public long statLiveFallbacks() { return liveFallbacks; } + public long statInstancedDraws() { return groups.instancedDraws + shadowGroups.instancedDraws; } + public long statInstancedInstances() { return groups.instancedInstances + shadowGroups.instancedInstances; } + public long statCubeInstances() { return groups.cubeInstances + shadowGroups.cubeInstances; } + public long statTexMatrixRuns() { return groups.texMatrixRuns + shadowGroups.texMatrixRuns; } public long statBail(BailReason reason) { return bails[reason.ordinal()]; } + public long statShadowQuads() { return shadows.statQuads(); } + public long statShadowDraws() { return shadows.statDraws(); } private void bail(BailReason reason) { bails[reason.ordinal()]++; @@ -96,10 +113,10 @@ public final class ModelPartBatcher { private static final class PartTemplate { TemplateBuffer template; + CubeParams[] cubes; float scale; long lastUsedMs; boolean emptyVanillaPart; - boolean forceStream; } private final Reference2ObjectOpenHashMap templates = new Reference2ObjectOpenHashMap<>(); @@ -110,13 +127,15 @@ public final class ModelPartBatcher { PassOverride pass; float offsetFactor; float offsetUnits; + int glintSlot; - LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) { + LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) { this.texture = texture; this.material = material; this.pass = pass; this.offsetFactor = offsetFactor; this.offsetUnits = offsetUnits; + this.glintSlot = glintSlot; return this; } @@ -126,7 +145,8 @@ public final class ModelPartBatcher { return Objects.equals(texture, other.texture) && Objects.equals(material, other.material) && Objects.equals(pass, other.pass) && Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor) - && Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits); + && Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits) + && glintSlot == other.glintSlot; } @Override @@ -134,6 +154,7 @@ public final class ModelPartBatcher { int h = (Objects.hashCode(texture) * 31 + Objects.hashCode(material)) * 31 + Objects.hashCode(pass); h = h * 31 + Float.floatToIntBits(offsetFactor); h = h * 31 + Float.floatToIntBits(offsetUnits); + h = h * 31 + glintSlot; return h; } } @@ -145,16 +166,24 @@ public final class ModelPartBatcher { private PassOverride lastLayerPass; private float lastLayerOffsetFactor; private float lastLayerOffsetUnits; + private int lastLayerGlintSlot; private RenderLayer lastLayer; private static ResourceLocation lastBoundLocation; private static int lastBoundGlId = -1; + private static int lastBoundGlintSlot = ShaderGlint.NO_TINT; private ModelPartBatcher() {} + public static void onTextureSwap(int glId, int glintSlot) { + lastBoundGlId = glId; + lastBoundGlintSlot = glintSlot; + } + public static void onTextureBind(ResourceLocation location, int glId) { lastBoundLocation = location; lastBoundGlId = glId; + lastBoundGlintSlot = ShaderGlint.NO_TINT; } public void begin(Mode mode) { @@ -172,16 +201,17 @@ public final class ModelPartBatcher { return; } active = true; + final long nowMs = System.currentTimeMillis(); mvCaptured = false; + texCaptured = false; activeGroups = shadow ? shadowGroups : groups; bufferSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY); activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline); - final long now = System.currentTimeMillis(); - if (now - lastSweepMs >= SWEEP_INTERVAL_MS) { - lastSweepMs = now; - groups.sweep(now); - shadowGroups.sweep(now); - sweepTemplates(now); + if (nowMs - lastSweepMs >= SWEEP_INTERVAL_MS) { + lastSweepMs = nowMs; + groups.sweep(nowMs); + shadowGroups.sweep(nowMs); + sweepTemplates(nowMs); } } @@ -189,25 +219,18 @@ public final class ModelPartBatcher { if (!active) return; active = false; if (shadow) { - bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups); - bufferSource.endBatch(activeGroups); - if (instancedThisCycle) { - TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame(); + drawBatches(); + } else { + final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive(); + final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop; + if (wrapEntities) GbufferPrograms.beginEntities(); + else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary(); + try { + shadows.flush(bufferSource); + drawBatches(); + } finally { + if (wrapEntities) GbufferPrograms.endEntities(); } - if (!TesrBatchRenderer.INSTANCE.hasPendingGeometry()) { - BatchingFontRenderer.flushDeferredText(); - } - return; - } - final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive(); - final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop; - if (wrapEntities) GbufferPrograms.beginEntities(); - else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary(); - try { - bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups); - bufferSource.endBatch(activeGroups); - } finally { - if (wrapEntities) GbufferPrograms.endEntities(); } if (instancedThisCycle) { TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame(); @@ -217,10 +240,32 @@ public final class ModelPartBatcher { } } + private void drawBatches() { + if (Tracy.ENABLED) Tracy.beginZone(Z_ENTITY_LAYER_LOOP); + try { + bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups); + bufferSource.endBatch(activeGroups); + } finally { + if (Tracy.ENABLED) Tracy.endZone(); + } + } + public boolean isActive() { return active; } + public boolean entityPassActive() { + return active && mode == Mode.ENTITIES && !shadow; + } + + public boolean isShadowPass() { + return active && shadow; + } + + public static boolean recordShadow(World world, Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, float shadowSize) { + return INSTANCE.shadows.record(world, entity, x, y, z, shadowAlpha, partialTicks, shadowSize); + } + public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { final ModelPartBatcher r = INSTANCE; if (!r.active) { @@ -244,15 +289,6 @@ public final class ModelPartBatcher { } private boolean queuePart(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { - if (shaderPipeline != null) { - if (GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) { - bail(BailReason.FOREIGN_PROGRAM); - return false; - } - } else if (GLStateManager.getOverlayA() != 0.0f) { - bail(BailReason.HURT_FLASH); - return false; - } final PartTemplate entry = templateFor(part, scale, builder); if (entry.emptyVanillaPart) { return true; @@ -260,7 +296,19 @@ public final class ModelPartBatcher { if (shadow && isDepthEqualDecalState()) { return true; } - final TesrMaterial material = EntityMaterials.fromCurrentState(); + return queueTemplate(entry.template, entry.cubes, scale, null); + } + + public boolean queueTemplate(TemplateBuffer template, TesrMaterial material) { + return queueTemplate(template, null, 1.0f, material); + } + + private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, float scale, TesrMaterial explicitMaterial) { + if (shaderPipeline != null && GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) { + bail(BailReason.FOREIGN_PROGRAM); + return false; + } + final TesrMaterial material = explicitMaterial != null ? explicitMaterial : EntityMaterials.fromCurrentState(unitTexIdentity()); if (material == null) { bail(BailReason.MATERIAL); if (Tracy.ENABLED) { @@ -283,35 +331,26 @@ public final class ModelPartBatcher { return false; } } - final TemplateBuffer template = entry.template; if (template == null) { bail(BailReason.TEMPLATE); if (Tracy.ENABLED) BailClassCounts.TEMPLATE.add(TesrAttribution.currentRenderable); return false; } - Matrix4f texMatrix = null; - if (texture != null) { - final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0); - if (!MatrixHelper.isIdentity(unitMatrix)) { - texMatrix = texMatrixScratch.set(unitMatrix); - if (material.isDepthEqual()) { - entry.forceStream = true; - } - } - } + final Matrix4f texMatrix = texture != null && !unitTexIdentity() ? texMatrixScratch : null; final PassOverride pass = shaderPipeline != null ? PassOverride.capture() : PassOverride.NONE; final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL); final PolygonState polygon = GLStateManager.getPolygonState(); final float offsetFactor = offset ? polygon.getOffsetFactor() : 0.0f; final float offsetUnits = offset ? polygon.getOffsetUnits() : 0.0f; - final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits); + final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT; + final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot); // Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id - final int entityId = mode == Mode.ENTITIES || pass.isEntityPhase() - ? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()) - : CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); + final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); final Color4 color = GLStateManager.getColor(); - final int colorABGR = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + final int colorABGR = AngelicaBufferSource.packAbgr(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + final int overlayABGR = shaderPipeline != null ? AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()) : AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA()); + final long entityInfo = shaderPipeline != null ? InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem()) : 0L; final int packedLight = GLSMConfig.packedLastBrightness(); final int mvGen = GLStateManager.getMvGeneration(); if (!mvCaptured || mvGen != lastMvGeneration) { @@ -319,29 +358,43 @@ public final class ModelPartBatcher { lastMvGeneration = mvGen; mvCaptured = true; } - activeGroups.queue(template, layer, material, modelView, packedLight, colorABGR, entityId, texMatrix, entry.forceStream); + activeGroups.queue(template, cubes, scale, layer, material, modelView, packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix); parts++; return true; } private final ReferenceOpenHashSet> loggedMaterialBails = new ReferenceOpenHashSet<>(); + private final BlendState bailBlend = new BlendState(); + private final AlphaState bailAlpha = new AlphaState(); private void logMaterialBail() { final Class cls = TesrAttribution.currentRenderable; if (cls == null || !loggedMaterialBails.add(cls)) return; final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled(); - final BlendState blendState = GLStateManager.getBlendState(); - AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}", - cls.getName(), shadow, textured, - textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)), - GLStateManager.getBlendMode().isEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(), - GLStateManager.getAlphaTest().isEnabled(), - GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(), - GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled()); + final BlendState blendState = GLStateManager.getEffectiveBlendState(bailBlend); + final AlphaState alphaState = GLStateManager.getEffectiveAlphaState(bailAlpha); + AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}", cls.getName(), shadow, textured, textured && !unitTexIdentity(), GLStateManager.isEffectiveBlendEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alphaState.getFunction(), alphaState.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled()); + } + + static int groupId(boolean piped, boolean entityPhase, int entityId, int blockEntityId) { + if (!piped) return 0; + return entityPhase ? entityId : blockEntityId; + } + + private boolean unitTexIdentity() { + final int generation = GLStateManager.getTexMatrixGeneration(); + if (!texCaptured || generation != texGeneration) { + final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0); + texIdentity = MatrixHelper.isIdentity(unitMatrix); + if (!texIdentity) texMatrixScratch.set(unitMatrix); + texGeneration = generation; + texCaptured = true; + } + return texIdentity; } private static boolean isDepthEqualDecalState() { - return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.getDepthState().isEnabled(); + return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.isEffectiveDepthMaskEnabled(); } private PartTemplate templateFor(ModelRenderer part, float scale, ModelPartMeshBuilder builder) { @@ -357,6 +410,7 @@ public final class ModelPartBatcher { final PartTemplate entry = reuse != null ? reuse : new PartTemplate(); entry.scale = scale; entry.template = null; + entry.cubes = null; entry.emptyVanillaPart = false; final List boxes = part.cubeList; if (builder != null) { @@ -372,6 +426,7 @@ public final class ModelPartBatcher { boxes.get(i).render(tess, scale); } entry.template = captureBackend.endCaptureToTemplate(); + captureCubes(entry, boxes); } else { entry.emptyVanillaPart = part.getClass() == ModelRenderer.class; } @@ -379,21 +434,35 @@ public final class ModelPartBatcher { return entry; } - private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) { + private static void captureCubes(PartTemplate entry, List boxes) { + final int n = boxes.size(); + CubeParams[] cubes = null; + for (int i = 0; i < n; i++) { + if (!(boxes.get(i) instanceof ModelBoxData data)) return; + final CubeParams params = data.angelica$cubeParams(); + if (params == null) return; + if (cubes == null) cubes = new CubeParams[n]; + cubes[i] = params; + } + entry.cubes = cubes; + } + + private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) { if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass) - && offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits) { + && offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && glintSlot == lastLayerGlintSlot) { return lastLayer; } - RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits)); + RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot)); if (layer == null) { - layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits); - layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits), layer); + layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot); + layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot), layer); } lastLayerTexture = texture; lastLayerMaterial = material; lastLayerPass = pass; lastLayerOffsetFactor = offsetFactor; lastLayerOffsetUnits = offsetUnits; + lastLayerGlintSlot = glintSlot; lastLayer = layer; return layer; } @@ -409,11 +478,21 @@ public final class ModelPartBatcher { } public void clear() { + shadows.reset(); groups.clear(); shadowGroups.clear(); templates.clear(); bufferSource.freeBuffers(); active = false; + shaderPipeline = null; + layers.clear(); + scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT); + lastLayerTexture = null; + lastLayerMaterial = null; + lastLayerPass = null; + lastLayer = null; + loggedMaterialBails.clear(); + lastBoundLocation = null; } public String getDebugString() { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java index daf6efdcd..a69b58de4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroups.java @@ -4,21 +4,24 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import it.unimi.dsi.fastutil.floats.FloatArrayList; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; -import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder; -import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.minecraft.util.ResourceLocation; import org.joml.Matrix4f; +import org.joml.Matrix4fc; import org.joml.Vector3f; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.function.LongSupplier; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; @@ -29,6 +32,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { static final int DEMOTE_AFTER_STABLE_FRAMES = 4; static final long IDLE_RESET_FRAMES = 100; static final long GROUP_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS; + static final int MERGE_SCAN = 4; private static final Tracy.ZoneId Z_TESR_REBUILD = Tracy.zoneId("tesrRebuild", Tracy.COLOR_CLIENT); @@ -42,6 +46,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { private final Matrix4f drawMV = new Matrix4f(); private final Matrix4f savedMV = new Matrix4f(); private boolean mvSaved; + private final Matrix4f savedTexMatrix = new Matrix4f(); + private boolean texApplied; private final float[] matScratch = new float[16]; private double camX, camY, camZ; private long frameMark; @@ -52,19 +58,75 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { long streamedInstances; long instancedDraws; long instancedInstances; + long cubeInstances; + long texMatrixRuns; private InstancedTemplateRenderer instanced; private boolean instancedActive; - private DeferredWorldRenderingPipeline deferred; + private TesrInstancingPipeline deferred; private final MeshBuffer fallbackMesh = new MeshBuffer(); private ByteBuffer fallbackScratch; + static final class TexRun { + final Matrix4f matrix = new Matrix4f(); + boolean identity; + int start, end; + int parts, instances; + TexRun next, last; + } + + static final class InstanceColumns { + final ObjectArrayList templates = new ObjectArrayList<>(); + final ObjectArrayList cubes = new ObjectArrayList<>(); + final FloatArrayList scales = new FloatArrayList(); + final IntArrayList lights = new IntArrayList(); + final IntArrayList colors = new IntArrayList(); + final IntArrayList overlays = new IntArrayList(); + final LongArrayList infos = new LongArrayList(); + final ObjectArrayList runs = new ObjectArrayList<>(); + float[] matrices = new float[16 * 64]; + int size; + + void add(TemplateBuffer templateOrNull, Matrix4fc mv, int light, int color, int overlay, long info) { + final int base = size * 16; + if (base + 16 > matrices.length) { + matrices = Arrays.copyOf(matrices, matrices.length << 1); + } + mv.get(matrices, base); + if (templateOrNull != null) templates.add(templateOrNull); + lights.add(light); + colors.add(color); + overlays.add(overlay); + infos.add(info); + size++; + } + + void addCubes(TemplateBuffer templateOrNull, CubeParams[] cubeParams, float scale, Matrix4fc mv, int light, int color, int overlay, long info) { + cubes.add(cubeParams); + scales.add(scale); + add(templateOrNull, mv, light, color, overlay, info); + } + + void clear() { + templates.clear(); + cubes.clear(); + scales.clear(); + lights.clear(); + colors.clear(); + overlays.clear(); + infos.clear(); + runs.clear(); + size = 0; + } + } + static final class Group { final RenderLayer layer; final TesrMaterial material; final int blockEntityId; final boolean opaque; final boolean stream; + final boolean mergeRuns; Class renderableClass; int rebuildsWindow; long anchorX, anchorY, anchorZ; @@ -73,15 +135,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { long lastUsedMs; int entityColor; - final ObjectArrayList instTemplates = new ObjectArrayList<>(); - final FloatArrayList instMatrices = new FloatArrayList(); - final IntArrayList instLights = new IntArrayList(); - final IntArrayList instColors = new IntArrayList(); + final InstanceColumns templateColumns = new InstanceColumns(); + final InstanceColumns cubeColumns = new InstanceColumns(); final ObjectArrayList instTexMatrices = new ObjectArrayList<>(); private final ObjectArrayList texMatrixPool = new ObjectArrayList<>(); private int texMatrixPoolUsed; + private final ObjectArrayList runPool = new ObjectArrayList<>(); + private int runPoolUsed; long hashAcc; - int count; long builtHash; int builtCount = -1; @@ -106,13 +167,49 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { instTexMatrices.add(texMatrixPool.get(texMatrixPoolUsed++).set(src)); } + TexRun openOrExtendRun(InstanceColumns cols, Matrix4f texMatrix) { + final ObjectArrayList list = cols.runs; + final int part = cols.size; + final boolean identity = texMatrix == null; + final int size = list.size(); + final int floor = Math.max(0, mergeRuns ? size - MERGE_SCAN : size - 1); + for (int i = size - 1; i >= floor; i--) { + final TexRun head = list.get(i); + if (head.identity != identity || (!identity && !head.matrix.equals(texMatrix))) continue; + if (head.last.end != part) { + final TexRun segment = pooledRun(part); + head.last.next = segment; + head.last = segment; + } + return head; + } + final TexRun head = pooledRun(part); + head.identity = identity; + if (!identity) head.matrix.set(texMatrix); + list.add(head); + return head; + } + + private TexRun pooledRun(int part) { + if (runPoolUsed == runPool.size()) { + runPool.add(new TexRun()); + } + final TexRun run = runPool.get(runPoolUsed++); + run.start = part; + run.end = part; + run.parts = 0; + run.instances = 0; + run.next = null; + run.last = run; + return run; + } + void clearInstances() { - instTemplates.clear(); - instMatrices.clear(); - instLights.clear(); - instColors.clear(); + templateColumns.clear(); + cubeColumns.clear(); instTexMatrices.clear(); texMatrixPoolUsed = 0; + runPoolUsed = 0; } Group(RenderLayer layer, TesrMaterial material, int blockEntityId) { @@ -121,12 +218,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { this.blockEntityId = blockEntityId; this.opaque = material.transparency() == TesrMaterial.Transparency.OPAQUE; this.stream = material.isStream(); + this.mergeRuns = material.isDepthEqual() && material.isNoDepthWrite(); this.streaming = stream; } } private final Reference2ObjectOpenHashMap>> groups = new Reference2ObjectOpenHashMap<>(); private final Reference2ObjectOpenHashMap> byLayer = new Reference2ObjectOpenHashMap<>(); + private Group lastGroup; RetainedTesrGroups(AngelicaBufferSource source) { this(source, System::currentTimeMillis); @@ -145,7 +244,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { beginPass(base, camX, camY, camZ, instancedRenderer, null); } - void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, DeferredWorldRenderingPipeline deferred) { + void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) { baseMV.set(base); baseMVInv.set(base).invert(); this.camX = camX; @@ -158,23 +257,28 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { nowMs = clock.getAsLong(); } - private Group groupFor(RenderLayer layer, TesrMaterial material, int blockEntityId) { - Reference2ObjectOpenHashMap> byMaterial = groups.get(layer); - if (byMaterial == null) { - byMaterial = new Reference2ObjectOpenHashMap<>(); - groups.put(layer, byMaterial); - } - Int2ObjectOpenHashMap byId = byMaterial.get(material); - if (byId == null) { - byId = new Int2ObjectOpenHashMap<>(); - byMaterial.put(material, byId); - } - Group group = byId.get(blockEntityId); - if (group == null) { - group = new Group(layer, material, blockEntityId); - group.lastUsedMs = nowMs; - byId.put(blockEntityId, group); - byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group); + private Group groupFor(RenderLayer layer, TesrMaterial material, int id) { + final int key = instanceableMaterial(material) ? 0 : id; + Group group = lastGroup; + if (group == null || group.layer != layer || group.material != material || group.blockEntityId != key) { + Reference2ObjectOpenHashMap> byMaterial = groups.get(layer); + if (byMaterial == null) { + byMaterial = new Reference2ObjectOpenHashMap<>(); + groups.put(layer, byMaterial); + } + Int2ObjectOpenHashMap byId = byMaterial.get(material); + if (byId == null) { + byId = new Int2ObjectOpenHashMap<>(); + byMaterial.put(material, byId); + } + group = byId.get(key); + if (group == null) { + group = new Group(layer, material, key); + group.lastUsedMs = nowMs; + byId.put(key, group); + byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group); + } + lastGroup = group; } if (group.renderableClass == null) { group.renderableClass = TesrAttribution.currentRenderable; @@ -186,8 +290,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { promote(groupFor(layer, material, blockEntityId)); } - void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int blockEntityId, Matrix4f texMatrix, boolean forceStream) { - final Group group = groupFor(layer, material, blockEntityId); + void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix) { + queue(template, null, 1.0f, layer, material, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, id, texMatrix); + } + + void queue(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix) { + final Group group = groupFor(layer, material, id); if (group.frameMark != frameMark) { if (frameMark - group.frameMark > IDLE_RESET_FRAMES) { group.streaming = group.stream; @@ -210,8 +318,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } group.frameMark = frameMark; group.lastUsedMs = nowMs; - group.entityColor = SegmentedBufferBuilder.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); - group.count = 0; + group.entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); group.hashAcc = 0; group.clearInstances(); if (!group.anchored || TesrAnchorMath.shouldReanchor(camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ)) { @@ -224,18 +331,25 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { source.declareUse(layer); } if (group.stream) { - final boolean instanceable = !forceStream && instancedActive && (deferred == null || material.shader() == null); - if (instanceable && (texMatrix == null || template.drawMode != layer.getDrawMode())) { - group.count++; - group.instTemplates.add(template); - currentMV.get(matScratch); - group.instMatrices.addElements(group.instMatrices.size(), matScratch); - group.instLights.add(packedLight); - group.instColors.add(colorABGR); + final boolean instanceable = instanceable(group); + if (instanceable && cubes != null) { + final TexRun run = group.openOrExtendRun(group.cubeColumns, texMatrix); + group.cubeColumns.addCubes(deferred != null ? template : null, cubes, scale, currentMV, packedLight, colorABGR, overlayABGR, entityInfo); + run.last.end = group.cubeColumns.size; + run.parts++; + run.instances += cubes.length; + return; + } + if (instanceable) { + final TexRun run = group.openOrExtendRun(group.templateColumns, texMatrix); + group.templateColumns.add(template, currentMV, packedLight, colorABGR, overlayABGR, entityInfo); + run.last.end = group.templateColumns.size; + run.parts++; + run.instances++; return; } if (template.drawMode == layer.getDrawMode()) { - source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); + source.getBuffer(layer, id).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); streamedInstances++; return; } @@ -248,17 +362,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } if (group.streaming && template.drawMode == layer.getDrawMode()) { group.frameHash += hash; - source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); + source.getBuffer(layer, id).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix); streamedInstances++; return; } group.hashAcc += hash; - group.count++; - group.instTemplates.add(template); - scratchMat.get(matScratch); - group.instMatrices.addElements(group.instMatrices.size(), matScratch); - group.instLights.add(packedLight); - group.instColors.add(colorABGR); + group.templateColumns.add(template, scratchMat, packedLight, colorABGR, overlayABGR, entityInfo); group.addTexMatrix(texMatrix); } @@ -267,8 +376,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { final ObjectArrayList list = byLayer.get(layer); if (list == null) return false; for (int i = 0, n = list.size(); i < n; i++) { - final Group group = list.get(i); - if (group.frameMark == frameMark && group.count > 0) return true; + if (live(list.get(i))) return true; } return false; } @@ -277,101 +385,222 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { public void drawLayer(RenderLayer layer) { final ObjectArrayList list = byLayer.get(layer); if (list == null) return; - boolean variantResolved = false; - boolean variantAvailable = false; - boolean variantBound = false; - for (int i = 0, n = list.size(); i < n; i++) { - final Group group = list.get(i); - if (group.frameMark != frameMark || group.count == 0) continue; - if (group.stream && instancedActive && (deferred == null || group.material.shader() == null)) { - restoreMV(); - if (deferred == null) { - instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs); - instancedInstances += group.count; - continue; - } - if (!variantResolved) { - variantResolved = true; - variantAvailable = deferred.hasTesrInstancedVariant(); - } - if (variantAvailable) { - applyGroupRenderState(group); - if (!variantBound) { - variantBound = true; - deferred.rebindCurrentPass(); - deferred.bindTesrInstancedVariant(); - } - instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs); - instancedInstances += group.count; - } else { - drawGroupCpuFallback(group); - } - continue; - } - variantBound = false; - if (group.builtCount != group.count || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) { - if (group.mesh.isUploaded()) { - group.consecutiveRebuilds++; - } - rebuild(group); - } else { - group.consecutiveRebuilds = 0; - } - draw(group); - if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) { - promote(group); - } + boolean matrixAvailable = true; + boolean cubeAvailable = true; + if (deferred != null && anyInstanceable(list)) { + deferred.rebindCurrentPass(); + matrixAvailable = deferred.hasInstancedVariant(Instancing.TEMPLATE); + cubeAvailable = deferred.hasInstancedVariant(Instancing.CUBE); } + final int need = drawUninstanced(list, matrixAvailable, cubeAvailable); restoreMV(); - if (variantBound) { + if ((need & NEED_MATRIX) != 0) { + if (deferred != null) deferred.bindInstancedVariant(Instancing.TEMPLATE); + drawMatrixVariant(list, cubeAvailable); + } + if ((need & NEED_CUBE) != 0) { + if (deferred != null) deferred.bindInstancedVariant(Instancing.CUBE); + drawCubeVariant(list); + } + if (need != 0 && deferred != null) { deferred.rebindCurrentPass(); } } - private void applyGroupRenderState(Group group) { - AngelicaBufferSource.setEntityColor(group.entityColor); - source.applyIdNoRebind(group.blockEntityId); + private static final int NEED_MATRIX = 1; + private static final int NEED_CUBE = 2; + + private boolean live(Group g) { + return g.frameMark == frameMark && (g.templateColumns.size > 0 || g.cubeColumns.size > 0); + } + + private boolean anyInstanceable(ObjectArrayList list) { + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (live(group) && instanceable(group)) return true; + } + return false; + } + + private int drawUninstanced(ObjectArrayList list, boolean matrixAvailable, boolean cubeAvailable) { + int need = 0; + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (!live(group)) continue; + if (!instanceable(group)) { + drawRetained(group); + continue; + } + if (group.templateColumns.size > 0) { + if (matrixAvailable) { + need |= NEED_MATRIX; + } else { + drawInstancesCpu(group, group.templateColumns); + } + } + if (group.cubeColumns.size > 0) { + if (cubeAvailable) { + need |= NEED_CUBE; + } else if (matrixAvailable) { + need |= NEED_MATRIX; + } else { + drawInstancesCpu(group, group.cubeColumns); + } + } + } + return need; + } + + private void drawMatrixVariant(ObjectArrayList list, boolean cubeAvailable) { + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (!live(group) || !instanceable(group)) continue; + if (group.templateColumns.size > 0) { + drawTemplateRuns(group.templateColumns); + } + if (!cubeAvailable && group.cubeColumns.size > 0) { + drawTemplateRuns(group.cubeColumns); + } + } + restoreTexMatrix(); + } + + private void drawCubeVariant(ObjectArrayList list) { + for (int i = 0, n = list.size(); i < n; i++) { + final Group group = list.get(i); + if (!live(group) || !instanceable(group) || group.cubeColumns.size == 0) continue; + drawCubeInstances(group); + } + restoreTexMatrix(); + } + + private boolean instanceable(Group group) { + return instanceableMaterial(group.material); + } + + private boolean instanceableMaterial(TesrMaterial material) { + return material.isStream() && instancedActive && (deferred == null || material.shader() == null); + } + + private void drawRetained(Group group) { + if (group.builtCount != group.templateColumns.size || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) { + if (group.mesh.isUploaded()) { + group.consecutiveRebuilds++; + } + rebuild(group); + } else { + group.consecutiveRebuilds = 0; + } + draw(group); + if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) { + promote(group); + } + } + + private void drawTemplateRuns(InstanceColumns cols) { + for (int r = 0, n = cols.runs.size(); r < n; r++) { + final TexRun run = cols.runs.get(r); + applyTexMatrix(run); + instancedDraws += instanced.drawTemplates(cols, run, nowMs); + instancedInstances += run.parts; + } + } + + private void drawCubeInstances(Group group) { + final InstanceColumns cols = group.cubeColumns; + for (int r = 0, n = cols.runs.size(); r < n; r++) { + final TexRun run = cols.runs.get(r); + applyTexMatrix(run); + instanced.drawCubes(cols, run); + instancedDraws++; + cubeInstances += run.instances; + } + } + + private void applyTexMatrix(TexRun run) { + if (run.identity && !texApplied) return; + if (!texApplied) { + texApplied = true; + savedTexMatrix.set(GLStateManager.getTextures().getTextureUnitMatrix(0)); + } + GLStateManager.setTextureMatrix(0, run.identity ? IDENTITY : run.matrix); + if (!run.identity) texMatrixRuns++; + } + + private void restoreTexMatrix() { + if (!texApplied) return; + texApplied = false; + GLStateManager.setTextureMatrix(0, savedTexMatrix); } private static final Matrix4f IDENTITY = new Matrix4f(); - private void drawGroupCpuFallback(Group group) { - AngelicaBufferSource.setEntityColor(group.entityColor); - source.applyIdAndRebind(group.blockEntityId); + static int entityFromInfo(long info) { + return (short) info; + } + + static int blockEntityFromInfo(long info) { + return (short) (info >>> 16); + } + + private int idFromInfo(long info) { + return source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY ? entityFromInfo(info) : blockEntityFromInfo(info); + } + + private void drawInstancesCpu(Group group, InstanceColumns cols) { saveMV(); GLStateManager.setModelViewMatrix(IDENTITY); final VertexFormat format = group.layer.getVertexFormat(); - int start = 0; - while (start < group.count) { - final int drawMode = group.instTemplates.get(start).drawMode; - int end = start; - int totalVerts = 0; - while (end < group.count && group.instTemplates.get(end).drawMode == drawMode) { - totalVerts += group.instTemplates.get(end).vertexCount; - end++; + final ObjectArrayList templates = cols.templates; + for (int r = 0, rn = cols.runs.size(); r < rn; r++) { + final TexRun head = cols.runs.get(r); + final Matrix4f texMatrix = head.identity ? null : head.matrix; + for (TexRun seg = head; seg != null; seg = seg.next) { + final int runEnd = seg.end; + int sub = seg.start; + while (sub < runEnd) { + final long info = cols.infos.getLong(sub); + final int overlay = cols.overlays.getInt(sub); + int subEnd = sub; + while (subEnd < runEnd && cols.infos.getLong(subEnd) == info && cols.overlays.getInt(subEnd) == overlay) { + subEnd++; + } + AngelicaBufferSource.setEntityColor(overlay); + source.applyIdAndRebind(idFromInfo(info)); + int start = sub; + while (start < subEnd) { + final int drawMode = templates.get(start).drawMode; + int end = start; + int totalVerts = 0; + while (end < subEnd && templates.get(end).drawMode == drawMode) { + totalVerts += templates.get(end).vertexCount; + end++; + } + fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false); + fallbackScratch.clear(); + final long base = memAddress0(fallbackScratch); + long ptr = base; + for (int i = start; i < end; i++) { + System.arraycopy(cols.matrices, i * 16, matScratch, 0, 16); + scratchMat.set(matScratch); + ptr = VertexTransform.writeInstance(ptr, format, templates.get(i), scratchMat, scratchVec, cols.colors.getInt(i), cols.lights.getInt(i), texMatrix); + } + fallbackScratch.position((int) (ptr - base)); + fallbackScratch.flip(); + fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts); + fallbackMesh.render(); + streamedInstances += end - start; + start = end; + } + sub = subEnd; + } } - fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false); - fallbackScratch.clear(); - final long base = memAddress0(fallbackScratch); - long ptr = base; - for (int i = start; i < end; i++) { - group.instMatrices.getElements(i * 16, matScratch, 0, 16); - scratchMat.set(matScratch); - ptr = VertexTransform.writeInstance(ptr, format, group.instTemplates.get(i), scratchMat, scratchVec, group.instColors.getInt(i), group.instLights.getInt(i), null); - } - fallbackScratch.position((int) (ptr - base)); - fallbackScratch.flip(); - fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts); - fallbackMesh.render(); - streamedInstances += end - start; - start = end; } } private void promote(Group group) { group.streaming = true; streamPromotions++; - group.count = 0; group.hashAcc = 0; group.frameHash = 0; group.prevFrameHash = 0; @@ -383,6 +612,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } void sweep(long now) { + lastGroup = null; for (final ObjectArrayList list : byLayer.values()) { for (int i = list.size() - 1; i >= 0; i--) { final Group group = list.get(i); @@ -408,8 +638,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { } byLayer.clear(); groups.clear(); + lastGroup = null; fallbackMesh.delete(); fallbackScratch = null; + texApplied = false; + instanced = null; + instancedActive = false; + deferred = null; } int groupCount() { @@ -483,22 +718,20 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { private void rebuildInner(Group group) { final VertexFormat format = group.layer.getVertexFormat(); + final InstanceColumns cols = group.templateColumns; int totalVerts = 0; - for (int i = 0, n = group.instTemplates.size(); i < n; i++) { - totalVerts += group.instTemplates.get(i).vertexCount; + for (int i = 0, n = cols.templates.size(); i < n; i++) { + totalVerts += cols.templates.get(i).vertexCount; } final int bytes = format.getVertexSize() * totalVerts; group.scratch = MeshBuffer.ensureCapacity(group.scratch, bytes, false); group.scratch.clear(); final long base = memAddress0(group.scratch); long ptr = base; - for (int i = 0, n = group.count; i < n; i++) { - group.instMatrices.getElements(i * 16, matScratch, 0, 16); + for (int i = 0, n = cols.size; i < n; i++) { + System.arraycopy(cols.matrices, i * 16, matScratch, 0, 16); scratchMat.set(matScratch); - final int light = group.instLights.getInt(i); - final int color = group.instColors.getInt(i); - final TemplateBuffer template = group.instTemplates.get(i); - ptr = VertexTransform.writeInstance(ptr, format, template, scratchMat, scratchVec, color, light, group.instTexMatrices.get(i)); + ptr = VertexTransform.writeInstance(ptr, format, cols.templates.get(i), scratchMat, scratchVec, cols.colors.getInt(i), cols.lights.getInt(i), group.instTexMatrices.get(i)); } group.scratch.position((int) (ptr - base)); group.scratch.flip(); @@ -506,7 +739,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook { group.mesh.upload(format, group.layer.getDrawMode(), group.scratch, group.builtVertexCount, true); group.meshBytes = bytes; group.builtHash = group.hashAcc; - group.builtCount = group.count; + group.builtCount = cols.size; } private void draw(Group group) { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ShadowQuadMath.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ShadowQuadMath.java new file mode 100644 index 000000000..ac9784da2 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/ShadowQuadMath.java @@ -0,0 +1,98 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import net.minecraft.util.MathHelper; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX; + +public final class ShadowQuadMath { + + public static final int RECORD_SIZE = 11; + + public static final int MIN_X = 0, Y = 1, MIN_Z = 2, MAX_X = 3, MAX_Z = 4, U_MIN_X = 5, V_MIN_Z = 6, U_MAX_X = 7, V_MAX_Z = 8, COLOR = 9, LIGHT = 10; + + private ShadowQuadMath() {} + + public static int box(double ex, double ey, double ez, float size, int[] outIJK) { + final int i = MathHelper.floor_double(ex - size); + final int j = MathHelper.floor_double(ex + size); + final int k = MathHelper.floor_double(ey - size); + final int l = MathHelper.floor_double(ey); + final int i1 = MathHelper.floor_double(ez - size); + final int j1 = MathHelper.floor_double(ez + size); + outIJK[0] = i; + outIJK[1] = j; + outIJK[2] = k; + outIJK[3] = l; + outIJK[4] = i1; + outIJK[5] = j1; + return (j - i + 1) * (l - k + 1) * (j1 - i1 + 1); + } + + public static boolean project(int[] out, int off, double x, double y, double z, int bx, int by, int bz, float shadowAlpha, float size, double ox, double oy, double oz, double minX, double maxX, double minY, double minZ, double maxZ, float brightness, int packedLight) { + double alpha = ((double) shadowAlpha - (y - ((double) by + oy)) / 2.0D) * 0.5D * (double) brightness; + if (alpha < 0.0D) return false; + if (alpha > 1.0D) alpha = 1.0D; + + final double qMinX = (double) bx + minX + ox; + final double qMaxX = (double) bx + maxX + ox; + final double qY = (double) by + minY + oy + 0.015625D; + final double qMinZ = (double) bz + minZ + oz; + final double qMaxZ = (double) bz + maxZ + oz; + final float uMinX = (float) ((x - qMinX) / 2.0D / (double) size + 0.5D); + final float uMaxX = (float) ((x - qMaxX) / 2.0D / (double) size + 0.5D); + final float vMinZ = (float) ((z - qMinZ) / 2.0D / (double) size + 0.5D); + final float vMaxZ = (float) ((z - qMaxZ) / 2.0D / (double) size + 0.5D); + + out[off + MIN_X] = Float.floatToRawIntBits((float) qMinX); + out[off + Y] = Float.floatToRawIntBits((float) qY); + out[off + MIN_Z] = Float.floatToRawIntBits((float) qMinZ); + out[off + MAX_X] = Float.floatToRawIntBits((float) qMaxX); + out[off + MAX_Z] = Float.floatToRawIntBits((float) qMaxZ); + out[off + U_MIN_X] = Float.floatToRawIntBits(uMinX); + out[off + V_MIN_Z] = Float.floatToRawIntBits(vMinZ); + out[off + U_MAX_X] = Float.floatToRawIntBits(uMaxX); + out[off + V_MAX_Z] = Float.floatToRawIntBits(vMaxZ); + out[off + COLOR] = 0xFFFFFF | ((int) ((float) alpha * 255.0F)) << 24; + out[off + LIGHT] = packedLight; + return true; + } + + public static void expand(int[] packed32, int[] records, int off, int normalPacked) { + final int minX = records[off + MIN_X]; + final int y = records[off + Y]; + final int minZ = records[off + MIN_Z]; + final int maxX = records[off + MAX_X]; + final int maxZ = records[off + MAX_Z]; + final int uMinX = records[off + U_MIN_X]; + final int vMinZ = records[off + V_MIN_Z]; + final int uMaxX = records[off + U_MAX_X]; + final int vMaxZ = records[off + V_MAX_Z]; + final int color = records[off + COLOR]; + final int light = records[off + LIGHT]; + + write(packed32, 0, minX, y, minZ, uMinX, vMinZ, color, light, normalPacked); + write(packed32, 1, minX, y, maxZ, uMinX, vMaxZ, color, light, normalPacked); + write(packed32, 2, maxX, y, maxZ, uMaxX, vMaxZ, color, light, normalPacked); + write(packed32, 3, maxX, y, minZ, uMaxX, vMinZ, color, light, normalPacked); + } + + private static void write(int[] packed32, int vertex, int x, int y, int z, int u, int v, int color, int light, int normal) { + final int base = vertex * VERTEX_SIZE; + packed32[base | X_INDEX] = x; + packed32[base | Y_INDEX] = y; + packed32[base | Z_INDEX] = z; + packed32[base | TEX_X_INDEX] = u; + packed32[base | TEX_Y_INDEX] = v; + packed32[base | COLOR_INDEX] = color; + packed32[base | LIGHT_INDEX] = light; + packed32[base | NORMAL_INDEX] = normal; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java index 59673e0a8..a6141fa76 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateBuffer.java @@ -6,6 +6,8 @@ public final class TemplateBuffer { final int[] work; public final int vertexCount; public final int drawMode; + long bucketEpoch; + int bucketIndex; public TemplateBuffer(int[] data, int vertexCount, int drawMode) { this.data = data; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateCapture.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateCapture.java new file mode 100644 index 000000000..c432fbb6f --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TemplateCapture.java @@ -0,0 +1,25 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; + +public final class TemplateCapture { + + private TemplateCapture() {} + + public static TemplateBuffer toTemplate(DirectTessellator direct) { + final int vertexCount = direct.getVertexCount(); + if (vertexCount == 0) return null; + final int drawMode = direct.getDrawMode(); + final VertexFormat format = direct.getVertexFormat(); + final ByteBuffer copy = direct.allocateBufferCopy(); + final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode); + memFree(copy); + return new TemplateBuffer(data, vertexCount, drawMode); + } +} 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 446efc224..d6333eb33 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrBatchRenderer.java @@ -1,13 +1,14 @@ package com.gtnewhorizons.angelica.rendering.tesr; import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; 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.client.font.BatchingFontRenderer; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; @@ -60,7 +61,8 @@ public final class TesrBatchRenderer { private final AngelicaBufferSource bufferSource = new AngelicaBufferSource(); private final RetainedTesrGroups[] retained = new RetainedTesrGroups[PASS_COUNT]; - final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer(); + final InstanceRing instanceRing = new InstanceRing(); + final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer(instanceRing); private int activePass = -1; private long lastSweepMs; private boolean deferredFlushPending; @@ -94,12 +96,16 @@ public final class TesrBatchRenderer { } } + public InstanceRing instanceRing() { + return instanceRing; + } + static boolean instancedCapable() { if (!ShaderManager.getInstance().isEnabled()) return false; if (!Iris.enabled) return true; final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline == null || pipeline instanceof FixedFunctionWorldRenderingPipeline) return true; - return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsTesrInstancing(); + return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsInstancing(Instancing.TEMPLATE); } static DeferredWorldRenderingPipeline deferredPipeline() { @@ -121,9 +127,18 @@ public final class TesrBatchRenderer { retained[i].clear(); } instancedRenderer.clear(); + instanceRing.delete(); immediateMesh.delete(); immediateScratch = null; bufferSource.freeBuffers(); + layers.clear(); + lastLayerTexture = null; + lastLayerMaterial = null; + lastLayerPass = null; + lastLayer = null; + lastImmediateTexture = null; + lastImmediateMaterial = null; + lastImmediateLayer = null; AngelicaTesrMeshCache.INSTANCE.clear(); } @@ -146,9 +161,10 @@ public final class TesrBatchRenderer { final RenderLayer layer = layerFor(texture, material, pass, offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f); final int blockEntityId = pass.isEntityPhase() - ? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()) + ? CapturedRenderingState.INSTANCE.getCurrentRenderedEntity() : CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); - retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, blockEntityId, captureTextureMatrix(), false); + final long entityInfo = InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); + retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, 0, entityInfo, blockEntityId, captureTextureMatrix()); } else { drawImmediate(template, texture, material, packedLight, colorABGR); } @@ -287,10 +303,10 @@ public final class TesrBatchRenderer { private static int resolveColor(TesrMaterial material) { if (material.hasColor()) { - return ColorABGR.pack(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha()); + return AngelicaBufferSource.packAbgr(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha()); } final Color4 color = GLStateManager.getColor(); - return ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + return AngelicaBufferSource.packAbgr(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } public void flush() { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrInstancingPipeline.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrInstancingPipeline.java new file mode 100644 index 000000000..13b95ab87 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/TesrInstancingPipeline.java @@ -0,0 +1,12 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; + +public interface TesrInstancingPipeline { + + void rebindCurrentPass(); + + boolean hasInstancedVariant(Instancing kind); + + void bindInstancedVariant(Instancing kind); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java index 5716fd0be..a392df91e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java +++ b/src/main/java/com/gtnewhorizons/angelica/shadercompat/ShaderGlint.java @@ -3,10 +3,12 @@ package com.gtnewhorizons.angelica.shadercompat; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.GlintColorHandler; +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import it.unimi.dsi.fastutil.ints.Int2IntLinkedOpenHashMap; import net.coderbot.iris.pipeline.ShadowRenderer; import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.util.ResourceLocation; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; @@ -27,7 +29,8 @@ import static org.joml.Math.clamp; public final class ShaderGlint { private static final ResourceLocation GLINT_MASK = new ResourceLocation("textures/misc/enchanted_item_glint.png"); - private static final int MAX_CACHE = 64; + public static final int TINT_SLOTS = 64; + public static final int NO_TINT = -1; private static boolean maskLoaded; private static boolean maskFailed; @@ -35,10 +38,11 @@ public final class ShaderGlint { private static int maskH; private static int[] maskLum; - private static final Int2IntLinkedOpenHashMap colorToTexture = new Int2IntLinkedOpenHashMap(); + private static final Int2IntLinkedOpenHashMap colorToSlot = new Int2IntLinkedOpenHashMap(); static { - colorToTexture.defaultReturnValue(0); + colorToSlot.defaultReturnValue(NO_TINT); } + private static final int[] slotTextures = new int[TINT_SLOTS]; private static final GlintColorHandler COLOR_HANDLER = ShaderGlint::onColorChanged; @@ -76,6 +80,7 @@ public final class ShaderGlint { if (swapped) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, prevTexture); + ModelPartBatcher.onTextureSwap(prevTexture, NO_TINT); } swapped = false; injecting = false; @@ -84,35 +89,61 @@ public final class ShaderGlint { private static void onColorChanged(float red, float green, float blue, float alpha) { if (injecting) return; - final int texture = getTintedTexture(red, green, blue); - if (texture <= 0) return; + final int slot = tintSlot(red, green, blue); + if (slot < 0) return; + final int texture = slotTextures[slot]; injecting = true; GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, alpha); injecting = false; swapped = true; + ModelPartBatcher.onTextureSwap(texture, slot); } - private static int getTintedTexture(float r, float g, float b) { + public static void invalidate() { + for (int i = 0; i < slotTextures.length; i++) { + if (slotTextures[i] != 0) { + GLStateManager.glDeleteTextures(slotTextures[i]); + slotTextures[i] = 0; + } + } + colorToSlot.clear(); + maskLum = null; + tintBuffer = null; + maskLoaded = false; + maskFailed = false; + } + + public static void bindTintedGlint(int slot) { + if (slot < 0 || ShadowRenderer.ACTIVE || !IrisApi.getInstance().isShaderPackInUse()) return; + final ITextureObject mask = Minecraft.getMinecraft().getTextureManager().getTexture(GLINT_MASK); + if (mask == null || GLStateManager.getBoundTextureForServerState() != mask.getGlTextureId()) return; + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, slotTextures[slot]); + } + + private static int tintSlot(float r, float g, float b) { ensureMaskLoaded(); - if (!maskLoaded) return -1; + if (!maskLoaded) return NO_TINT; final int ri = clamp8(r); final int gi = clamp8(g); final int bi = clamp8(b); final int key = (ri << 16) | (gi << 8) | bi; - final int cached = colorToTexture.getAndMoveToLast(key); - if (cached != 0) return cached; + final int cached = colorToSlot.getAndMoveToLast(key); + if (cached != NO_TINT) return cached; - if (colorToTexture.size() >= MAX_CACHE) { - GLStateManager.glDeleteTextures(colorToTexture.remove(colorToTexture.firstIntKey())); + final int slot; + if (colorToSlot.size() >= TINT_SLOTS) { + slot = colorToSlot.remove(colorToSlot.firstIntKey()); + GLStateManager.glDeleteTextures(slotTextures[slot]); + } else { + slot = colorToSlot.size(); } - - final int texture = uploadTinted(ri / 255.0F, gi / 255.0F, bi / 255.0F); - colorToTexture.putAndMoveToLast(key, texture); - return texture; + slotTextures[slot] = uploadTinted(ri / 255.0F, gi / 255.0F, bi / 255.0F); + colorToSlot.putAndMoveToLast(key, slot); + return slot; } private static int uploadTinted(float r, float g, float b) { diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java index 9be6304c6..af0b5e07c 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSource.java @@ -4,12 +4,14 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager; import net.coderbot.iris.Iris; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.pipeline.WorldRenderingPhase; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.uniforms.CapturedRenderingState; +import org.joml.Vector4fc; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; @@ -37,6 +39,7 @@ public class AngelicaBufferSource implements Groupable { private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS]; private final Object2IntLinkedOpenHashMap affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS); private final Map> typeToSegment = new Object2ObjectOpenHashMap<>(); + private final ObjectArrayList> segmentLists = new ObjectArrayList<>(); private boolean prepared; private final List order = new ArrayList<>(); @@ -86,7 +89,13 @@ public class AngelicaBufferSource implements Groupable { final List builderSegments = builder.getSegments(); for (int i = 0, n = builderSegments.size(); i < n; i++) { final BufferSegment segment = builderSegments.get(i); - typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment); + List segments = typeToSegment.get(segment.getRenderType()); + if (segments == null) { + segments = new ArrayList<>(); + typeToSegment.put(segment.getRenderType(), segments); + segmentLists.add(segments); + } + segments.add(segment); } } order.clear(); @@ -168,7 +177,7 @@ public class AngelicaBufferSource implements Groupable { anyIdSet = false; } - private GroupIdKind effectiveIdKind() { + public GroupIdKind effectiveIdKind() { return GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.ENTITIES ? GroupIdKind.ENTITY : idKind; } @@ -223,8 +232,8 @@ public class AngelicaBufferSource implements Groupable { } private void clearSegmentLists() { - for (List segments : typeToSegment.values()) { - segments.clear(); + for (int i = 0, n = segmentLists.size(); i < n; i++) { + segmentLists.get(i).clear(); } } @@ -245,6 +254,7 @@ public class AngelicaBufferSource implements Groupable { builder.freeAll(); } typeToSegment.clear(); + segmentLists.clear(); order.clear(); affinities.clear(); renderOrderManager.reset(); @@ -283,19 +293,20 @@ public class AngelicaBufferSource implements Groupable { } } - public void applyIdNoRebind(int id) { - anyIdSet = true; - if (effectiveIdKind() == GroupIdKind.ENTITY) { - CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(id, 0); - } else { - CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id); - } + public static int packEntityColor(Vector4fc c) { + return packAbgr(c.x(), c.y(), c.z(), c.w()); } - public static void setEntityColor(int packed) { - CapturedRenderingState.INSTANCE.setCurrentEntityColor( - ((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f, - (packed & 0xFF) / 255f, (packed >>> 24) / 255f); + public static int packAbgr(float r, float g, float b, float a) { + return (unit(a) << 24) | (unit(b) << 16) | (unit(g) << 8) | unit(r); + } + + private static int unit(float v) { + return (int) (Math.clamp(v, 0f, 1f) * 255f + 0.5f); + } + + public static void setEntityColor(int abgr) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor((abgr & 0xFF) / 255f, ((abgr >>> 8) & 0xFF) / 255f, ((abgr >>> 16) & 0xFF) / 255f, (abgr >>> 24) / 255f); } public static void setBlockEntityAndRebind(int blockEntityId) { diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java b/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java index ab02860c3..f7124471e 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java +++ b/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java @@ -1,6 +1,7 @@ package net.coderbot.batchedentityrendering.impl; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; @@ -10,7 +11,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.coderbot.iris.uniforms.CapturedRenderingState; import org.joml.Matrix4fc; import org.joml.Vector3f; -import org.joml.Vector4fc; import org.lwjgl.BufferUtils; import java.nio.ByteBuffer; @@ -79,7 +79,7 @@ public class SegmentedBufferBuilder { private long allocatedBytes; public void begin(RenderLayer type, int blockEntityId) { - final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); + final int entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()); if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) { return; } @@ -98,10 +98,6 @@ public class SegmentedBufferBuilder { segmentStartVertex = current.vertexCount; } - public static int packEntityColor(Vector4fc c) { - return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f); - } - public void addQuad(ModelQuadView quad) { if (current == null) { throw new IllegalStateException("addQuad() without begin()"); @@ -125,6 +121,19 @@ public class SegmentedBufferBuilder { current.vertexCount += template.vertexCount; } + public void addPackedVertices(int[] packed, int vertexCount, Matrix4fc mv, Vector3f scratch) { + if (current == null) { + throw new IllegalStateException("addPackedVertices() without begin()"); + } + final VertexFormat format = currentType.getVertexFormat(); + ensureCurrentCapacity(format.getVertexSize() * vertexCount); + final ByteBuffer buffer = current.buffer; + final long ptr = memAddress0(buffer) + buffer.position(); + final long end = format.writeToBuffer0(ptr, packed, vertexCount * ModelQuadUtil.VERTEX_SIZE, mv, scratch); + buffer.position(buffer.position() + (int) (end - ptr)); + current.vertexCount += vertexCount; + } + private void ensureCurrentCapacity(int bytes) { final int before = current.buffer.capacity(); current.ensureCapacity(bytes); diff --git a/src/main/java/net/coderbot/iris/Iris.java b/src/main/java/net/coderbot/iris/Iris.java index fcd933a88..338fcf2f3 100644 --- a/src/main/java/net/coderbot/iris/Iris.java +++ b/src/main/java/net/coderbot/iris/Iris.java @@ -238,7 +238,7 @@ public class Iris { try { submitTracked(() -> { TransformPatcher.patchComposite(vertexShader, null, fragmentShader); - TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true)); + TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, InputAvailability.of(true, true)); }).get(); } catch (Exception e) { logger.warn("Warmup failed", e); diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java index bdd9e729f..60a45ce2f 100644 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java +++ b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java @@ -1,64 +1,28 @@ package net.coderbot.iris.gbuffer_overrides.matching; -public class InputAvailability { +public enum InputAvailability { + NONE(false, false), TEXTURE(true, false), LIGHTMAP(false, true), BOTH(true, true); + public static final int NUM_VALUES = 8; + public static final InputAvailability[] VALUES = values(); public final boolean texture; public final boolean lightmap; - public InputAvailability(boolean texture, boolean lightmap) { + InputAvailability(boolean texture, boolean lightmap) { this.texture = texture; this.lightmap = lightmap; } + public static InputAvailability of(boolean texture, boolean lightmap) { + return VALUES[(texture ? 1 : 0) | (lightmap ? 2 : 0)]; + } + public static InputAvailability unpack(int packed) { - return new InputAvailability((packed & 1) == 1, (packed & 2) == 2); + return VALUES[packed & 3]; } public int pack() { - int packed = 0; - - if (lightmap) { - packed |= 2; - } - - if (texture) { - packed |= 1; - } - - return packed; - } - - @Override - public String toString() { - return "InputAvailability{" + - "texture=" + texture + - ", lightmap=" + lightmap + - '}'; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (lightmap ? 1231 : 1237); - result = prime * result + (texture ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - InputAvailability other = (InputAvailability) obj; - if (lightmap != other.lightmap) - return false; - if (texture != other.texture) - return false; - return true; + return ordinal(); } } diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java index 46f38a6fc..d8c48d317 100644 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java +++ b/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java @@ -13,6 +13,6 @@ public class StateTracker { public boolean lightmapSampler; public InputAvailability getInputs() { - return new InputAvailability(albedoSampler, lightmapSampler); + return InputAvailability.of(albedoSampler, lightmapSampler); } } diff --git a/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java b/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java index a92c5a702..57cf2ad18 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java +++ b/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java @@ -25,8 +25,10 @@ public class ProgramCreator { int program = GLStateManager.glCreateProgram(); // TODO: This is *really* hardcoded, we need to refactor this to support external calls to glBindAttribLocation + RenderSystem.bindAttributeLocation(program, MC_ENTITY, "iris_Entity"); RenderSystem.bindAttributeLocation(program, MC_ENTITY, "mc_Entity"); RenderSystem.bindAttributeLocation(program, MC_MID_TEX_COORD, "mc_midTexCoord"); + RenderSystem.bindAttributeLocation(program, AT_TANGENT, "iris_CubeTangent"); RenderSystem.bindAttributeLocation(program, AT_TANGENT, "at_tangent"); RenderSystem.bindAttributeLocation(program, AT_MIDBLOCK, "at_midBlock"); diff --git a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java b/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java index 8cd20aa34..fb4a71ba7 100644 --- a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java +++ b/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java @@ -329,12 +329,20 @@ public class GbufferPrograms { public static void setupSpecialRenderCondition(SpecialCondition override) { currentSpecial = override; - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override)); + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (pipeline != null) { + pipeline.setSpecialCondition(override); + } } public static void teardownSpecialRenderCondition() { currentSpecial = null; - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null)); + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (pipeline != null) { + pipeline.setSpecialCondition(null); + } } public static void runPhaseChangeNotifier() { diff --git a/src/main/java/net/coderbot/iris/layer/PassOverride.java b/src/main/java/net/coderbot/iris/layer/PassOverride.java index 7f40909f7..a310e7300 100644 --- a/src/main/java/net/coderbot/iris/layer/PassOverride.java +++ b/src/main/java/net/coderbot/iris/layer/PassOverride.java @@ -3,12 +3,17 @@ package net.coderbot.iris.layer; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.pipeline.WorldRenderingPhase; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + import java.util.Locale; +import java.util.Objects; public record PassOverride(SpecialCondition special, Boolean translucent, WorldRenderingPhase phase) { public static final PassOverride NONE = new PassOverride(null, null, null); + private static final ObjectArrayList INTERNED = new ObjectArrayList<>(); + public PassOverride(SpecialCondition special, Boolean translucent) { this(special, translucent, null); } @@ -17,8 +22,18 @@ public record PassOverride(SpecialCondition special, Boolean translucent, WorldR final SpecialCondition special = GbufferPrograms.getSpecialCondition(); final Boolean translucent = GbufferPrograms.getDeclaredTranslucency(); final WorldRenderingPhase phase = GbufferPrograms.getOverridePhase(); - return special == null && translucent == null && phase == null - ? NONE : new PassOverride(special, translucent, phase); + if (special == null && translucent == null && phase == null) { + return NONE; + } + for (int i = 0, n = INTERNED.size(); i < n; i++) { + final PassOverride candidate = INTERNED.get(i); + if (candidate.special == special && candidate.phase == phase && Objects.equals(candidate.translucent, translucent)) { + return candidate; + } + } + final PassOverride created = new PassOverride(special, translucent, phase); + INTERNED.add(created); + return created; } public void apply() { diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index f1a61c8e9..6b86ee558 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -13,8 +13,13 @@ import org.joml.Matrix4fc; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.PendingProgramSelection; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.rendering.RenderingState; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.gtnewhorizons.angelica.rendering.tesr.TesrInstancingPipeline; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.Iris; @@ -111,6 +116,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; +import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -127,7 +133,7 @@ import java.util.function.Supplier; /** * Encapsulates the compiled shader program objects for the currently loaded shaderpack. */ -public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener { +public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener, TesrInstancingPipeline, PendingProgramSelection { private final RenderTargets renderTargets; @Nullable @@ -178,8 +184,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final ShaderStorageBufferHolder ssboHolder; private final Map, Map> attributeTransforms; - private final Map, Map> instancedAttributeTransforms; - private boolean supportsTesrInstancing = true; + private final EnumMap, Map>> instancedAttributeTransforms = new EnumMap<>(Instancing.class); + private final boolean[] supportsInstancing = initialInstancingSupport(); private final ParityFlipState parityState = new ParityFlipState(AngelicaConfig.shaderParityFlip); private final Supplier> flippedGbuffers; private final Supplier> flippedShadowGbuffers; @@ -214,7 +220,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private boolean worldGroupActive = false; private boolean isBeforeTranslucent; private boolean isRenderingShadow = false; - private InputAvailability inputs = new InputAvailability(false, false); + private InputAvailability inputs = InputAvailability.of(false, false); private SpecialCondition special = null; private boolean shouldBindPBR; @@ -254,8 +260,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R .orElse(null); resolver = new ProgramFallbackResolver(programs); - final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver, ProgramId.values(), false); - final Map, CompletableFuture>> instancedTransformFutures = submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true); + final Map mvBuiltinsMemo = new ConcurrentHashMap<>(); + final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver, attributeProgramIds(Instancing.NONE), Instancing.NONE, mvBuiltinsMemo); + final EnumMap, CompletableFuture>>> instancedTransformFutures = new EnumMap<>(Instancing.class); + for (Instancing kind : Instancing.VALUES) { + if (kind != Instancing.NONE) { + instancedTransformFutures.put(kind, submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo)); + } + } final Optional terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic()); final Optional terrainSolidOverride = programs.getGbuffersTerrainSolid(); @@ -506,17 +518,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R Iris.logger.info("[Load #{}] DWRP phase=attribute-join elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0)); _tLast = System.nanoTime(); - this.instancedAttributeTransforms = new HashMap<>(); - for (Map.Entry, CompletableFuture>> entry : instancedTransformFutures.entrySet()) { - try { - final Map transformed = entry.getValue().join(); - if (transformed == null) continue; - this.instancedAttributeTransforms.put(entry.getKey(), transformed); - } catch (Exception e) { - Iris.logger.warn("Instanced transform failed for {}; disabling TESR instancing", entry.getKey().getLeft(), e); - supportsTesrInstancing = false; - instancedAttributeTransforms.clear(); - break; + for (Map.Entry, CompletableFuture>>> kindEntry : instancedTransformFutures.entrySet()) { + final Instancing kind = kindEntry.getKey(); + final Map, Map> joined = new HashMap<>(); + this.instancedAttributeTransforms.put(kind, joined); + for (Map.Entry, CompletableFuture>> entry : kindEntry.getValue().entrySet()) { + try { + final Map transformed = entry.getValue().join(); + if (transformed == null) continue; + joined.put(entry.getKey(), transformed); + } catch (Exception e) { + Iris.logger.warn("{} instanced transform failed for {}; disabling it", kind, entry.getKey().getLeft(), e); + supportsInstancing[kind.ordinal()] = false; + joined.clear(); + break; + } } } @@ -594,10 +610,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null), programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer, () -> usesSampler(IrisSamplers.USAGE_SHADOWTEX1)); - Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram(); - Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, new InputAvailability(true, true)).getProgram(); - shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0) - || (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0)); + Program shadowProgram = table.match(RenderCondition.SHADOW, InputAvailability.of(true, true)).getProgram(); + Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, InputAvailability.of(true, true)).getProgram(); + shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0) || (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0)); shadowRenderer.setPlayerReflectionCaptureEnabled((shadowProgram != null && GLStateManager.glGetUniformLocation(shadowProgram.getProgramId(), "playerAtlas_img") != -1) || (shadowWaterProgram != null && GLStateManager.glGetUniformLocation(shadowWaterProgram.getProgramId(), "playerAtlas_img") != -1)); } else { shadowRenderer = null; @@ -644,7 +659,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW)); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true)); recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); @@ -679,7 +694,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW)); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flippedAfterPrepareResolved, renderTargets, false, this); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); // Bind custom images as samplers (for texture() access to voxel_sampler, floodfill_sampler, etc.) @@ -926,6 +941,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } current = null; currentCondition = null; + clearPendingSelection(); } public void restorePassAfterModProgram(int newProgram) { @@ -966,7 +982,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R matchingBlend = true; try { - matchPass(); + requestMatch(); } finally { matchingBlend = false; } @@ -974,7 +990,30 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private boolean matchingBlend; + private void requestMatch() { + if (GLStateManager.isForeignDraw() || BatchEligibility.batchingAllowed()) { + GLSMHooks.pendingProgramSelection = this; + return; + } + matchPass(); + } + + @Override + public void resolvePendingProgram() { + if (GLSMHooks.pendingProgramSelection == this && !GLStateManager.isForeignDraw()) { + matchPass(); + } + } + + private void clearPendingSelection() { + if (GLSMHooks.pendingProgramSelection == this) { + GLSMHooks.pendingProgramSelection = null; + } + } + private void matchPass() { + clearPendingSelection(); + if (!shouldOverrideShaders()) { return; } @@ -989,6 +1028,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void onEntityRenderBoundary() { + GLSMHooks.resolvePendingProgram(); + if (!shouldOverrideShaders()) { return; } @@ -1026,6 +1067,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void rebindCurrentPass() { + GLSMHooks.resolvePendingProgram(); final Pass pass = this.current; if (pass == null) { if (GLStateManager.getActiveProgram() == 0) { @@ -1147,11 +1189,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R framebufferAfterTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, programDirectives.getDrawBuffers()); } - builder.bindAttributeLocation(11, "mc_Entity"); - builder.bindAttributeLocation(12, "mc_midTexCoord"); - builder.bindAttributeLocation(13, "at_tangent"); - builder.bindAttributeLocation(14, "at_midBlock"); - AlphaTestOverride alphaTestOverride = programDirectives.getAlphaTestOverride() .orElse(id.getDefaultAlphaTestOverride()); @@ -1186,7 +1223,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor); } - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(hasTexture, hasLightmap)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(hasTexture, hasLightmap)); if (!isShadowPass) { recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets)); } @@ -1301,8 +1338,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private String instancingSourceName; private InputAvailability instancingAvailability; private boolean instancingShadow; - @Nullable private Program instancedVariant; - private boolean instancedVariantAttempted; + private final Program[] instancedVariants = new Program[Instancing.VALUES.length]; + private final boolean[] instancedVariantAttempted = new boolean[Instancing.VALUES.length]; private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents, @Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List bufferBlendOverrides, boolean shadowViewport) { @@ -1382,64 +1419,77 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } @Nullable - Program getInstancedVariant() { - if (!instancedVariantAttempted) { - instancedVariantAttempted = true; - if (instancingSourceName != null && supportsTesrInstancing) { - instancedVariant = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow); + Program instancedVariant(Instancing kind) { + final int i = kind.ordinal(); + if (!instancedVariantAttempted[i]) { + instancedVariantAttempted[i] = true; + if (instancingSourceName != null && supportsInstancing[i]) { + instancedVariants[i] = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow, kind); } } - return instancedVariant; + return instancedVariants[i]; } public void destroy() { if (this.program != null) { this.program.destroy(); } - if (this.instancedVariant != null) { - this.instancedVariant.destroy(); - this.instancedVariant = null; + for (int i = 0; i < instancedVariants.length; i++) { + if (instancedVariants[i] != null) { + instancedVariants[i].destroy(); + instancedVariants[i] = null; + } } } } @Nullable - private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow) { - final Map transformed = instancedAttributeTransforms.get(Pair.of(sourceName, availability)); + private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow, Instancing kind) { + final Map, Map> transforms = instancedAttributeTransforms.get(kind); + final Map transformed = transforms != null ? transforms.get(Pair.of(sourceName, availability)) : null; if (transformed == null) { return null; } try { - final ProgramBuilder builder = beginBuilder(sourceName + "_instanced", transformed); + final ProgramBuilder builder = beginBuilder(sourceName + kind.variantSuffix, transformed); wireGbufferProgram(builder, availability, shadow); final Program variant = builder.build(); this.customUniforms.mapholderToPass(builder, variant); return variant; } catch (Exception e) { - Iris.logger.warn("TESR instanced variant link failed for {}; disabling TESR instancing", sourceName, e); - supportsTesrInstancing = false; + Iris.logger.warn("{} instanced variant link failed for {}; disabling it", kind, sourceName, e); + supportsInstancing[kind.ordinal()] = false; return null; } } - public boolean supportsTesrInstancing() { - return supportsTesrInstancing; + static boolean[] initialInstancingSupport() { + final boolean[] out = new boolean[Instancing.VALUES.length]; + out[Instancing.TEMPLATE.ordinal()] = true; + out[Instancing.CUBE.ordinal()] = AngelicaConfig.cubeInstancingEnabled(); + out[Instancing.PARTICLE.ordinal()] = true; + return out; } - public boolean hasTesrInstancedVariant() { - final Pass pass = current; - return pass != null && pass.getInstancedVariant() != null; + public boolean supportsInstancing(Instancing kind) { + return supportsInstancing[kind.ordinal()]; } - public void bindTesrInstancedVariant() { - final Pass pass = current; - final Program variant = pass.getInstancedVariant(); + @Override + public boolean hasInstancedVariant(Instancing kind) { + return current != null && current.instancedVariant(kind) != null; + } + + @Override + public void bindInstancedVariant(Instancing kind) { + final Program variant = current.instancedVariant(kind); variant.use(); this.customUniforms.push(variant); } @Override public void destroy() { + clearPendingSelection(); DepthColorStorage.unlockDepthColor(); BlendModeOverride.restore(); AlphaTestOverride.restore(); @@ -1683,7 +1733,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage)); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); IrisImages.addRenderTargetImages(builder, flipped, renderTargets); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures()); @@ -1761,7 +1811,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); IrisImages.addRenderTargetImages(builder, flipped, renderTargets); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); @@ -2141,7 +2191,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R public void setOverridePhase(WorldRenderingPhase phase) { this.overridePhase = phase; syncPhaseDebugGroup(); - matchPass(); + requestMatch(); GbufferPrograms.runPhaseChangeNotifier(); } @@ -2149,7 +2199,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R public void setPhase(WorldRenderingPhase phase) { this.phase = phase; syncPhaseDebugGroup(); - matchPass(); + requestMatch(); GbufferPrograms.runPhaseChangeNotifier(); } @@ -2179,19 +2229,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R @Override public void setInputs(InputAvailability availability) { this.inputs = availability; - matchPass(); + requestMatch(); } @Override public void setSpecialCondition(SpecialCondition special) { this.special = special; - matchPass(); + requestMatch(); } @Override public void setDeclaredTranslucency(@Nullable Boolean translucent) { this.declaredTranslucent = translucent; - matchPass(); + requestMatch(); } @Nullable @@ -2229,12 +2279,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } } - private static final InputAvailability INPUT_NONE = new InputAvailability(false, false); - private static final InputAvailability INPUT_LIGHTMAP_ONLY = new InputAvailability(false, true); - private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false); - private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true); - private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_LIGHTMAP_ONLY, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP }; - private static CompletableFuture> submitCompositeTransform(ProgramSource source, TextureStage stage, Object2ObjectMap, String> textureMap) { return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite( @@ -2264,10 +2308,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } private static Map, CompletableFuture>> - submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, boolean instanced) { + submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, Instancing instancing, Map mvBuiltinsMemo) { + if (instancing == Instancing.CUBE && !AngelicaConfig.cubeInstancingEnabled()) { + return Collections.emptyMap(); + } + final boolean instanced = instancing != Instancing.NONE; + final boolean matrixInstanced = instancing.hasInstanceHead(); final Map, CompletableFuture>> futures = new HashMap<>(); final Set processedSourceNames = new HashSet<>(); - final Map mvBuiltinsMemo = new ConcurrentHashMap<>(); for (ProgramId id : ids) { if (id.getGroup() == ProgramGroup.Dh) continue; final ProgramSource source = resolver.resolveNullable(id); @@ -2276,9 +2324,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } final String vertexSource = source.getVertexSource().orElse(null); final boolean scrollGlint = GlintScrollInjector.shouldInject(id, source); - for (InputAvailability avail : INPUT_AVAILABILITIES) { + for (InputAvailability avail : InputAvailability.VALUES) { futures.put(Pair.of(source.getName(), avail), Iris.ShaderTransformExecutor.submitTracked(() -> { - if (instanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> { + if (matrixInstanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> { final boolean references = referencesMvBuiltinsOutsideVertex(source); if (references) { Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", k); @@ -2291,7 +2339,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R final String tessControl = source.getTessControlSource().orElse(null); final String tessEval = source.getTessEvalSource().orElse(null); final String fragment = source.getFragmentSource().orElse(null); - return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint) + return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint, instancing) : TransformPatcher.patchAttributes(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint); })); } @@ -2301,9 +2349,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private static final ProgramId[] INSTANCED_PROGRAM_IDS = { ProgramId.Block, ProgramId.BlockTrans, ProgramId.Entities, ProgramId.EntitiesTrans, - ProgramId.Shadow, ProgramId.ShadowWater + ProgramId.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint }; + private static final ProgramId[] PARTICLE_PROGRAM_IDS = { + ProgramId.Particles, ProgramId.ParticlesTrans + }; + + private static ProgramId[] attributeProgramIds(Instancing kind) { + return switch (kind) { + case NONE -> ProgramId.values(); + case TEMPLATE, CUBE -> INSTANCED_PROGRAM_IDS; + case PARTICLE -> PARTICLE_PROGRAM_IDS; + }; + } + private static final String[] MV_BUILTINS = { "gl_ModelViewMatrix", "gl_ModelViewMatrixInverse", "gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixInverse", @@ -2371,8 +2431,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R .ifPresent(source -> submitCompositeTransform(source, TextureStage.COMPOSITE_AND_FINAL, tm)); final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs); - submitAttributeTransforms(resolver, ProgramId.values(), false); - submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true); + final Map mvBuiltinsMemo = new ConcurrentHashMap<>(); + for (Instancing kind : Instancing.VALUES) { + submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo); + } final Optional terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic()); final Optional translucentSource = first(programs.getGbuffersWater(), terrainSource); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java index 167a9f1ad..3de74606f 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -1,6 +1,10 @@ package net.coderbot.iris.pipeline.transform; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import com.gtnewhorizons.angelica.glsm.shader.ShaderType; +import net.coderbot.iris.gl.shader.ProgramCreator; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLLexer; @@ -30,27 +34,37 @@ class AttributeTransformer { } private static void transformCore(Transformer transformer, AttributeParameters parameters) { - final boolean instancedVertex = parameters.instanced && parameters.type == ShaderType.VERTEX; - final boolean wantsMvInverse = instancedVertex && transformer.containsCall("gl_ModelViewMatrixInverse"); - CoreTransformHelper.injectMatrixUniforms(transformer, instancedVertex); + final boolean vertex = parameters.type == ShaderType.VERTEX; + final boolean instancedVertex = vertex && parameters.instancing != Instancing.NONE; + final boolean cubeVertex = vertex && parameters.instancing == Instancing.CUBE; + final boolean particleVertex = vertex && parameters.instancing == Instancing.PARTICLE; + final boolean matrixVertex = vertex && parameters.instancing.hasInstanceHead(); + final boolean wantsMvInverse = matrixVertex && transformer.containsCall("gl_ModelViewMatrixInverse"); + CoreTransformHelper.injectMatrixUniforms(transformer, vertex ? parameters.instancing : Instancing.NONE); aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix"); aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix"); aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix"); if (parameters.type == ShaderType.VERTEX) { - transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); - transformer.injectVariable("layout(location = 1) in vec4 iris_Color;"); - transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;"); - if (instancedVertex) { - transformer.injectVariable("vec4 iris_MultiTexCoord1;"); - } else { - transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;"); + if (!particleVertex) { + transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); + transformer.injectVariable("layout(location = 1) in vec4 iris_Color;"); + if (cubeVertex) { + transformer.injectVariable("vec4 iris_MultiTexCoord0;"); + } else { + transformer.injectVariable("layout(location = " + PRIMARY_UV + ") in vec4 iris_MultiTexCoord0;"); + } + if (instancedVertex) { + transformer.injectVariable("vec4 iris_MultiTexCoord1;"); + } else { + transformer.injectVariable("layout(location = " + SECONDARY_UV + ") in vec4 iris_MultiTexCoord1;"); + } } transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); transformer.rename("gl_Vertex", "iris_Vertex"); - transformer.replaceExpression("gl_Color", instancedVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)"); + transformer.replaceExpression("gl_Color", matrixVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)"); transformer.rename("gl_Normal", "iris_Normal"); aliasIfUsed(transformer, "vaNormal", "iris_Normal"); if (transformer.containsCall("vaPosition") && !transformer.hasVariable("vaPosition")) { @@ -88,18 +102,83 @@ class AttributeTransformer { if (instancedVertex) { foldConstantAttribute(transformer, "mc_Entity", "-1.0", "vec2(-1.0, -1.0)", "vec3(-1.0, -1.0, 0.0)", "vec4(-1.0, -1.0, 0.0, 1.0)"); - final StringBuilder init = new StringBuilder(256); - init.append("{ iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3);"); - init.append(" iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz));"); - if (wantsMvInverse) { - init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);"); + final StringBuilder init = new StringBuilder(256).append("{ "); + if (particleVertex) { + init.append("iris_Vertex = ").append(InstancedGlslHelpers.particlePos("iris_InstCenterHalf", "iris_ParticleOffset")).append(';'); + init.append(" iris_Color = iris_InstColor;"); + init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.particleUv("iris_InstUv", "iris_ParticleCorner")).append(';'); + init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0);"); + assignMidTexCoord(transformer, init, "vec4((iris_InstUv.x + iris_InstUv.z) * 0.5, (iris_InstUv.y + iris_InstUv.w) * 0.5, 0.0, 1.0)"); + } else { + init.append("iris_ModelViewMatrix = ").append(InstancedGlslHelpers.mat4FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';'); + init.append(" iris_NormalMatrix = ").append(InstancedGlslHelpers.mat3FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';'); + if (wantsMvInverse) { + init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);"); + } + init.append(" iris_MultiTexCoord1 = vec4(").append(cubeVertex ? "iris_InstLightmapScale.xy" : "iris_InstLightmap").append(", 0.0, 1.0);"); + if (cubeVertex) { + appendCubeTexCoords(transformer, init); + } } - init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0); }"); + init.append(" }"); transformer.prependMain(init.toString()); } } } + private static final int PRIMARY_UV = VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(); + private static final int SECONDARY_UV = VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation(); + + private static void appendCubeTexCoords(Transformer transformer, StringBuilder init) { + init.append(' ').append(InstancedGlslHelpers.cubePrelude("iris_", "iris_CubeMid", "iris_CubeDelta", "iris_Normal", "iris_CubeTex", " ")); + init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeU.x", "iris_cubeU.y", "iris_cubeV.x", "iris_cubeV.y")).append(';'); + + final int tangentType = transformer.findType("at_tangent"); + if (tangentType != 0) { + final String name = vecName(tangentType); + if (name == null || tangentType == GLSLLexer.VEC2) { + throw new IllegalStateException("Unsupported at_tangent type token " + tangentType + " for the cube instanced variant"); + } + transformer.removeVariable("at_tangent"); + transformer.injectVariable("layout(location = " + ProgramCreator.AT_TANGENT + ") in vec4 iris_CubeTangent;"); + transformer.injectVariable(name + " at_tangent;"); + init.append(" at_tangent = (iris_CubeTangent * (1.0 - 2.0 * iris_cubeMirror))").append(swizzle(tangentType)).append(';'); + } + + assignMidTexCoord(transformer, init, InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeMidU.x", "iris_cubeMidU.y", "iris_CubeMid.z", "iris_CubeMid.w")); + } + + private static void assignMidTexCoord(Transformer transformer, StringBuilder init, String midExpression) { + final int midType = transformer.findType("mc_midTexCoord"); + if (midType == 0) { + return; + } + final String name = vecName(midType); + if (name == null) { + throw new IllegalStateException("Unsupported mc_midTexCoord type token " + midType + " for the instanced variant"); + } + transformer.removeVariable("mc_midTexCoord"); + transformer.injectVariable(name + " mc_midTexCoord;"); + init.append(" mc_midTexCoord = (").append(midExpression).append(')').append(swizzle(midType)).append(';'); + } + + private static String vecName(int type) { + return switch (type) { + case GLSLLexer.VEC2 -> "vec2"; + case GLSLLexer.VEC3 -> "vec3"; + case GLSLLexer.VEC4 -> "vec4"; + default -> null; + }; + } + + private static String swizzle(int type) { + return switch (type) { + case GLSLLexer.VEC2 -> ".xy"; + case GLSLLexer.VEC3 -> ".xyz"; + default -> ""; + }; + } + private static void foldConstantAttribute(Transformer transformer, String name, String floatVal, String vec2Val, String vec3Val, String vec4Val) { final int type = transformer.findType(name); if (type == 0) { diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java index 23bbc0592..30c1500ad 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java @@ -1,6 +1,8 @@ package net.coderbot.iris.pipeline.transform; -import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import org.taumc.glsl.Transformer; import java.util.HashMap; @@ -16,24 +18,37 @@ class CoreTransformHelper { * Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix. */ static void injectMatrixUniforms(Transformer transformer) { - injectMatrixUniforms(transformer, false); + injectMatrixUniforms(transformer, Instancing.NONE); } - static void injectMatrixUniforms(Transformer transformer, boolean instancedVertex) { - if (instancedVertex) { - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL0 + ") in vec4 iris_InstMat0;"); - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL1 + ") in vec4 iris_InstMat1;"); - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL2 + ") in vec4 iris_InstMat2;"); - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL3 + ") in vec4 iris_InstMat3;"); - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_COLOR + ") in vec4 iris_InstColor;"); - transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_LIGHTMAP + ") in vec2 iris_InstLightmap;"); - transformer.injectVariable("mat4 iris_ModelViewMatrix;"); - transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;"); - transformer.injectVariable("mat3 iris_NormalMatrix;"); - } else { - transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); - transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); - transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + static void injectMatrixUniforms(Transformer transformer, Instancing instancing) { + switch (instancing) { + case PARTICLE -> { + transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.POSITION.getAttributeLocation() + ") in vec3 iris_ParticleOffset;"); + transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation() + ") in vec2 iris_ParticleCorner;"); + injectAttributeDecls(transformer, instancing); + transformer.injectVariable("vec4 iris_Vertex;"); + transformer.injectVariable("vec4 iris_Color;"); + transformer.injectVariable("vec4 iris_MultiTexCoord0;"); + transformer.injectVariable("vec4 iris_MultiTexCoord1;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + } + case TEMPLATE, CUBE -> { + injectAttributeDecls(transformer, instancing); + transformer.injectVariable("mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("mat3 iris_NormalMatrix;"); + if (!declaresInvariantPosition(transformer)) { + transformer.injectVariable("invariant gl_Position;"); + } + } + case NONE -> { + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + } } transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;"); transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;"); @@ -58,6 +73,25 @@ class CoreTransformHelper { transformer.replaceExpression("gl_TextureMatrix", "mat4[8](iris_TextureMatrix, iris_LightmapTextureMatrix, mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0))"); } + private static void injectAttributeDecls(Transformer transformer, Instancing instancing) { + for (String decl : InstancedGlslHelpers.attributeDecls("iris_", instancing)) { + transformer.injectVariable(decl); + } + } + + private static boolean declaresInvariantPosition(Transformer transformer) { + final boolean[] found = new boolean[1]; + transformer.mutateTree(root -> { + for (int i = 0; i < root.getChildCount(); i++) { + if ("invariantgl_Position;".equals(root.getChild(i).getText())) { + found[0] = true; + return; + } + } + }); + return found[0]; + } + /** * Inject vertex attributes and ftransform() replacement for composite/depth shaders. Uses locations matching FullScreenQuadRenderer's POSITION_TEXTURE VAO layout. */ diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/EntityPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/EntityPatcher.java index 9f51882a3..bc1af126b 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/EntityPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/EntityPatcher.java @@ -1,18 +1,120 @@ package net.coderbot.iris.pipeline.transform; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import org.taumc.glsl.Transformer; +import org.taumc.glsl.grammar.GLSLParser; class EntityPatcher { public static void patchEntityId(Transformer transformer, AttributeParameters parameters) { - injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;"); - injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;"); - injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;"); + if (!hasInstanceAttributes(parameters)) { + injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;"); + injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;"); + injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;"); + return; + } + + removeIfDeclared(transformer, "entityId"); + removeIfDeclared(transformer, "blockEntityId"); + removeIfDeclared(transformer, "currentRenderedItemId"); + + final String geometryIn = parameters.hasTesselation ? "iris_entityInfoTES" : "iris_entityInfo"; + final String info = switch (parameters.type) { + case GEOMETRY -> geometryIn + "[0]"; + case TESSELATION_CONTROL -> "iris_entityInfo[gl_InvocationID]"; + case TESSELATION_EVAL -> "iris_entityInfoTCS[0]"; + default -> "iris_entityInfo"; + }; + transformer.replaceExpression("entityId", info + ".x", GLSLParser::postfix_expression); + transformer.replaceExpression("blockEntityId", info + ".y", GLSLParser::postfix_expression); + transformer.replaceExpression("currentRenderedItemId", info + ".z", GLSLParser::postfix_expression); + + switch (parameters.type) { + case VERTEX -> { + if (!transformer.hasVariable("iris_Entity")) { + transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_ENTITY + ") in ivec4 iris_Entity;"); + } + transformer.injectVariable("flat out ivec3 iris_entityInfo;"); + transformer.prependMain("iris_entityInfo = iris_Entity.xyz;"); + } + case TESSELATION_CONTROL -> { + transformer.injectVariable("flat out ivec3 iris_entityInfoTCS[];"); + transformer.injectVariable("flat in ivec3 iris_entityInfo[];"); + transformer.prependMain("iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];"); + } + case TESSELATION_EVAL -> { + transformer.injectVariable("flat out ivec3 iris_entityInfoTES;"); + transformer.injectVariable("flat in ivec3 iris_entityInfoTCS[];"); + transformer.prependMain("iris_entityInfoTES = iris_entityInfoTCS[0];"); + } + case GEOMETRY -> { + transformer.injectVariable("flat out ivec3 iris_entityInfoGS;"); + transformer.injectVariable("flat in ivec3 " + geometryIn + "[];"); + transformer.prependMain("iris_entityInfoGS = " + geometryIn + "[0];"); + } + case FRAGMENT -> { + if (transformer.containsCall("iris_entityInfo")) { + transformer.injectVariable("flat in ivec3 iris_entityInfo;"); + if (parameters.hasGeometry) { + transformer.rename("iris_entityInfo", "iris_entityInfoGS"); + } else if (parameters.hasTesselation) { + transformer.rename("iris_entityInfo", "iris_entityInfoTES"); + } + } + } + default -> {} + } } public static void patchOverlayColor(Transformer transformer, AttributeParameters parameters) { - injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;"); + if (!hasInstanceAttributes(parameters)) { + injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;"); + return; + } + + removeIfDeclared(transformer, "entityColor"); + + switch (parameters.type) { + case VERTEX -> { + transformer.injectVariable("out vec4 entityColor;"); + transformer.prependMain("{ entityColor = iris_InstOverlay; entityColor.rgb *= float(entityColor.a != 0.0); }"); + } + case TESSELATION_CONTROL -> { + transformer.replaceExpression("entityColor", "entityColor[gl_InvocationID]", GLSLParser::postfix_expression); + transformer.injectVariable("patch out vec4 entityColorTCS;"); + transformer.injectVariable("in vec4 entityColor[];"); + transformer.prependMain("entityColorTCS = entityColor[gl_InvocationID];"); + } + case TESSELATION_EVAL -> { + transformer.replaceExpression("entityColor", "entityColorTCS", GLSLParser::postfix_expression); + transformer.injectVariable("out vec4 entityColorTES;"); + transformer.injectVariable("patch in vec4 entityColorTCS;"); + transformer.prependMain("entityColorTES = entityColorTCS;"); + } + case GEOMETRY -> { + final String geometryIn = parameters.hasTesselation ? "entityColorTES" : "entityColor"; + transformer.replaceExpression("entityColor", geometryIn + "[0]", GLSLParser::postfix_expression); + transformer.injectVariable("out vec4 entityColorGS;"); + transformer.injectVariable("in vec4 " + geometryIn + "[];"); + transformer.prependMain("entityColorGS = " + geometryIn + "[0];"); + } + case FRAGMENT -> { + if (transformer.containsCall("entityColor")) { + transformer.injectVariable("in vec4 entityColor;"); + if (parameters.hasGeometry) { + transformer.rename("entityColor", "entityColorGS"); + } else if (parameters.hasTesselation) { + transformer.rename("entityColor", "entityColorTES"); + } + } + } + default -> {} + } + } + + private static boolean hasInstanceAttributes(AttributeParameters parameters) { + return parameters.instancing.hasInstanceHead(); } private static void injectUniformIfUndeclared(Transformer transformer, String name, String declaration) { @@ -20,4 +122,10 @@ class EntityPatcher { transformer.injectVariable(declaration); } } + + private static void removeIfDeclared(Transformer transformer, String name) { + if (transformer.hasVariable(name)) { + transformer.removeVariable(name); + } + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java index deb7a2b5c..c77da2ae0 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer; import com.gtnewhorizons.angelica.glsm.RenderSystem; import java.util.EnumMap; import com.gtnewhorizons.angelica.glsm.backend.BackendManager; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; @@ -138,11 +139,11 @@ public class TransformPatcher { } public static Map patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) { - return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint)); + return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, Instancing.NONE)); } - public static Map patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) { - return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint, true)); + public static Map patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint, Instancing instancing) { + return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, instancing)); } public static Map patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) { diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java index 62637df6b..5ae56d32c 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java @@ -1,26 +1,25 @@ package net.coderbot.iris.pipeline.transform.parameter; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.pipeline.transform.Patch; import net.coderbot.iris.shaderpack.texture.TextureStage; public class AttributeParameters extends Parameters { public final boolean hasGeometry; + public final boolean hasTesselation; public final InputAvailability inputs; public final boolean scrollGlint; - public final boolean instanced; + public final Instancing instancing; // WARNING: adding new fields requires updating hashCode and equals methods! - public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint) { - this(patch, hasGeometry, inputs, scrollGlint, false); - } - - public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint, boolean instanced) { + public AttributeParameters(Patch patch, boolean hasGeometry, boolean hasTesselation, InputAvailability inputs, boolean scrollGlint, Instancing instancing) { super(patch, null); this.hasGeometry = hasGeometry; + this.hasTesselation = hasTesselation; this.inputs = inputs; this.scrollGlint = scrollGlint; - this.instanced = instanced; + this.instancing = instancing; } @Override @@ -33,8 +32,9 @@ public class AttributeParameters extends Parameters { final int prime = 31; int result = super.hashCode(); result = prime * result + (hasGeometry ? 1231 : 1237); + result = prime * result + (hasTesselation ? 1231 : 1237); result = prime * result + (scrollGlint ? 1231 : 1237); - result = prime * result + (instanced ? 1231 : 1237); + result = prime * result + instancing.ordinal(); result = prime * result + ((inputs == null) ? 0 : inputs.hashCode()); return result; } @@ -50,9 +50,11 @@ public class AttributeParameters extends Parameters { AttributeParameters other = (AttributeParameters) obj; if (hasGeometry != other.hasGeometry) return false; + if (hasTesselation != other.hasTesselation) + return false; if (scrollGlint != other.scrollGlint) return false; - if (instanced != other.instanced) + if (instancing != other.instancing) return false; if (inputs == null) { if (other.inputs != null) diff --git a/src/main/resources/META-INF/angelica_at.cfg b/src/main/resources/META-INF/angelica_at.cfg index 934c97465..58df0329d 100644 --- a/src/main/resources/META-INF/angelica_at.cfg +++ b/src/main/resources/META-INF/angelica_at.cfg @@ -98,3 +98,26 @@ public net.minecraftforge.client.ForgeHooksClient worldRenderPass # worldRenderP public net.minecraft.client.renderer.culling.Frustrum field_78550_b # xPosition public net.minecraft.client.renderer.culling.Frustrum field_78551_c # yPosition public net.minecraft.client.renderer.culling.Frustrum field_78549_d # zPosition +public net.minecraft.client.particle.EntityFX field_94054_b # particleTextureIndexX +public net.minecraft.client.particle.EntityFX field_94055_c # particleTextureIndexY +public net.minecraft.client.particle.EntityFX field_70548_b # particleTextureJitterX +public net.minecraft.client.particle.EntityFX field_70549_c # particleTextureJitterY +public net.minecraft.client.particle.EntityFX field_70546_d # particleAge +public net.minecraft.client.particle.EntityFX field_70547_e # particleMaxAge +public net.minecraft.client.particle.EntityFX field_70544_f # particleScale +public net.minecraft.client.particle.EntityFX field_70552_h # particleRed +public net.minecraft.client.particle.EntityFX field_70553_i # particleGreen +public net.minecraft.client.particle.EntityFX field_70551_j # particleBlue +public net.minecraft.client.particle.EntityFX field_82339_as # particleAlpha + +public net.minecraft.client.particle.EntityFlameFX field_70562_a # flameScale +public net.minecraft.client.particle.EntityLavaFX field_70586_a # lavaParticleScale +public net.minecraft.client.particle.EntityPortalFX field_70571_a # portalParticleScale +public net.minecraft.client.particle.EntitySmokeFX field_70587_a # smokeParticleScale +public net.minecraft.client.particle.EntityCloudFX field_70569_a +public net.minecraft.client.particle.EntityCritFX field_70561_a # initialParticleScale +public net.minecraft.client.particle.EntityHeartFX field_70575_a # particleScaleOverTime +public net.minecraft.client.particle.EntityNoteFX field_70585_a # noteParticleScale +public net.minecraft.client.particle.EntityReddustFX field_70570_a # reddustParticleScale +public net.minecraft.client.particle.EntitySnowShovelFX field_70588_a # snowDigParticleScale +public net.minecraft.client.particle.EntityFireworkSparkFX field_92048_ay diff --git a/src/main/resources/assets/angelica/lang/en_US.lang b/src/main/resources/assets/angelica/lang/en_US.lang index b954db44b..bef37ebb8 100644 --- a/src/main/resources/assets/angelica/lang/en_US.lang +++ b/src/main/resources/assets/angelica/lang/en_US.lang @@ -279,7 +279,7 @@ options.angelica.shadowGraphHorizonScale=Shadow Graph Horizon Tightening options.angelica.shadowGraphHorizonScale.tooltip=Adjusts the rate the shadow map rebuilds when when a celestial body is near the horizon. Rate is sinusoidal. options.angelica.shadowGraphHorizonScale.off=OFF options.angelica.itemdisplaylistcount=Item Renderer Cache Limit -options.angelica.itemdisplaylistcount.tooltip=The upper limit of VBO's to cache in the optimized item renderer. Higher values will significantly increase performance, but may result in increased VRAM usage. +options.angelica.itemdisplaylistcount.tooltip=The upper limit of item meshes to cache in the optimized item renderer, covering VBOs and batched dropped and held item templates. Higher values will significantly increase performance, but may result in increased memory and VRAM usage. options.angelica.threadedChunkBuilding=Threaded Chunk Building options.angelica.threadedChunkBuilding.tooltip=If enabled, chunk meshing will be performed on multiple threads in parallel, significantly improving chunk build speed. Disable if you experience rendering issues with mods that have custom block renderers. Requires renderer reload to take effect. options.angelica.gpuCullingMode=GPU Culling Mode @@ -328,5 +328,5 @@ sodium.options.upload_method.tooltip=Changes the way the data gets streamed to t sodium.options.upload_method.buffer_data=BufferData sodium.options.upload_method.buffer_subdata=BufferSubData sodium.options.upload_method.map_buffer=MapBufferRange -sodium.options.enable_deferred_batching.name=Deferred Particle Batching -sodium.options.enable_deferred_batching.tooltip=Batches particle draw calls into fewer merged draws per layer. Disable if particles render incorrectly. +sodium.options.enable_deferred_batching.name=Particle Batching +sodium.options.enable_deferred_batching.tooltip=Draws particles as instanced quads, or merged draws where instancing is unavailable. Disable if particles render incorrectly. diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java index d01e5b7ec..fe8f44463 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinMinecraft_FrameHook.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica; import com.gtnewhorizons.angelica.glsm.hooks.FrameHooks; +import com.gtnewhorizons.angelica.rendering.GlintClock; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; @@ -25,6 +26,11 @@ public class MixinMinecraft_FrameHook { FrameHooks.bootstrapFirstFrame(); } + @Inject(method = "runGameLoop", at = @At("HEAD")) + private void angelica$beginGlintFrame(CallbackInfo ci) { + GlintClock.beginFrame(Minecraft.getSystemTime()); + } + @Inject(method = "func_147120_f"/*resetSize*/, at = @At("HEAD")) private void angelica$onFrameEnd(CallbackInfo ci) { FrameHooks.frameEnd(); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_DeferredEntityOverlay.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_DeferredEntityOverlay.java index de64d0dbe..91e734586 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_DeferredEntityOverlay.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_DeferredEntityOverlay.java @@ -1,8 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; import com.gtnewhorizons.angelica.rendering.DeferredEntityOverlay; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RendererLivingEntity; import net.minecraft.entity.Entity; @@ -14,24 +13,14 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = RendererLivingEntity.class, priority = 1200) public class MixinRendererLivingEntity_DeferredEntityOverlay { - /** - * Intercepts the first renderPassModel.render() call in the shouldRenderPass loop. - * When an entity overlay pass is active, captures the animation params and modelview - * matrix for deferred rendering, skipping the immediate render. - */ - @WrapOperation( + @WrapWithCondition( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V", ordinal = 0) ) - private void angelica$maybeDeferOverlay(ModelBase model, Entity entity, - float limbSwing, float limbSwingAmount, float ageInTicks, - float headYaw, float headPitch, float scale, - Operation original) { - if (DeferredEntityOverlay.isOverlayPassActive()) { - DeferredEntityOverlay.deferRender(limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch, scale); - } else { - original.call(model, entity, limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch, scale); - } + private boolean angelica$maybeDeferOverlay(ModelBase model, Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float headYaw, float headPitch, float scale) { + if (!DeferredEntityOverlay.isOverlayPassActive()) return true; + DeferredEntityOverlay.deferRender(limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch, scale); + return false; } /** diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_EyeDepth.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_EyeDepth.java index a8a7a357d..c5ac54dd3 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_EyeDepth.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_EyeDepth.java @@ -1,26 +1,19 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.renderer.entity.RenderDragon; -import net.minecraft.client.renderer.entity.RenderEnderman; -import net.minecraft.client.renderer.entity.RenderSpider; +import com.gtnewhorizons.angelica.helpers.RendererLivingEntityHelper; import net.minecraft.client.renderer.entity.RendererLivingEntity; -import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(RendererLivingEntity.class) public class MixinRendererLivingEntity_EyeDepth { - /** - * Push the eye out just a tad towards the camera. Fixes Z-Fighting on the eyes. - */ - @WrapOperation( + @Inject( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V"), slice = @Slice( @@ -28,14 +21,22 @@ public class MixinRendererLivingEntity_EyeDepth { to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V") ) ) - private void angelica$eyePassPolygonOffset(ModelBase instance, Entity entity, float a, float b, float c, float d, float e, float f, Operation original) { - if (!((Object) this instanceof RenderSpider) && !((Object) this instanceof RenderEnderman) && !((Object) this instanceof RenderDragon)) { - original.call(instance, entity, a, b, c, d, e, f); - return; - } + private void angelica$eyePassPolygonOffset(CallbackInfo ci) { + if (!RendererLivingEntityHelper.hasEyePass(this)) return; GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); GLStateManager.glPolygonOffset(-1.0f, -1.0f); - original.call(instance, entity, a, b, c, d, e, f); + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V", shift = At.Shift.AFTER), + slice = @Slice( + from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I"), + to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V") + ) + ) + private void angelica$eyePassPolygonOffsetEnd(CallbackInfo ci) { + if (!RendererLivingEntityHelper.hasEyePass(this)) return; GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); GLStateManager.glPolygonOffset(0.0f, 0.0f); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java index f1fc9c35d..8701ba0e7 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java @@ -2,8 +2,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import net.coderbot.iris.Iris; import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; @@ -32,6 +31,7 @@ public class MixinRendererLivingEntity_OverlayTint { @Unique private boolean angelica$skipReRender; @Unique private boolean angelica$ffpOverlayActive; @Unique private boolean angelica$shaderEntityColorActive; + @Unique private boolean angelica$untint; @Inject( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", @@ -78,10 +78,7 @@ public class MixinRendererLivingEntity_OverlayTint { } } - /** - * Skip the vanilla re-render block. - */ - @WrapOperation( + @WrapWithCondition( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V"), @@ -92,16 +89,11 @@ public class MixinRendererLivingEntity_OverlayTint { ), require = 1, expect = 1 ) - private void angelica$skipOverlayReRender(ModelBase model, Entity entity, - float p1, float p2, float p3, float p4, float p5, float p6, Operation original) { - if (angelica$skipReRender) return; - original.call(model, entity, p1, p2, p3, p4, p5, p6); + private boolean angelica$skipOverlayReRender(ModelBase model, Entity entity, float p1, float p2, float p3, float p4, float p5, float p6) { + return !angelica$skipReRender; } - /** - * Skip the overlay on additive passes (emissive eyes, enchantment glint). - */ - @WrapOperation( + @Inject( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V"), @@ -113,22 +105,38 @@ public class MixinRendererLivingEntity_OverlayTint { ), require = 1, expect = 1 ) - private void angelica$untintAdditivePass(ModelBase model, Entity entity, - float p1, float p2, float p3, float p4, float p5, float p6, Operation original) { - if (!angelica$skipReRender || !angelica$isAdditivePass()) { - original.call(model, entity, p1, p2, p3, p4, p5, p6); - return; - } + private void angelica$untintAdditivePass(CallbackInfo ci) { + angelica$untint = false; + if (!angelica$skipReRender || !angelica$isAdditivePass()) return; if (angelica$ffpOverlayActive) { GLStateManager.setOverlayColor(0.0F, 0.0F, 0.0F, 0.0F); - original.call(model, entity, p1, p2, p3, p4, p5, p6); - GLStateManager.setOverlayColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + angelica$untint = true; } else if (angelica$shaderEntityColorActive) { CapturedRenderingState.INSTANCE.setCurrentEntityColor(0.0F, 0.0F, 0.0F, 0.0F); - original.call(model, entity, p1, p2, p3, p4, p5, p6); + angelica$untint = true; + } + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V", + shift = At.Shift.AFTER), + slice = @Slice( + from = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I"), + to = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V") + ), + require = 1, expect = 1 + ) + private void angelica$retintAfterAdditivePass(CallbackInfo ci) { + if (!angelica$untint) return; + angelica$untint = false; + if (angelica$ffpOverlayActive) { + GLStateManager.setOverlayColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + } else if (angelica$shaderEntityColorActive) { CapturedRenderingState.INSTANCE.setCurrentEntityColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); - } else { - original.call(model, entity, p1, p2, p3, p4, p5, p6); } } @@ -146,6 +154,7 @@ public class MixinRendererLivingEntity_OverlayTint { angelica$shaderEntityColorActive = false; } angelica$skipReRender = false; + angelica$untint = false; } @Unique diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinItemRenderer_Instanced.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinItemRenderer_Instanced.java new file mode 100644 index 000000000..718341c74 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinItemRenderer_Instanced.java @@ -0,0 +1,74 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.rendering.GlintClock; +import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.ItemRenderer; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer.ItemRenderType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(ItemRenderer.class) +public abstract class MixinItemRenderer_Instanced { + + @WrapOperation( + method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 0 + ) + ) + private void angelica$instanceHeldIcon(Tessellator tessellator, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original, @Local(argsOnly = true) ItemStack stack, @Local(argsOnly = true) ItemRenderType type) { + DroppedItemInstancer.icon(angelica$batchable(type) ? stack : null, tessellator, maxU, minV, minU, maxV, width, height, thickness, original); + } + + @WrapOperation( + method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", + at = { + @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 1 + ), + @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 2 + ) + } + ) + private void angelica$instanceHeldGlint(Tessellator tessellator, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + DroppedItemInstancer.glint(tessellator, maxU, minV, minU, maxV, width, height, thickness, original); + } + + @WrapOperation( + method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/RenderBlocks;renderBlockAsItem(Lnet/minecraft/block/Block;IF)V" + ) + ) + private void angelica$instanceHeldBlock(RenderBlocks renderBlocks, Block block, int meta, float brightness, Operation original, @Local(argsOnly = true) ItemStack stack, @Local(argsOnly = true) ItemRenderType type) { + DroppedItemInstancer.block(angelica$batchable(type) ? stack : null, renderBlocks, block, meta, brightness, false, original); + } + + @Redirect( + method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;getSystemTime()J") + ) + private long angelica$globalGlintTime() { + return GlintClock.millis(); + } + + private static boolean angelica$batchable(ItemRenderType type) { + return type == ItemRenderType.EQUIPPED || type == ItemRenderType.ENTITY; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelBox_CubeParams.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelBox_CubeParams.java new file mode 100644 index 000000000..888bd1ef7 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinModelBox_CubeParams.java @@ -0,0 +1,35 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.mixins.interfaces.ModelBoxData; +import com.gtnewhorizons.angelica.rendering.tesr.ModelBoxCapture; +import net.minecraft.client.model.ModelBox; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.model.TexturedQuad; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ModelBox.class) +public abstract class MixinModelBox_CubeParams implements ModelBoxData { + + @Shadow + private TexturedQuad[] quadList; + + @Unique + private CubeParams angelica$cubeParams; + + @Inject(method = "", at = @At("RETURN")) + private void angelica$captureCubeParams(ModelRenderer part, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate, CallbackInfo ci) { + if (((Object) this).getClass() != ModelBox.class) return; + this.angelica$cubeParams = ModelBoxCapture.capture(this.quadList, part.textureWidth, part.textureHeight, part.mirror, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + } + + @Override + public CubeParams angelica$cubeParams() { + return this.angelica$cubeParams; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderItem_Instanced.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderItem_Instanced.java new file mode 100644 index 000000000..77799df29 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRenderItem_Instanced.java @@ -0,0 +1,98 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.GlintClock; +import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(RenderItem.class) +public abstract class MixinRenderItem_Instanced { + + @WrapOperation( + method = "renderDroppedItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/util/IIcon;IFFFFI)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 0 + ) + ) + private void angelica$instanceDroppedIcon(Tessellator tessellator, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original, @Local ItemStack stack) { + DroppedItemInstancer.icon(stack, tessellator, maxU, minV, minU, maxV, width, height, thickness, original); + } + + @WrapOperation( + method = "renderDroppedItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/util/IIcon;IFFFFI)V", + at = { + @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 1 + ), + @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", + ordinal = 2 + ) + } + ) + private void angelica$instanceDroppedGlint(Tessellator tessellator, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation original) { + DroppedItemInstancer.glint(tessellator, maxU, minV, minU, maxV, width, height, thickness, original); + } + + @Redirect( + method = "renderDroppedItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/util/IIcon;IFFFFI)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;getSystemTime()J") + ) + private long angelica$globalGlintTime() { + return GlintClock.millis(); + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/item/EntityItem;DDDFF)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraftforge/client/ForgeHooksClient;renderEntityItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/item/ItemStack;FFLjava/util/Random;Lnet/minecraft/client/renderer/texture/TextureManager;Lnet/minecraft/client/renderer/RenderBlocks;I)Z", + remap = false + ) + ) + private void angelica$beginCustomItemDraws(CallbackInfo ci) { + BatchEligibility.beginExpectedDraws(GLStateManager.drawCalls); + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/item/EntityItem;DDDFF)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraftforge/client/ForgeHooksClient;renderEntityItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/item/ItemStack;FFLjava/util/Random;Lnet/minecraft/client/renderer/texture/TextureManager;Lnet/minecraft/client/renderer/RenderBlocks;I)Z", + shift = At.Shift.AFTER, + remap = false + ) + ) + private void angelica$endCustomItemDraws(CallbackInfo ci) { + BatchEligibility.endExpectedDraws(GLStateManager.drawCalls); + } + + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/item/EntityItem;DDDFF)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/RenderBlocks;renderBlockAsItem(Lnet/minecraft/block/Block;IF)V" + ) + ) + private void angelica$instanceDroppedBlock(RenderBlocks renderBlocks, Block block, int meta, float brightness, Operation original, @Local ItemStack stack) { + DroppedItemInstancer.block(stack, renderBlocks, block, meta, brightness, true, original); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_ShadowBatch.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_ShadowBatch.java new file mode 100644 index 000000000..011a88803 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRender_ShadowBatch.java @@ -0,0 +1,28 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Render.class) +public abstract class MixinRender_ShadowBatch { + + @Shadow + protected float shadowSize; + + @Shadow + protected RenderManager renderManager; + + @Inject(method = "renderShadow(Lnet/minecraft/entity/Entity;DDDFF)V", at = @At("HEAD"), cancellable = true) + private void angelica$batchShadow(Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, CallbackInfo ci) { + if (ModelPartBatcher.recordShadow(renderManager.worldObj, entity, x, y, z, shadowAlpha, partialTicks, shadowSize)) { + ci.cancel(); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_EquippedDraws.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_EquippedDraws.java new file mode 100644 index 000000000..ec99e04d6 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_EquippedDraws.java @@ -0,0 +1,40 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.OperationArgs; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.renderer.entity.RendererLivingEntity; +import net.minecraft.entity.EntityLivingBase; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(RendererLivingEntity.class) +public abstract class MixinRendererLivingEntity_EquippedDraws { + + @Unique private static final Object[] angelica$equippedArgs = new Object[3]; + + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V" + ) + ) + private void angelica$countEquippedDraws(RendererLivingEntity self, EntityLivingBase entity, float partialTicks, Operation original) { + final Object[] args = angelica$equippedArgs; + args[0] = self; + args[1] = entity; + args[2] = OperationArgs.boxed(args[2], partialTicks); + BatchEligibility.beginExpectedDraws(GLStateManager.drawCalls); + try { + original.call(args); + } finally { + args[0] = null; + args[1] = null; + BatchEligibility.endExpectedDraws(GLStateManager.drawCalls); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java new file mode 100644 index 000000000..065fd9828 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_GlintClock.java @@ -0,0 +1,35 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.rendering.GlintClock; +import net.minecraft.client.renderer.entity.RendererLivingEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Group; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(RendererLivingEntity.class) +public abstract class MixinRendererLivingEntity_GlintClock { + + @Group(name = "angelica$globalGlintPhase", min = 1, max = 1) + @Redirect( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glTranslatef(FFF)V", ordinal = 1, remap = false) + ) + private void angelica$globalGlintPhase(float x, float y, float z) { + GlintClock.translateArmorGlint(); + } + + @Group(name = "angelica$globalGlintPhase", min = 1, max = 1) + @Redirect( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At( + value = "INVOKE", + target = "Lcom/gtnewhorizons/angelica/glsm/GLStateManager;glTranslatef(FFF)V", + ordinal = 1, + remap = false + ) + ) + private void angelica$globalGlintPhaseGlsm(float x, float y, float z) { + GlintClock.translateArmorGlint(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_ModelPassDraws.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_ModelPassDraws.java new file mode 100644 index 000000000..5e884f1a6 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/entity/MixinRendererLivingEntity_ModelPassDraws.java @@ -0,0 +1,43 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.entity; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.OperationArgs; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.renderer.entity.RendererLivingEntity; +import net.minecraft.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(RendererLivingEntity.class) +public abstract class MixinRendererLivingEntity_ModelPassDraws { + + @Unique private static final Object[] angelica$modelPassArgs = new Object[8]; + + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V") + ) + private void angelica$countModelPassDraws(ModelBase model, Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float headYaw, float headPitch, float scale, Operation original) { + final Object[] args = angelica$modelPassArgs; + args[0] = model; + args[1] = entity; + args[2] = OperationArgs.boxed(args[2], limbSwing); + args[3] = OperationArgs.boxed(args[3], limbSwingAmount); + args[4] = OperationArgs.boxed(args[4], ageInTicks); + args[5] = OperationArgs.boxed(args[5], headYaw); + args[6] = OperationArgs.boxed(args[6], headPitch); + args[7] = OperationArgs.boxed(args[7], scale); + BatchEligibility.beginExpectedDraws(GLStateManager.drawCalls); + try { + original.call(args); + } finally { + args[0] = null; + args[1] = null; + BatchEligibility.endExpectedDraws(GLStateManager.drawCalls); + } + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/optimizations/MixinRenderBiped_ArmorResource.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/optimizations/MixinRenderBiped_ArmorResource.java new file mode 100644 index 000000000..35dbf6ff5 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/optimizations/MixinRenderBiped_ArmorResource.java @@ -0,0 +1,33 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.optimizations; + +import com.gtnewhorizons.angelica.rendering.ArmorTexturePaths; +import net.minecraft.client.renderer.entity.RenderBiped; +import net.minecraft.entity.Entity; +import net.minecraft.item.ItemArmor; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.ForgeHooksClient; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.Map; + +@Mixin(RenderBiped.class) +public class MixinRenderBiped_ArmorResource { + @Shadow @Final private static Map field_110859_k/*armorTextureCache*/; + + @Overwrite(remap = false) + public static ResourceLocation getArmorResource(Entity entity, ItemStack stack, int slot, String type) { + final ItemArmor item = (ItemArmor) stack.getItem(); + final String prefix = RenderBiped.bipedArmorFilenamePrefix[item.renderIndex]; + final String path = ForgeHooksClient.getArmorTexture(entity, stack, ArmorTexturePaths.path(prefix, item.renderIndex, slot, type), slot, type); + ResourceLocation rl = field_110859_k/*armorTextureCache*/.get(path); + if (rl == null) { + rl = new ResourceLocation(path); + field_110859_k/*armorTextureCache*/.put(path, rl); + } + return rl; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_DeferredBatch.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_DeferredBatch.java deleted file mode 100644 index 53bb8c30c..000000000 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_DeferredBatch.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gtnewhorizons.angelica.mixins.early.angelica.particles; - -import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher; -import com.gtnewhorizons.angelica.proxy.ClientProxy; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.entity.Entity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * Captures individual particle draw() calls and merges them into a single draw call per unique GL state. - */ -@Mixin(EffectRenderer.class) -public class MixinEffectRenderer_DeferredBatch { - - @Inject(method = "renderParticles", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/Tessellator;startDrawingQuads()V", - shift = At.Shift.AFTER)) - private void angelica$enterDeferredMode(Entity player, float partialTickTime, CallbackInfo ci) { - if (ClientProxy.options() != null && ClientProxy.options().advanced.enableDeferredBatching) { - DeferredDrawBatcher.enter(); - } - } - - @Inject(method = "renderParticles", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/Tessellator;draw()I", - shift = At.Shift.BEFORE)) - private void angelica$exitDeferredAndFlush(Entity player, float partialTickTime, CallbackInfo ci) { - if (DeferredDrawBatcher.isActive()) { - DeferredDrawBatcher.exitAndFlush(); - } - } -} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_ParticleBatch.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_ParticleBatch.java new file mode 100644 index 000000000..1bdbb945f --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/particles/MixinEffectRenderer_ParticleBatch.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.particles; + +import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(value = EffectRenderer.class, priority = 900) +public class MixinEffectRenderer_ParticleBatch { + + @WrapOperation(method = "renderParticles", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/particle/EntityFX;renderParticle(Lnet/minecraft/client/renderer/Tessellator;FFFFFF)V")) + private void angelica$captureParticle(EntityFX particle, Tessellator tessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation original) { + ParticleInstancer.renderParticle(particle, tessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original); + } + + @Inject(method = "renderParticles", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/Tessellator;draw()I", + shift = At.Shift.BEFORE)) + private void angelica$endLayer(Entity player, float partialTickTime, CallbackInfo ci) { + ParticleInstancer.endLayer(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/culling/MixinEffectRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/culling/MixinEffectRenderer.java index 42abd4a95..600eb86da 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/culling/MixinEffectRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/features/culling/MixinEffectRenderer.java @@ -2,12 +2,13 @@ package com.gtnewhorizons.angelica.mixins.early.celeritas.features.culling; import com.gtnewhorizons.angelica.proxy.ClientProxy; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.rendering.particles.ParticleCulling; +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; -import net.minecraft.tileentity.TileEntity; -import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -15,51 +16,42 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -/** - * EffectRenderer mixin for celeritas particle culling. - * Culls particles that are outside the view frustum. - */ @Mixin(EffectRenderer.class) public class MixinEffectRenderer { @Unique - private Viewport cullingViewport; + private static final Tracy.ZoneId angelica$Z_PARTICLE_PASS = Tracy.zoneId("particlePass", Tracy.COLOR_CLIENT); @Unique - private void setupCullingViewport() { + private CeleritasWorldRenderer cullingRenderer; + + @Unique + private boolean particleVisible; + + @Inject(method = {"renderParticles", "renderLitParticles"}, at = @At("HEAD")) + private void setupViewport(Entity player, float partialTickTime, CallbackInfo ci) { final boolean useCulling = ClientProxy.options().advanced.useParticleCulling; if(useCulling) { - this.cullingViewport = CeleritasWorldRenderer.getInstance().getLastViewport(); + this.cullingRenderer = CeleritasWorldRenderer.getInstanceOrNull(); } else { - this.cullingViewport = null; + this.cullingRenderer = null; } + if (Tracy.ENABLED) Tracy.beginZone(angelica$Z_PARTICLE_PASS); } - @Inject(method = "renderParticles", at = @At("HEAD")) - private void setupViewport$standard(Entity player, float partialTickTime, CallbackInfo ci) { - setupCullingViewport(); + @Inject(method = {"renderParticles", "renderLitParticles"}, at = @At("RETURN")) + private void endParticlePass(Entity player, float partialTickTime, CallbackInfo ci) { + if (Tracy.ENABLED) Tracy.endZone(); } - @Redirect(method = "renderParticles", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/EntityFX;renderParticle(Lnet/minecraft/client/renderer/Tessellator;FFFFFF)V")) - private void renderParticles(EntityFX particle, Tessellator tessellator, float partialTicks, float rotationX, float rotationZ, float rotationYZ, float rotationXY, float rotationXZ) { - if (cullingViewport == null || particle.boundingBox == TileEntity.INFINITE_EXTENT_AABB || - cullingViewport.isBoxVisible(particle.boundingBox.minX, particle.boundingBox.minY, particle.boundingBox.minZ, - particle.boundingBox.maxX, particle.boundingBox.maxY, particle.boundingBox.maxZ)) { - particle.renderParticle(tessellator, partialTicks, rotationX, rotationZ, rotationYZ, rotationXY, rotationXZ); - } + @Redirect(method = {"renderParticles", "renderLitParticles"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/EntityFX;getBrightnessForRender(F)I")) + private int cullParticles(EntityFX particle, float partialTicks) { + this.particleVisible = ParticleCulling.visible(this.cullingRenderer, particle.posX, particle.posY, particle.posZ); + return this.particleVisible ? particle.getBrightnessForRender(partialTicks) : 0; } - @Inject(method = "renderLitParticles", at = @At("HEAD")) - private void setupViewport$lit(Entity player, float partialTickTime, CallbackInfo ci) { - setupCullingViewport(); - } - - @Redirect(method = "renderLitParticles", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/EntityFX;renderParticle(Lnet/minecraft/client/renderer/Tessellator;FFFFFF)V")) - private void renderLitParticles(EntityFX particle, Tessellator tessellator, float partialTicks, float rotationX, float rotationZ, float rotationYZ, float rotationXY, float rotationXZ) { - if (cullingViewport == null || particle.boundingBox == TileEntity.INFINITE_EXTENT_AABB || - cullingViewport.isBoxVisible(particle.boundingBox.minX, particle.boundingBox.minY, particle.boundingBox.minZ, - particle.boundingBox.maxX, particle.boundingBox.maxY, particle.boundingBox.maxZ)) { - particle.renderParticle(tessellator, partialTicks, rotationX, rotationZ, rotationYZ, rotationXY, rotationXZ); - } + @WrapWithCondition(method = {"renderParticles", "renderLitParticles"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/EntityFX;renderParticle(Lnet/minecraft/client/renderer/Tessellator;FFFFFF)V")) + private boolean renderParticles(EntityFX particle, Tessellator tessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY) { + return this.particleVisible; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinDroppedItemGlintEdges.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinDroppedItemGlintEdges.java index ca18f5c65..30b35c605 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinDroppedItemGlintEdges.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinDroppedItemGlintEdges.java @@ -1,41 +1,33 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.llamalad7.mixinextras.sugar.Local; import net.minecraft.client.renderer.entity.RenderItem; -import net.minecraft.entity.item.EntityItem; import net.minecraft.util.IIcon; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArgs; -import org.spongepowered.asm.mixin.injection.invoke.arg.Args; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.Slice; @Mixin(RenderItem.class) public class MixinDroppedItemGlintEdges { - /** - * Fix enchantment glint not rendering on item edges by using the actual icon dimensions - * instead of hardcoded 255x255. This ensures the edge geometry calculation matches the - * main item render, allowing GL_EQUAL depth test to pass on all edges. - - * First glint pass (ordinal 1) - */ - @ModifyArgs( + @ModifyArg( method = "renderDroppedItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/util/IIcon;IFFFFI)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1) + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1)), + index = 5 ) - private void iris$fixFirstGlintDimensions(Args args, EntityItem entity, IIcon icon, int count, float partialTicks, float r, float g, float b, int pass) { - args.set(5, icon.getIconWidth()); - args.set(6, icon.getIconHeight()); + private int iris$glintWidth(int width, @Local(argsOnly = true) IIcon icon) { + return icon.getIconWidth(); } - /** - * Second glint pass (ordinal 2) - */ - @ModifyArgs( + @ModifyArg( method = "renderDroppedItem(Lnet/minecraft/entity/item/EntityItem;Lnet/minecraft/util/IIcon;IFFFFI)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 2) + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1)), + index = 6 ) - private void iris$fixSecondGlintDimensions(Args args, EntityItem entity, IIcon icon, int count, float partialTicks, float r, float g, float b, int pass) { - args.set(5, icon.getIconWidth()); - args.set(6, icon.getIconHeight()); + private int iris$glintHeight(int height, @Local(argsOnly = true) IIcon icon) { + return icon.getIconHeight(); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEffectRenderer_Particles.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEffectRenderer_Particles.java index cf07cfcb2..14b82daf9 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEffectRenderer_Particles.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEffectRenderer_Particles.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; import com.gtnewhorizons.angelica.rendering.ParticleRunSplitter; +import com.llamalad7.mixinextras.injector.ModifyReceiver; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; @@ -8,12 +9,10 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -/** - * Splits the particle batch between {@code gbuffers_particles} and {@code gbuffers_particles_translucent}. - */ -@Mixin(EffectRenderer.class) +@Mixin(value = EffectRenderer.class, priority = 900) public class MixinEffectRenderer_Particles { + @Redirect( method = "renderParticles", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/Tessellator;startDrawingQuads()V") @@ -23,13 +22,13 @@ public class MixinEffectRenderer_Particles { tessellator.startDrawingQuads(); } - @Redirect( + @ModifyReceiver( method = "renderParticles", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/EntityFX;getBrightnessForRender(F)I"), require = 1 ) - private int iris$splitRun(EntityFX particle, float partialTicks) { + private EntityFX iris$splitRun(EntityFX particle, float partialTicks) { ParticleRunSplitter.splitIfNeeded(particle, Tessellator.instance, partialTicks); - return particle.getBrightnessForRender(partialTicks); + return particle; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinHeldItemGlintEdges.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinHeldItemGlintEdges.java index 1c6d5bcf6..1aedbc102 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinHeldItemGlintEdges.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinHeldItemGlintEdges.java @@ -1,50 +1,33 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.llamalad7.mixinextras.sugar.Local; import net.minecraft.client.renderer.ItemRenderer; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import net.minecraftforge.client.IItemRenderer.ItemRenderType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArgs; -import org.spongepowered.asm.mixin.injection.invoke.arg.Args; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.Slice; -/** - * Fix enchantment glint not rendering on item edges by using the actual icon dimensions - * instead of hardcoded 256x256. This ensures the edge geometry calculation matches the - * main item render, allowing GL_EQUAL depth test to pass on all edges. - */ @Mixin(ItemRenderer.class) public class MixinHeldItemGlintEdges { - /** - * First glint pass (ordinal 1) - */ - @ModifyArgs( + @ModifyArg( method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1) + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1)), + index = 5 ) - private void iris$fixFirstGlintDimensions(Args args, EntityLivingBase entity, ItemStack stack, int pass, ItemRenderType type) { - IIcon icon = entity.getItemIcon(stack, pass); - if (icon != null) { - args.set(5, icon.getIconWidth()); - args.set(6, icon.getIconHeight()); - } + private int iris$glintWidth(int width, @Local IIcon icon) { + return icon.getIconWidth(); } - /** - * Second glint pass (ordinal 2) - */ - @ModifyArgs( + @ModifyArg( method = "renderItem(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;ILnet/minecraftforge/client/IItemRenderer$ItemRenderType;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 2) + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V"), + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemIn2D(Lnet/minecraft/client/renderer/Tessellator;FFFFIIF)V", ordinal = 1)), + index = 6 ) - private void iris$fixSecondGlintDimensions(Args args, EntityLivingBase entity, ItemStack stack, int pass, ItemRenderType type) { - IIcon icon = entity.getItemIcon(stack, pass); - if (icon != null) { - args.set(5, icon.getIconWidth()); - args.set(6, icon.getIconHeight()); - } + private int iris$glintHeight(int height, @Local IIcon icon) { + return icon.getIconHeight(); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderBiped.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderBiped.java index db6193dcb..53d70e85d 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderBiped.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderBiped.java @@ -1,14 +1,12 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import net.coderbot.iris.uniforms.ItemIdManager; -import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderBiped; import net.minecraft.entity.EntityLiving; -import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * Mixin to set currentRenderedItem ID when rendering armor and equipment on biped entities. @@ -22,19 +20,11 @@ import org.spongepowered.asm.mixin.injection.At; @Mixin(RenderBiped.class) public class MixinRenderBiped { - /** - * Set item ID when rendering armor on biped entities. - * Wraps setRenderPassModel() which is called inside shouldRenderPass(). - */ - @WrapOperation( + @Inject( method = "shouldRenderPass(Lnet/minecraft/entity/EntityLiving;IF)I", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderBiped;setRenderPassModel(Lnet/minecraft/client/model/ModelBase;)V") ) - private void iris$setArmorItemId(RenderBiped instance, ModelBase model, Operation original, EntityLiving entity, int armorSlot, float partialTicks) { - // Get the armor item stack for this slot (slot 0=boots, 1=legs, 2=chest, 3=helmet) - ItemStack itemStack = entity.func_130225_q(3 - armorSlot); - ItemIdManager.setItemId(itemStack); - - original.call(instance, model); + private void iris$setArmorItemId(EntityLiving entity, int armorSlot, float partialTicks, CallbackInfoReturnable cir) { + ItemIdManager.setItemId(entity.func_130225_q(3 - armorSlot)); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java index 5eef038b2..cf2246bd9 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java @@ -12,8 +12,6 @@ import net.coderbot.iris.pipeline.WorldRenderingPhase; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.entity.RenderManager; -import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MovingObjectPosition; import org.spongepowered.asm.mixin.Mixin; @@ -134,9 +132,8 @@ public class MixinRenderGlobal { GbufferPrograms.endEntityLoop(); } - @WrapOperation(method="renderEntities", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z")) - private boolean angelica$renderEntitySimple(RenderManager instance, Entity entity, float partialTicks, Operation original) { + @Inject(method="renderEntities", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z")) + private void angelica$renderEntitySimple(CallbackInfo ci) { GbufferPrograms.onEntityRenderBoundary(); - return original.call(instance, entity, partialTicks); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderPlayerArmor.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderPlayerArmor.java index 14778bd4c..a3711b16c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderPlayerArmor.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderPlayerArmor.java @@ -8,13 +8,13 @@ import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.ItemIdManager; import net.minecraft.client.entity.AbstractClientPlayer; -import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.entity.RenderPlayer; -import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Objects; @@ -35,18 +35,12 @@ public class MixinRenderPlayerArmor { @Unique private static final NamespacedId PLAYER_CAPE = new NamespacedId("minecraft", "player_cape"); - /** - * Set item ID when rendering player armor. - */ - @WrapOperation( + @Inject( method = "shouldRenderPass(Lnet/minecraft/client/entity/AbstractClientPlayer;IF)I", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderPlayer;setRenderPassModel(Lnet/minecraft/client/model/ModelBase;)V") ) - private void iris$setArmorItemId(RenderPlayer instance, ModelBase model, Operation original, AbstractClientPlayer player, int armorSlot, float partialTicks) { - ItemStack itemStack = player.getCurrentArmor(3 - armorSlot); - ItemIdManager.setItemId(itemStack); - - original.call(instance, model); + private void iris$setArmorItemId(AbstractClientPlayer player, int armorSlot, float partialTicks, CallbackInfoReturnable cir) { + ItemIdManager.setItemId(player.getCurrentArmor(3 - armorSlot)); } /** diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRendererLivingEntity.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRendererLivingEntity.java index a3b3eb8fd..16d09b8fb 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRendererLivingEntity.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRendererLivingEntity.java @@ -1,19 +1,13 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizons.angelica.helpers.RendererLivingEntityHelper; import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.ItemIdManager; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.renderer.entity.RenderDragon; -import net.minecraft.client.renderer.entity.RenderEnderman; import net.minecraft.client.renderer.entity.RenderPlayer; -import net.minecraft.client.renderer.entity.RenderSpider; import net.minecraft.client.renderer.entity.RendererLivingEntity; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -78,24 +72,29 @@ public abstract class MixinRendererLivingEntity { return j; } - /** - * Handle special render conditions for entity eyes (spiders, endermen, ender dragon). - */ - @WrapOperation( + @Inject( method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V", ordinal = 0), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I") ) ) - private void iris$specialRenderConditionEntityEyes(ModelBase instance, Entity entity, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_, Operation original) { - RendererLivingEntity self = (RendererLivingEntity) (Object) this; - if (self instanceof RenderSpider || self instanceof RenderDragon || self instanceof RenderEnderman) { + private void iris$specialRenderConditionEntityEyes(CallbackInfo ci) { + if (RendererLivingEntityHelper.hasEyePass(this)) { GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.ENTITY_EYES); - original.call(instance, entity, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_); + } + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V", ordinal = 0, shift = At.Shift.AFTER), + slice = @Slice( + from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I") + ) + ) + private void iris$specialRenderConditionEntityEyesEnd(CallbackInfo ci) { + if (RendererLivingEntityHelper.hasEyePass(this)) { GbufferPrograms.teardownSpecialRenderCondition(); - } else { - original.call(instance, entity, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_ParticleBatch.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_ParticleBatch.java new file mode 100644 index 000000000..b37dd075e --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/dragonapi/MixinThrottleableEffectRenderer_ParticleBatch.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.mixins.late.client.dragonapi; + +import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.injection.At; + +@Pseudo +@Mixin(targets = { "Reika/DragonAPI/Extras/ThrottleableEffectRenderer" }, remap = false) +public class MixinThrottleableEffectRenderer_ParticleBatch { + + @WrapOperation(method = "doRenderParticles", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/particle/EntityFX;renderParticle(Lnet/minecraft/client/renderer/Tessellator;FFFFFF)V", + remap = true), + require = 1) + private void angelica$captureParticle(EntityFX particle, Tessellator tessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation original) { + ParticleInstancer.renderParticle(particle, tessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original); + } + + @WrapOperation(method = "doRenderParticles", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/Tessellator;draw()I", remap = true), + require = 1) + private int angelica$endLayer(Tessellator tessellator, Operation original) { + ParticleInstancer.endLayer(); + return original.call(tessellator); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrainTest.java b/src/test/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrainTest.java new file mode 100644 index 000000000..ccb5e961d --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/debug/flyby/FlybyTerrainTest.java @@ -0,0 +1,42 @@ +package com.gtnewhorizons.angelica.debug.flyby; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class FlybyTerrainTest { + + private static final double[] LINE_X = { 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 }; + private static final double[] LINE_Z = { 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5 }; + + @Test + void pillarAtCorridorEdgeRaisesFloor() { + assertEquals(9, FlybyTerrain.routeFloor(LINE_X, LINE_Z, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == 2 && z == 5 ? 9 : 4)); + assertEquals(9, FlybyTerrain.routeFloor(LINE_X, LINE_Z, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == -2 && z == 12 ? 9 : 4)); + assertEquals(4, FlybyTerrain.routeFloor(LINE_X, LINE_Z, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == 3 && z == 5 ? 9 : 4)); + assertEquals(4, FlybyTerrain.routeFloor(LINE_X, LINE_Z, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == 0 && z == 13 ? 9 : 4)); + } + + @Test + void negativeCoordinatesFloorToLowerCell() { + final double[] pathX = { -0.5 }; + final double[] pathZ = { -0.5 }; + assertEquals(9, FlybyTerrain.routeFloor(pathX, pathZ, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == -3 && z == -3 ? 9 : 4)); + assertEquals(9, FlybyTerrain.routeFloor(pathX, pathZ, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == 1 && z == 1 ? 9 : 4)); + assertEquals(4, FlybyTerrain.routeFloor(pathX, pathZ, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> x == 2 ? 9 : 4)); + assertEquals(4, FlybyTerrain.routeFloor(pathX, pathZ, FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> z == -4 ? 9 : 4)); + } + + @Test + void originParseWithYaw() { + assertEquals(new FlybyOrigin(1509.5, -924.5, 0.0F), FlybyOrigin.parse("1509.5,-924.5,0")); + assertEquals(new FlybyOrigin(10.0, 20.0, 90.0F), FlybyOrigin.parse("10, 20, 90")); + assertEquals(new FlybyOrigin(1509.5, -924.5, 0.0F), FlybyOrigin.parse("1509.5,-924.5")); + } + + @Test + void originParseRejectsMalformed() { + assertThrows(IllegalArgumentException.class, () -> FlybyOrigin.parse("1,2,3,4")); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/GlintClockTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/GlintClockTest.java new file mode 100644 index 000000000..2d19077ef --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/GlintClockTest.java @@ -0,0 +1,126 @@ +package com.gtnewhorizons.angelica.rendering; + +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import org.joml.Matrix4f; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GlintClockTest { + + @BeforeEach + void resetArmorPathTable() { + Reflect.setStatic(ArmorTexturePaths.class, "table", new String[0]); + } + + private static float armorU0() { + return Reflect.getStatic(GlintClock.class, "armorU0"); + } + + private static float armorV0() { + return Reflect.getStatic(GlintClock.class, "armorV0"); + } + + private static float armorU1() { + return Reflect.getStatic(GlintClock.class, "armorU1"); + } + + private static float armorV1() { + return Reflect.getStatic(GlintClock.class, "armorV1"); + } + + @Test + void armorTranslationMatchesVanillaModuloIntegerUv() { + for (final long millis : new long[] { 61725L, 1000003L }) { + GlintClock.beginFrame(millis); + final double ticks = millis / 50.0; + for (int k = 0; k <= 1; k++) { + final double speed = 0.001 + 0.003 * k; + final float f11 = (float) (ticks * speed * 20.0); + final float angle = (float) Math.toRadians(30 - 60 * k); + final Matrix4f vanilla = new Matrix4f().scale(0.33333334f).rotateZ(angle).translate(0f, f11, 0f); + final float u = k == 0 ? armorU0() : armorU1(); + final float v = k == 0 ? armorV0() : armorV1(); + final Matrix4f ours = new Matrix4f().scale(0.33333334f).rotateZ(angle).translate(u, v, 0f); + + final String ctx = "millis=" + millis + " k=" + k; + assertEquals(vanilla.m00(), ours.m00(), 1e-6f, ctx + " scale/rotate must be untouched"); + assertEquals(vanilla.m01(), ours.m01(), 1e-6f, ctx + " scale/rotate must be untouched"); + assertEquals(vanilla.m10(), ours.m10(), 1e-6f, ctx + " scale/rotate must be untouched"); + assertEquals(vanilla.m11(), ours.m11(), 1e-6f, ctx + " scale/rotate must be untouched"); + + final float dx = vanilla.m30() - ours.m30(); + final float dy = vanilla.m31() - ours.m31(); + assertEquals(0f, dx - Math.round(dx), 1e-3f, ctx + " u must differ from vanilla by a whole texel"); + assertEquals(0f, dy - Math.round(dy), 1e-3f, ctx + " v must differ from vanilla by a whole texel"); + } + } + } + + @Test + void beginFrameIsDeterministicAndBounded() { + GlintClock.beginFrame(864000000123L); + final float u0 = armorU0(); + final float v0 = armorV0(); + final float u1 = armorU1(); + final float v1 = armorV1(); + + final float bound = 4.25f; + assertTrue(Math.abs(u0) <= bound, "u0=" + u0); + assertTrue(Math.abs(v0) <= bound, "v0=" + v0); + assertTrue(Math.abs(u1) <= bound, "u1=" + u1); + assertTrue(Math.abs(v1) <= bound, "v1=" + v1); + } + + @Test + void secondArmorLayerFollowsRotationSign() { + final Matrix4f first = new Matrix4f().scale(1f / 3f).rotateZ((float) Math.toRadians(30.0)); + final Matrix4f second = new Matrix4f().scale(1f / 3f).rotateZ((float) Math.toRadians(-30.0)); + + assertFalse(GlintClock.secondArmorLayer(first), "k=0 (rotate +30) must read as the first armor layer"); + assertTrue(GlintClock.secondArmorLayer(second), "k=1 (rotate -30) must read as the second armor layer"); + } + + @Test + void pathsMatchForgeArmorResourceLiterals() { + assertEquals("textures/models/armor/diamond_layer_2_overlay.png", ArmorTexturePaths.path("diamond", 3, 2, "overlay")); + assertEquals("textures/models/armor/diamond_layer_2.png", ArmorTexturePaths.path("diamond", 3, 2, null)); + assertEquals("textures/models/armor/iron_layer_1.png", ArmorTexturePaths.path("iron", 2, 0, null)); + assertEquals("textures/models/armor/iron_layer_1_overlay.png", ArmorTexturePaths.path("iron", 2, 1, "overlay")); + assertEquals("textures/models/armor/chainmail_layer_1.png", ArmorTexturePaths.path("chainmail", 1, 3, null)); + assertEquals("textures/models/armor/cloth_layer_1_x.png", ArmorTexturePaths.path("cloth", 0, 0, "x")); + assertEquals("textures/models/armor/null_layer_1.png", ArmorTexturePaths.path(null, 2, 1, null)); + assertEquals("textures/models/armor/null_layer_2_overlay.png", ArmorTexturePaths.path(null, 2, 2, "overlay")); + } + + @Test + void replacedPrefixElementRebuildsRow() { + final String second = ArmorTexturePaths.path("skeleton", 3, 0, null); + final String third = ArmorTexturePaths.path("wither_skeleton", 3, 0, null); + assertNotEquals(second, third); + } + + @Test + void aChangedFloatGetsANewBox() { + final Object prev = Float.valueOf(1.5f); + assertSame(prev, OperationArgs.boxed(prev, 1.5f)); + final Object next = OperationArgs.boxed(prev, 2.5f); + assertNotSame(prev, next); + assertEquals(2.5f, (Float) next); + } + + @Test + void aChangedIntGetsANewBox() { + final Object prev = Integer.valueOf(100_000); + assertSame(prev, OperationArgs.boxed(prev, 100_000)); + final Object next = OperationArgs.boxed(prev, 100_001); + assertNotSame(prev, next); + assertEquals(100_001, (Integer) next); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/VertexAttributeLayoutTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/VertexAttributeLayoutTest.java index aa37cda14..7b6618c1b 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/VertexAttributeLayoutTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/VertexAttributeLayoutTest.java @@ -1,7 +1,9 @@ package com.gtnewhorizons.angelica.rendering; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.ffp.CubeInstancedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; import net.coderbot.iris.gl.shader.ProgramCreator; import org.junit.jupiter.api.Test; @@ -37,29 +39,31 @@ class VertexAttributeLayoutTest { claim(loc, "vertex format " + usage.name()); } - claim(InstancedAttribs.LOC_MATRIX_COL0, "InstancedAttribs.LOC_MATRIX_COL0"); - claim(InstancedAttribs.LOC_MATRIX_COL1, "InstancedAttribs.LOC_MATRIX_COL1"); - claim(InstancedAttribs.LOC_MATRIX_COL2, "InstancedAttribs.LOC_MATRIX_COL2"); - claim(InstancedAttribs.LOC_MATRIX_COL3, "InstancedAttribs.LOC_MATRIX_COL3"); + claim(InstancedAttribs.LOC_ROW0, "InstancedAttribs.LOC_ROW0"); + claim(InstancedAttribs.LOC_ROW1, "InstancedAttribs.LOC_ROW1"); + claim(InstancedAttribs.LOC_ROW2, "InstancedAttribs.LOC_ROW2"); claim(InstancedAttribs.LOC_COLOR, "InstancedAttribs.LOC_COLOR"); + claim(InstancedAttribs.LOC_OVERLAY, "InstancedAttribs.LOC_OVERLAY"); claim(InstancedAttribs.LOC_LIGHTMAP, "InstancedAttribs.LOC_LIGHTMAP"); + claim(InstancedAttribs.LOC_ENTITY, "InstancedAttribs.LOC_ENTITY"); - claim(ProgramCreator.MC_ENTITY, "ProgramCreator.MC_ENTITY"); claim(ProgramCreator.MC_MID_TEX_COORD, "ProgramCreator.MC_MID_TEX_COORD"); claim(ProgramCreator.AT_TANGENT, "ProgramCreator.AT_TANGENT"); claim(ProgramCreator.AT_MIDBLOCK, "ProgramCreator.AT_MIDBLOCK"); + + claim(CubeInstancedAttribs.LOC_CUBE_TEX, "CubeInstancedAttribs.LOC_CUBE_TEX"); } @Test - void instancedMatrixColumnsAreContiguous() { - final int[] columns = { - InstancedAttribs.LOC_MATRIX_COL0, InstancedAttribs.LOC_MATRIX_COL1, - InstancedAttribs.LOC_MATRIX_COL2, InstancedAttribs.LOC_MATRIX_COL3 - }; - for (int c = 1; c < columns.length; c++) { - assertEquals(columns[0] + c, columns[c], - "instance matrix column " + c + " must sit at LOC_MATRIX_COL0 + " + c); - } + void instancedEntitySharesLocationWithImmediateMcEntity() { + assertEquals(InstancedAttribs.LOC_ENTITY, ImmediateExtendedAttribHandler.LOC_MC_ENTITY, "instanced entity info and immediate mc_Entity share a location; they are never bound in the same draw"); + assertEquals(InstancedAttribs.LOC_ENTITY, ProgramCreator.MC_ENTITY); + } + + @Test + void instancedRowsAreContiguous() { + assertEquals(InstancedAttribs.LOC_ROW0 + 1, InstancedAttribs.LOC_ROW1, "instance row 1 must sit at LOC_ROW0 + 1"); + assertEquals(InstancedAttribs.LOC_ROW0 + 2, InstancedAttribs.LOC_ROW2, "instance row 2 must sit at LOC_ROW0 + 2"); } @Test diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/items/ItemTemplateCaptureGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/items/ItemTemplateCaptureGLTest.java new file mode 100644 index 000000000..0cfc10c01 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/items/ItemTemplateCaptureGLTest.java @@ -0,0 +1,167 @@ +package com.gtnewhorizons.angelica.rendering.items; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import com.gtnewhorizons.angelica.rendering.tesr.EntityMaterials; +import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.ItemRenderer; +import net.minecraft.client.renderer.Tessellator; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX; +import static com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility.SAFE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@GLCoreTest +class ItemTemplateCaptureGLTest { + + private static final float NORM_EPS = 1.5f / 127f; + private static final float EPS = 1.0e-5f; + + @AfterEach + void cleanup() { + DroppedItemInstancer.clear(); + } + + private static TemplateBuffer capture(float maxU, float minV, float minU, float maxV, int width, int height, float thickness) { + final AngelicaTesrMeshCache.GtnhMeshBackend backend = new AngelicaTesrMeshCache.GtnhMeshBackend(); + final Tessellator direct = backend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL); + RuntimeException failure = null; + try { + ItemRenderer.renderItemIn2D(direct, maxU, minV, minU, maxV, width, height, thickness); + } catch (RuntimeException e) { + failure = e; + } + final TemplateBuffer template = backend.endCaptureToTemplate(); + if (failure != null) throw failure; + return template; + } + + private static float[] vertex(float x, float y, float z, float u, float v, float nx, float ny, float nz) { + return new float[] { x, y, z, u, v, nx, ny, nz }; + } + + private static float[][] expected(float maxU, float minV, float minU, float maxV, int width, int height, float thickness) { + final float[][] out = new float[4 * (2 + 2 * width + 2 * height)][]; + int i = 0; + + out[i++] = vertex(0f, 0f, 0f, maxU, maxV, 0f, 0f, 1f); + out[i++] = vertex(1f, 0f, 0f, minU, maxV, 0f, 0f, 1f); + out[i++] = vertex(1f, 1f, 0f, minU, minV, 0f, 0f, 1f); + out[i++] = vertex(0f, 1f, 0f, maxU, minV, 0f, 0f, 1f); + + out[i++] = vertex(0f, 1f, -thickness, maxU, minV, 0f, 0f, -1f); + out[i++] = vertex(1f, 1f, -thickness, minU, minV, 0f, 0f, -1f); + out[i++] = vertex(1f, 0f, -thickness, minU, maxV, 0f, 0f, -1f); + out[i++] = vertex(0f, 0f, -thickness, maxU, maxV, 0f, 0f, -1f); + + final float f5 = 0.5f * (maxU - minU) / width; + final float f6 = 0.5f * (maxV - minV) / height; + + for (int k = 0; k < width; k++) { + final float f7 = (float) k / width; + final float f8 = maxU + (minU - maxU) * f7 - f5; + out[i++] = vertex(f7, 0f, -thickness, f8, maxV, -1f, 0f, 0f); + out[i++] = vertex(f7, 0f, 0f, f8, maxV, -1f, 0f, 0f); + out[i++] = vertex(f7, 1f, 0f, f8, minV, -1f, 0f, 0f); + out[i++] = vertex(f7, 1f, -thickness, f8, minV, -1f, 0f, 0f); + } + + for (int k = 0; k < width; k++) { + final float f7 = (float) k / width; + final float f8 = maxU + (minU - maxU) * f7 - f5; + final float f9 = f7 + 1f / width; + out[i++] = vertex(f9, 1f, -thickness, f8, minV, 1f, 0f, 0f); + out[i++] = vertex(f9, 1f, 0f, f8, minV, 1f, 0f, 0f); + out[i++] = vertex(f9, 0f, 0f, f8, maxV, 1f, 0f, 0f); + out[i++] = vertex(f9, 0f, -thickness, f8, maxV, 1f, 0f, 0f); + } + + for (int k = 0; k < height; k++) { + final float f7 = (float) k / height; + final float f8 = maxV + (minV - maxV) * f7 - f6; + final float f9 = f7 + 1f / height; + out[i++] = vertex(0f, f9, 0f, maxU, f8, 0f, 1f, 0f); + out[i++] = vertex(1f, f9, 0f, minU, f8, 0f, 1f, 0f); + out[i++] = vertex(1f, f9, -thickness, minU, f8, 0f, 1f, 0f); + out[i++] = vertex(0f, f9, -thickness, maxU, f8, 0f, 1f, 0f); + } + + for (int k = 0; k < height; k++) { + final float f7 = (float) k / height; + final float f8 = maxV + (minV - maxV) * f7 - f6; + out[i++] = vertex(1f, f7, 0f, minU, f8, 0f, -1f, 0f); + out[i++] = vertex(0f, f7, 0f, maxU, f8, 0f, -1f, 0f); + out[i++] = vertex(0f, f7, -thickness, maxU, f8, 0f, -1f, 0f); + out[i++] = vertex(1f, f7, -thickness, minU, f8, 0f, -1f, 0f); + } + + assertEquals(out.length, i); + return out; + } + + private static void assertCaptureMatches(float maxU, float minV, float minU, float maxV, int width, int height, float thickness) { + final TemplateBuffer template = capture(maxU, minV, minU, maxV, width, height, thickness); + assertNotNull(template, "renderItemIn2D must emit geometry"); + final float[][] expected = expected(maxU, minV, minU, maxV, width, height, thickness); + assertEquals(expected.length, template.vertexCount); + + for (int v = 0; v < expected.length; v++) { + final int base = v * VERTEX_SIZE; + final float[] want = expected[v]; + assertEquals(want[0], Float.intBitsToFloat(template.data[base + X_INDEX]), EPS, "vertex " + v + " x"); + assertEquals(want[1], Float.intBitsToFloat(template.data[base + Y_INDEX]), EPS, "vertex " + v + " y"); + assertEquals(want[2], Float.intBitsToFloat(template.data[base + Z_INDEX]), EPS, "vertex " + v + " z"); + assertEquals(want[3], Float.intBitsToFloat(template.data[base + TEX_X_INDEX]), EPS, "vertex " + v + " u"); + assertEquals(want[4], Float.intBitsToFloat(template.data[base + TEX_Y_INDEX]), EPS, "vertex " + v + " v"); + final int normal = template.data[base + NORMAL_INDEX]; + assertEquals(want[5], NormI8.unpackX(normal), NORM_EPS, "vertex " + v + " nx"); + assertEquals(want[6], NormI8.unpackY(normal), NORM_EPS, "vertex " + v + " ny"); + assertEquals(want[7], NormI8.unpackZ(normal), NORM_EPS, "vertex " + v + " nz"); + } + } + + @Test + void capturedIconMatchesVanillaLoopFormula() { + assertCaptureMatches(1.0f, 0.0f, 0.0f, 1.0f, 16, 16, 0.0625f); + } + + @Test + void anEmptyBlockCaptureDrawsVanillaWithoutDenyingTheRenderer() { + final Block block = new ProbeBlock(); + final int[] calls = { 0 }; + final Operation original = args -> { + if (calls[0]++ > 0) GLStateManager.drawCalls++; + return null; + }; + + BatchEligibility.begin(SAFE, GLStateManager.drawCalls); + DroppedItemInstancer.batchBlock(EntityMaterials.DROPPED_ITEM_CUTOUT, null, block, 0, 1f, original); + DroppedItemInstancer.batchBlock(EntityMaterials.DROPPED_ITEM_CUTOUT, null, block, 0, 1f, original); + assertEquals(SAFE, BatchEligibility.end(SAFE, GLStateManager.drawCalls), "a block with no cached template draws vanilla and reports no part"); + + assertEquals(3, calls[0], "one capture, then a vanilla draw on the miss and on the cached null template"); + } + + private static final class ProbeBlock extends Block { + + ProbeBlock() { + super(Material.rock); + } + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingGLTest.java new file mode 100644 index 000000000..6f6a37dcb --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingGLTest.java @@ -0,0 +1,713 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.ParticleParityFixture.Rotation; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.particle.EntityCloudFX; +import net.minecraft.client.particle.EntityCritFX; +import net.minecraft.client.particle.EntityDiggingFX; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.particle.EntityFireworkOverlayFX; +import net.minecraft.client.particle.EntityFireworkSparkFX; +import net.minecraft.client.particle.EntityFlameFX; +import net.minecraft.client.particle.EntityHeartFX; +import net.minecraft.client.particle.EntityLavaFX; +import net.minecraft.client.particle.EntityNoteFX; +import net.minecraft.client.particle.EntityPortalFX; +import net.minecraft.client.particle.EntityReddustFX; +import net.minecraft.client.particle.EntitySmokeFX; +import net.minecraft.client.particle.EntitySnowShovelFX; +import net.minecraft.client.particle.EntitySpellParticleFX; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.IIcon; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class ParticleInstancingGLTest { + + private static final float TOL = 1.0e-5f; + private static final float[] PARTIAL_TICKS = { 0.0f, 0.37f, 0.999f }; + private static final int FRAMES = 4; + private static final Rotation[] ROTATIONS = { Rotation.of(37f, 15f, false), Rotation.of(-110f, 62f, true) }; + private static final int STUB_TEXTURE_ID = 42; + + private static class NoOpTessellator extends Tessellator { + + @Override + public void setBrightness(int value) {} + + @Override + public void setColorRGBA(int red, int green, int blue, int alpha) {} + + @Override + public void setTextureUV(double u, double v) {} + + @Override + public void addVertexWithUV(double x, double y, double z, double u, double v) {} + + @Override + public void addVertex(double x, double y, double z) {} + + @Override + public void setNormal(float x, float y, float z) {} + + @Override + public void startDrawingQuads() {} + + @Override + public int draw() { + return 0; + } + } + + private static final class RecordingTessellator extends Tessellator { + + final List log = new ArrayList<>(); + + @Override + public void setBrightness(int value) { + log.add("brightness(" + value + ")"); + } + + @Override + public void setColorRGBA(int red, int green, int blue, int alpha) { + log.add("color(" + red + "," + green + "," + blue + "," + alpha + ")"); + } + + @Override + public void setTextureUV(double u, double v) { + log.add("uv(" + u + "," + v + ")"); + } + + @Override + public void addVertexWithUV(double x, double y, double z, double u, double v) { + log.add("vertexUV(" + x + "," + y + "," + z + "," + u + "," + v + ")"); + } + + @Override + public void addVertex(double x, double y, double z) { + log.add("vertex(" + x + "," + y + "," + z + ")"); + } + + @Override + public void setNormal(float x, float y, float z) { + log.add("normal(" + x + "," + y + "," + z + ")"); + } + + @Override + public void startDrawingQuads() { + log.add("startQuads"); + } + + @Override + public void startDrawing(int mode) { + log.add("startDrawing(" + mode + ")"); + } + + @Override + public int draw() { + log.add("draw"); + return 0; + } + } + + private static final class ProbeBlock extends Block { + + ProbeBlock() { + super(Material.rock); + } + } + + private static final class ProbeCritFX extends EntityCritFX { + + ProbeCritFX(double x, double y, double z, double mx, double my, double mz, float mult) { + super(null, x, y, z, mx, my, mz, mult); + } + + @Override + public void onUpdate() {} + } + + private static final class ProbeFireworkOverlay extends EntityFireworkOverlayFX { + + ProbeFireworkOverlay(double x, double y, double z) { + super(null, x, y, z); + } + } + + private static final class ProbePixieTrailFX extends EntityFX { + + ProbePixieTrailFX(double x, double y, double z) { + super(null, x, y, z); + } + + @Override + public void renderParticle(Tessellator tessellator, float par2, float par3, float par4, float par5, float par6, float par7) { + float f = (particleAge + par2) / particleMaxAge * 32.0F; + if (f < 0.0F) f = 0.0F; + if (f > 1.0F) f = 1.0F; + particleScale = particleScale * f; + + tessellator.draw(); + + float f6 = (float) particleTextureIndexX / 16.0F; + float f7 = f6 + 0.0624375F; + float f8 = (float) particleTextureIndexY / 16.0F; + float f9 = f8 + 0.0624375F; + float f10 = 0.1F * particleScale; + + if (particleIcon != null) { + f6 = particleIcon.getMinU(); + f7 = particleIcon.getMaxU(); + f8 = particleIcon.getMinV(); + f9 = particleIcon.getMaxV(); + } + + float f11 = (float) (prevPosX + (posX - prevPosX) * (double) par2 - interpPosX); + float f12 = (float) (prevPosY + (posY - prevPosY) * (double) par2 - interpPosY); + float f13 = (float) (prevPosZ + (posZ - prevPosZ) * (double) par2 - interpPosZ); + + tessellator.startDrawingQuads(); + tessellator.setBrightness(175); + + tessellator.setColorRGBA_F(particleRed, particleGreen, particleBlue, 1.0F); + tessellator.addVertexWithUV(f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9); + tessellator.addVertexWithUV(f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8); + tessellator.addVertexWithUV(f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8); + tessellator.addVertexWithUV(f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9); + + tessellator.draw(); + + tessellator.startDrawingQuads(); + } + } + + private record StubIcon(float minU, float maxU, float minV, float maxV) implements IIcon { + + @Override + public int getIconWidth() { + return 16; + } + + @Override + public int getIconHeight() { + return 16; + } + + @Override + public float getMinU() { + return minU; + } + + @Override + public float getMaxU() { + return maxU; + } + + @Override + public float getInterpolatedU(double u) { + throw new UnsupportedOperationException(); + } + + @Override + public float getMinV() { + return minV; + } + + @Override + public float getMaxV() { + return maxV; + } + + @Override + public float getInterpolatedV(double v) { + throw new UnsupportedOperationException(); + } + + @Override + public String getIconName() { + throw new UnsupportedOperationException(); + } + } + + @BeforeEach + @AfterEach + void resetState() { + ParticleDescriptorRegistry.clearCache(); + BopParticleDescriptors.invalidate(); + EntityFX.interpPosX = 0; + EntityFX.interpPosY = 0; + EntityFX.interpPosZ = 0; + } + + private static ParticleRenderState checkFrame(ParticleDescriptor descriptor, EntityFX reference, EntityFX candidate, float partialTicks, Rotation r, int startBrightness) { + final NoOpTessellator run = new NoOpTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + capture.begin(startBrightness, run, GLStateManager.getModelViewMatrix()); + reference.renderParticle(capture, partialTicks, r.x(), r.xz(), r.z(), r.yz(), r.xy()); + + assertFalse(capture.spilled()); + assertEquals(4, capture.captured()); + + final ParticleParams expected = new ParticleParams(); + final boolean decoded = ParticleQuadDecoder.decode(capture.vertices(), capture.captured(), r.x(), r.xz(), r.z(), r.yz(), r.xy(), expected); + assertTrue(decoded); + + final int expectedColor = capture.capturedColor(); + final int expectedBrightness = capture.capturedBrightness(); + + final ParticleParams actual = new ParticleParams(); + actual.brightness = startBrightness; + final ParticleRenderState state = new ParticleRenderState(); + final boolean ok = descriptor.describe(candidate, partialTicks, actual, state); + assertTrue(ok); + + assertEquals(expected.centerX, actual.centerX, TOL); + assertEquals(expected.centerY, actual.centerY, TOL); + assertEquals(expected.centerZ, actual.centerZ, TOL); + assertEquals(expected.half, actual.half, TOL); + assertEquals(expected.u0, actual.u0, TOL); + assertEquals(expected.v0, actual.v0, TOL); + assertEquals(expected.u1, actual.u1, TOL); + assertEquals(expected.v1, actual.v1, TOL); + assertEquals(expectedColor, actual.colorABGR); + assertEquals(expectedBrightness, actual.brightness); + return state; + } + + private static void runParity(Class cls, Supplier factory) { + final EntityFX reference = factory.get(); + final EntityFX candidate = factory.get(); + final ParticleDescriptor descriptor = ParticleDescriptorRegistry.forClass(cls); + for (int frame = 0; frame < FRAMES; frame++) { + for (Rotation r : ROTATIONS) { + for (float pt : PARTIAL_TICKS) { + checkFrame(descriptor, reference, candidate, pt, r, 50 + frame * 10); + } + } + reference.particleAge++; + candidate.particleAge++; + } + } + + private static void seedPositions(EntityFX fx, double x, double y, double z) { + fx.posX = x; + fx.posY = y; + fx.posZ = z; + fx.prevPosX = x - 0.1; + fx.prevPosY = y - 0.1; + fx.prevPosZ = z - 0.1; + } + + private static Arguments particle(Class cls, Supplier factory) { + return Arguments.of(cls, factory); + } + + static Stream particles() { + return Stream.of( + particle(EntityFlameFX.class, () -> { + final EntityFlameFX fx = new EntityFlameFX(null, 1.5, 10.0, -2.25, 0.0, 0.0, 0.0); + seedPositions(fx, 1.5, 10.0, -2.25); + fx.particleAge = 2; + fx.particleMaxAge = 20; + fx.particleScale = 1.3f; + Reflect.set(fx, "flameScale", 1.3f); + fx.particleRed = 0.9f; + fx.particleGreen = 0.5f; + fx.particleBlue = 0.2f; + fx.particleAlpha = 0.8f; + fx.particleTextureIndexX = 3; + fx.particleTextureIndexY = 1; + return fx; + }), + particle(EntitySmokeFX.class, () -> { + final EntitySmokeFX fx = new EntitySmokeFX(null, 2.0, 5.0, 1.0, 0.0, 0.0, 0.0); + seedPositions(fx, 2.0, 5.0, 1.0); + fx.particleAge = 1; + fx.particleMaxAge = 30; + fx.particleScale = 0.9f; + Reflect.set(fx, "smokeParticleScale", 0.9f); + fx.particleRed = 1.5f; + fx.particleGreen = 0.1f; + fx.particleBlue = 0.1f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityCloudFX.class, () -> { + final EntityCloudFX fx = new EntityCloudFX(null, -3.0, 20.0, 4.0, 0.0, 0.0, 0.0); + seedPositions(fx, -3.0, 20.0, 4.0); + fx.particleAge = 3; + fx.particleMaxAge = 40; + fx.particleScale = 2.4f; + Reflect.set(fx, "field_70569_a", 2.4f); + fx.particleRed = 0.8f; + fx.particleGreen = 0.8f; + fx.particleBlue = 0.8f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityCritFX.class, () -> { + final ProbeCritFX fx = new ProbeCritFX(0.5, 1.0, 0.5, 0.0, 0.0, 0.0, 1.0f); + seedPositions(fx, 0.5, 1.0, 0.5); + fx.particleAge = 1; + fx.particleMaxAge = 10; + fx.particleScale = 0.6f; + Reflect.set(fx, "initialParticleScale", 0.6f); + fx.particleRed = 0.7f; + fx.particleGreen = 0.7f; + fx.particleBlue = 0.7f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityHeartFX.class, () -> { + final EntityHeartFX fx = new EntityHeartFX(null, 4.0, 66.0, -1.0, 0.0, 0.0, 0.0); + seedPositions(fx, 4.0, 66.0, -1.0); + fx.particleAge = 1; + fx.particleMaxAge = 16; + fx.particleScale = 3.0f; + Reflect.set(fx, "particleScaleOverTime", 3.0f); + fx.particleRed = 1.0f; + fx.particleGreen = 0.2f; + fx.particleBlue = 0.2f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityLavaFX.class, () -> { + final EntityLavaFX fx = new EntityLavaFX(null, 8.0, 12.0, 8.0); + seedPositions(fx, 8.0, 12.0, 8.0); + fx.particleAge = 1; + fx.particleMaxAge = 18; + fx.particleScale = 1.7f; + Reflect.set(fx, "lavaParticleScale", 1.7f); + fx.particleRed = 1.0f; + fx.particleGreen = 1.0f; + fx.particleBlue = 1.0f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityNoteFX.class, () -> { + final EntityNoteFX fx = new EntityNoteFX(null, 0.0, 70.0, 0.0, 0.0, 0.0, 0.0); + seedPositions(fx, 0.0, 70.0, 0.0); + fx.particleAge = 0; + fx.particleMaxAge = 6; + fx.particleScale = 1.5f; + Reflect.set(fx, "noteParticleScale", 1.5f); + fx.particleRed = 0.4f; + fx.particleGreen = 0.9f; + fx.particleBlue = 0.6f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntityPortalFX.class, () -> { + final EntityPortalFX fx = new EntityPortalFX(null, 5.0, 40.0, 5.0, 0.0, 0.0, 0.0); + seedPositions(fx, 5.0, 40.0, 5.0); + fx.particleAge = 2; + fx.particleMaxAge = 45; + fx.particleScale = 0.6f; + Reflect.set(fx, "portalParticleScale", 0.6f); + fx.particleRed = 0.85f; + fx.particleGreen = 0.1f; + fx.particleBlue = 0.9f; + fx.particleAlpha = 1.0f; + fx.particleTextureIndexX = 2; + fx.particleTextureIndexY = 0; + return fx; + }), + particle(EntityReddustFX.class, () -> { + final EntityReddustFX fx = new EntityReddustFX(null, -2.0, 8.0, -2.0, 1.0f, 0.4f, 0.4f); + seedPositions(fx, -2.0, 8.0, -2.0); + fx.particleAge = 1; + fx.particleMaxAge = 20; + fx.particleScale = 1.1f; + Reflect.set(fx, "reddustParticleScale", 1.1f); + fx.particleRed = 0.9f; + fx.particleGreen = 0.35f; + fx.particleBlue = 0.35f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntitySnowShovelFX.class, () -> { + final EntitySnowShovelFX fx = new EntitySnowShovelFX(null, 3.0, 15.0, 3.0, 0.0, 0.0, 0.0); + seedPositions(fx, 3.0, 15.0, 3.0); + fx.particleAge = 1; + fx.particleMaxAge = 22; + fx.particleScale = 0.8f; + Reflect.set(fx, "snowDigParticleScale", 0.8f); + fx.particleRed = 0.9f; + fx.particleGreen = 0.9f; + fx.particleBlue = 1.0f; + fx.particleAlpha = 1.0f; + return fx; + }), + particle(EntitySpellParticleFX.class, () -> { + final EntitySpellParticleFX fx = new EntitySpellParticleFX(null, 1.0, 60.0, 1.0, 0.0, 0.0, 0.0); + seedPositions(fx, 1.0, 60.0, 1.0); + fx.particleAge = 1; + fx.particleMaxAge = 25; + fx.particleScale = 1.1f; + fx.particleRed = 0.6f; + fx.particleGreen = 0.3f; + fx.particleBlue = 0.9f; + fx.particleAlpha = 1.0f; + fx.particleIcon = new StubIcon(0.1f, 0.2f, 0.3f, 0.4f); + return fx; + })); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("particles") + void descriptorMatchesVanillaAcrossFrames(Class cls, Supplier factory) { + runParity(cls, factory); + } + + @Test + void fireworkOverlayFxMatchesVanillaIncludingNegativeHalfFrames() { + runParity(EntityFireworkOverlayFX.class, () -> { + final ProbeFireworkOverlay fx = new ProbeFireworkOverlay(6.0, 70.0, -4.0); + seedPositions(fx, 6.0, 70.0, -4.0); + fx.particleRed = 1.0f; + fx.particleGreen = 0.6f; + fx.particleBlue = 0.2f; + assertTrue(fx.particleAge == 0); + return fx; + }); + } + + private static EntityFireworkSparkFX twinklingSpark(int age) { + final EntityFireworkSparkFX fx = new EntityFireworkSparkFX(null, -1.0, 65.0, 3.0, 0.0, 0.0, 0.0, null); + seedPositions(fx, -1.0, 65.0, 3.0); + fx.particleAge = age; + fx.particleMaxAge = 30; + fx.particleScale = 0.75f; + fx.particleRed = 1.0f; + fx.particleGreen = 0.5f; + fx.particleBlue = 0.0f; + fx.particleAlpha = 1.0f; + Reflect.set(fx, "field_92048_ay", true); + return fx; + } + + @Test + void fireworkSparkFxMatchesVanillaAcrossTheTwinkleCycle() { + final ParticleDescriptor descriptor = ParticleDescriptorRegistry.forClass(EntityFireworkSparkFX.class); + final Rotation r = ROTATIONS[0]; + int drawn = 0; + int skipped = 0; + for (int age = 0; age <= 30; age++) { + final EntityFireworkSparkFX reference = twinklingSpark(age); + final EntityFireworkSparkFX candidate = twinklingSpark(age); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + capture.begin(100, new NoOpTessellator(), GLStateManager.getModelViewMatrix()); + reference.renderParticle(capture, 0.4f, r.x(), r.xz(), r.z(), r.yz(), r.xy()); + assertFalse(capture.spilled()); + if (capture.captured() == 0) { + skipped++; + assertFalse(descriptor.describe(candidate, 0.4f, new ParticleParams(), new ParticleRenderState()), "age " + age); + } else { + drawn++; + checkFrame(descriptor, reference, candidate, 0.4f, r, 100); + } + } + assertTrue(drawn > 0 && skipped > 0, "drawn=" + drawn + " skipped=" + skipped); + } + + @Test + void diggingFxMatchesVanillaAcrossFramesWithAnUnstitchedBlockIcon() { + final ProbeBlock block = new ProbeBlock(); + runParity(EntityDiggingFX.class, () -> { + final EntityDiggingFX fx = new EntityDiggingFX(null, 2.0, 5.0, 2.0, 0.0, 0.0, 0.0, block, 0, 3); + seedPositions(fx, 2.0, 5.0, 2.0); + fx.particleAge = 1; + fx.particleMaxAge = 15; + fx.particleScale = 0.5f; + fx.particleRed = 0.6f; + fx.particleGreen = 0.6f; + fx.particleBlue = 0.6f; + fx.particleTextureIndexX = 4; + fx.particleTextureIndexY = 2; + fx.particleTextureJitterX = 1.5f; + fx.particleTextureJitterY = 2.0f; + assertTrue(fx.particleIcon == null); + return fx; + }); + } + + private static ProbePixieTrailFX pixieTrail() { + final ProbePixieTrailFX fx = new ProbePixieTrailFX(1.0, 65.0, -2.0); + fx.posX = 1.0; + fx.posY = 65.0; + fx.posZ = -2.0; + fx.prevPosX = 0.9; + fx.prevPosY = 64.9; + fx.prevPosZ = -2.1; + fx.particleAge = 0; + fx.particleMaxAge = 64; + fx.particleScale = 2.0f; + fx.particleRed = 0.4f; + fx.particleGreen = 0.9f; + fx.particleBlue = 0.7f; + fx.particleTextureIndexX = 6; + fx.particleTextureIndexY = 3; + return fx; + } + + @Test + void pixieTrailFxMatchesVanillaAcrossFramesWithACachedTextureId() { + Reflect.setStatic(BopParticleDescriptors.class, "pixieTrailTexture", STUB_TEXTURE_ID); + ParticleDescriptorRegistry.register(ProbePixieTrailFX.class.getName(), BopParticleDescriptors.PIXIE_TRAIL); + final ParticleDescriptor descriptor = ParticleDescriptorRegistry.forClass(ProbePixieTrailFX.class); + assertSame(BopParticleDescriptors.PIXIE_TRAIL, descriptor); + + final ProbePixieTrailFX reference = pixieTrail(); + final ProbePixieTrailFX candidate = pixieTrail(); + + for (int frame = 0; frame < FRAMES; frame++) { + for (Rotation r : ROTATIONS) { + for (float pt : PARTIAL_TICKS) { + final ParticleRenderState state = checkFrame(descriptor, reference, candidate, pt, r, 50 + frame * 10); + assertTrue(state.blend); + assertEquals(GL11.GL_SRC_ALPHA, state.blendSrc); + assertEquals(GL11.GL_ONE, state.blendDst); + assertFalse(state.depthMask); + assertEquals(STUB_TEXTURE_ID, state.texture); + } + } + reference.particleAge++; + candidate.particleAge++; + } + } + + private static void feedQuad(ParticleCaptureTessellator capture) { + capture.addVertexWithUV(0.0, 0.0, 0.0, 0.0, 1.0); + capture.addVertexWithUV(0.0, 1.0, 0.0, 0.0, 0.0); + capture.addVertexWithUV(1.0, 1.0, 0.0, 1.0, 0.0); + capture.addVertexWithUV(1.0, 0.0, 0.0, 1.0, 1.0); + } + + @Test + void aSecondQuadAfterASelfDrawSpillsIntoItsOwnBatchWhenTheRunIsNotDrawing() { + final RecordingTessellator run = new RecordingTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + + capture.begin(100, run, GLStateManager.getModelViewMatrix()); + capture.setColorRGBA(5, 6, 7, 8); + feedQuad(capture); + capture.draw(); + run.log.clear(); + + capture.addVertexWithUV(2.0, 2.0, 0.0, 0.5, 0.5); + + assertTrue(capture.spilled(), "a fifth vertex after a self-draw is a multi-quad particle"); + assertEquals("startQuads", run.log.get(1), () -> "the replay must open its own batch: " + run.log); + assertEquals(1, run.log.stream().filter("startQuads"::equals).count()); + assertEquals("draw", run.log.get(run.log.size() - 2), () -> "the closed quad must be drawn on spill: " + run.log); + assertEquals("vertexUV(2.0,2.0,0.0,0.5,0.5)", run.log.get(run.log.size() - 1)); + assertEquals(5, run.log.stream().filter(l -> l.startsWith("vertexUV(")).count()); + assertFalse(run.isDrawing, "a run that was not drawing must be left not drawing"); + } + + @Test + void aClosedSpillReplaysInTheSameOrder() { + final RecordingTessellator run = new RecordingTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + + capture.begin(100, run, GLStateManager.getModelViewMatrix()); + capture.setColorRGBA(5, 6, 7, 8); + feedQuad(capture); + capture.draw(); + run.isDrawing = true; + run.log.clear(); + + capture.startDrawing(GL11.GL_LINES); + + final List expected = List.of( + "brightness(100)", + "color(5,6,7,8)", + "uv(1.0,1.0)", + "vertexUV(0.0,0.0,0.0,0.0,1.0)", + "vertexUV(0.0,1.0,0.0,0.0,0.0)", + "vertexUV(1.0,1.0,0.0,1.0,0.0)", + "vertexUV(1.0,0.0,0.0,1.0,1.0)", + "draw", + "startQuads", + "startDrawing(" + GL11.GL_LINES + ")"); + assertEquals(expected, run.log); + } + + @Test + void aFifthVertexSpillsAndForwardsRemainingCallsToRun() { + final RecordingTessellator run = new RecordingTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + + capture.begin(100, run, GLStateManager.getModelViewMatrix()); + capture.setColorRGBA(5, 6, 7, 8); + feedQuad(capture); + assertFalse(capture.spilled()); + + capture.addVertexWithUV(2.0, 2.0, 0.0, 0.5, 0.5); + + assertTrue(capture.spilled(), "a fifth vertex must taint/spill the capture"); + assertEquals(0, capture.captured()); + assertFalse(run.log.isEmpty(), "the spilled quad must be replayed into the run tessellator"); + assertTrue(run.log.get(0).equals("brightness(100)"), () -> "unexpected replay log: " + run.log); + assertEquals("vertexUV(2.0,2.0,0.0,0.5,0.5)", run.log.get(run.log.size() - 1), "the overflowing vertex must keep its own uv"); + + capture.setBrightness(999); + capture.setColorRGBA(9, 9, 9, 9); + assertEquals("brightness(999)", run.log.get(run.log.size() - 2)); + assertEquals("color(9,9,9,9)", run.log.get(run.log.size() - 1)); + } + + @Test + void setNormalSpillsImmediately() { + final RecordingTessellator run = new RecordingTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + + capture.begin(0, run, GLStateManager.getModelViewMatrix()); + capture.setColorRGBA(1, 1, 1, 1); + capture.addVertexWithUV(0.0, 0.0, 0.0, 0.0, 0.0); + capture.addVertexWithUV(0.0, 1.0, 0.0, 0.0, 1.0); + + capture.setNormal(0.0f, 1.0f, 0.0f); + + assertTrue(capture.spilled()); + assertEquals(0, capture.captured()); + assertTrue(run.log.contains("normal(0.0,1.0,0.0)")); + assertTrue(run.log.contains("vertexUV(0.0,0.0,0.0,0.0,0.0)")); + assertTrue(run.log.contains("vertexUV(0.0,1.0,0.0,0.0,1.0)")); + assertEquals(run.log.size() - 1, run.log.indexOf("normal(0.0,1.0,0.0)"), "normal must be forwarded after the replayed vertices"); + } + + @Test + void addVertexBeforeAnyUvSpillsImmediately() { + final RecordingTessellator run = new RecordingTessellator(); + final ParticleCaptureTessellator capture = new ParticleCaptureTessellator(); + + capture.begin(0, run, GLStateManager.getModelViewMatrix()); + capture.addVertex(3.0, 4.0, 5.0); + + assertTrue(capture.spilled()); + assertEquals(List.of("brightness(0)", "vertex(3.0,4.0,5.0)"), run.log); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingTest.java new file mode 100644 index 000000000..67f1809d0 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/particles/ParticleInstancingTest.java @@ -0,0 +1,99 @@ +package com.gtnewhorizons.angelica.rendering.particles; + +import com.gtnewhorizons.angelica.glsm.ffp.ParticleParityFixture; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ParticleInstancingTest { + + @BeforeEach + @AfterEach + void resetState() { + ParticleDescriptorRegistry.clearCache(); + } + + private static class PlainFx extends EntityFX { + + PlainFx() { + super(null, 0, 0, 0); + } + } + + private static class OverridingFx extends EntityFX { + + OverridingFx() { + super(null, 0, 0, 0); + } + + @Override + public void renderParticle(Tessellator t, float a, float b, float c, float d, float e, float f) {} + } + + private static float[] entityFxQuad(float cx, float cy, float cz, float half, ParticleParityFixture.Rotation r, float minU, float maxU, float minV, float maxV) { + final float[] u = { maxU, maxU, minU, minU }; + final float[] v = { maxV, minV, minV, maxV }; + final float[] verts = new float[20]; + for (int i = 0, o = 0; i < 4; i++, o += 5) { + final float a = ParticleParityFixture.cornerA(i) * half; + final float b = ParticleParityFixture.cornerB(i) * half; + verts[o] = cx + r.offsetX(a, b); + verts[o + 1] = cy + r.offsetY(b); + verts[o + 2] = cz + r.offsetZ(a, b); + verts[o + 3] = u[i]; + verts[o + 4] = v[i]; + } + return verts; + } + + @Test + void resolvesToVanillaUnlessRenderParticleIsOverridden() { + assertSame(ParticleDescriptorRegistry.VANILLA, ParticleDescriptorRegistry.forClass(PlainFx.class)); + assertSame(ParticleDescriptorRegistry.CAPTURE, ParticleDescriptorRegistry.forClass(OverridingFx.class)); + } + + @Test + void decodesAtCameraRelativeDistanceWithScaledTolerance() { + final ParticleParityFixture.Rotation r = ParticleParityFixture.Rotation.of(-64f, 33f, false); + final float cx = 214.0f, cy = -8.0f, cz = 196.5f, half = 0.045f; + final float[] verts = entityFxQuad(cx, cy, cz, half, r, 0.0f, 0.0625f, 0.0f, 0.0625f); + + final ParticleParams out = new ParticleParams(); + final boolean ok = ParticleQuadDecoder.decode(verts, 4, r.x(), r.xz(), r.z(), r.yz(), r.xy(), out); + + assertTrue(ok, "expected decode to succeed at camera-relative distance ~200"); + final float scale = Math.max(Math.abs(cx), Math.max(Math.abs(cy), Math.abs(cz))); + final float tol = 1.0e-5f * (1.0f + Math.abs(half) + scale); + assertEquals(cx, out.centerX, tol); + assertEquals(cy, out.centerY, tol); + assertEquals(cz, out.centerZ, tol); + } + + @Test + void rejectsQuadBuiltWithAMismatchedRotationBasis() { + final ParticleParityFixture.Rotation built = ParticleParityFixture.Rotation.of(0f, 0f, false); + final ParticleParityFixture.Rotation queried = ParticleParityFixture.Rotation.of(90f, 30f, false); + final float[] verts = entityFxQuad(0.5f, 1.0f, 0.5f, 0.1f, built, 0f, 1f, 0f, 1f); + + final boolean ok = ParticleQuadDecoder.decode(verts, 4, queried.x(), queried.xz(), queried.z(), queried.yz(), queried.xy(), new ParticleParams()); + + assertFalse(ok, "a quad built for a different camera orientation must not decode"); + } + + @Test + void rejectsUvNotMatchingTheBillboardPattern() { + final ParticleParityFixture.Rotation r = ParticleParityFixture.Rotation.of(10f, 10f, false); + final float[] verts = entityFxQuad(1f, 2f, 3f, 0.1f, r, 0.0f, 0.0625f, 0.0f, 0.0625f); + verts[8] = verts[3] + 0.01f; + + final boolean ok = ParticleQuadDecoder.decode(verts, 4, r.x(), r.xz(), r.z(), r.yz(), r.xy(), new ParticleParams()); + assertFalse(ok); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibilityTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibilityTest.java index 750317156..a88f03cb7 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibilityTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/BatchEligibilityTest.java @@ -1,5 +1,9 @@ package com.gtnewhorizons.angelica.rendering.tesr; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import net.minecraft.client.renderer.Tessellator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -105,4 +109,80 @@ class BatchEligibilityTest { BatchEligibility.end(SAFE, drawCalls); assertFalse(BatchEligibility.batchingAllowed()); } + + @Test + void bracketedDrawsWithAQueuedPartPromoteUnknownToSafe() { + BatchEligibility.begin(UNKNOWN, drawCalls); + BatchEligibility.onPartQueued(); + BatchEligibility.beginExpectedDraws(drawCalls); + draw(2); + BatchEligibility.endExpectedDraws(drawCalls); + assertEquals(SAFE, BatchEligibility.end(UNKNOWN, drawCalls)); + + BatchEligibility.begin(SAFE, drawCalls); + BatchEligibility.onPartQueued(); + BatchEligibility.beginExpectedDraws(drawCalls); + draw(2); + BatchEligibility.endExpectedDraws(drawCalls); + assertEquals(SAFE, BatchEligibility.end(SAFE, drawCalls)); + } + + @Test + void bracketDoesNotDoubleCountAFallbackPartsOwnDraws() { + BatchEligibility.begin(UNKNOWN, drawCalls); + BatchEligibility.beginExpectedDraws(drawCalls); + unbatchedPart(2); + BatchEligibility.endExpectedDraws(drawCalls); + draw(3); + assertEquals(DENIED, BatchEligibility.end(UNKNOWN, drawCalls)); + final long foreign = Reflect.getStatic(BatchEligibility.class, "foreignDraws"); + assertEquals(3, foreign, "only the 3 unbracketed draws must count as foreign"); + } + + @Test + void nestedBracketsCountOnlyTheOutermostSpan() { + BatchEligibility.begin(UNKNOWN, drawCalls); + BatchEligibility.onPartQueued(); + BatchEligibility.beginExpectedDraws(drawCalls); + draw(1); + BatchEligibility.beginExpectedDraws(drawCalls); + draw(1); + BatchEligibility.endExpectedDraws(drawCalls); + draw(1); + BatchEligibility.endExpectedDraws(drawCalls); + draw(2); + assertEquals(DENIED, BatchEligibility.end(UNKNOWN, drawCalls)); + final long foreign = Reflect.getStatic(BatchEligibility.class, "foreignDraws"); + assertEquals(2, foreign, "the inner bracket must not reset the outer span"); + } + + @Test + void shadowPassQueuesTheGlintWithoutTouchingTheCacheOrFallingBack() { + try { + Reflect.set(ModelPartBatcher.INSTANCE, "active", true); + Reflect.set(ModelPartBatcher.INSTANCE, "shadow", true); + Reflect.setStatic(DroppedItemInstancer.class, "basePart", true); + + final long glintBefore = DroppedItemInstancer.statGlintInstanced(); + final long fallbackBefore = DroppedItemInstancer.statFallback(); + final boolean[] originalCalled = { false }; + final Operation original = args -> { + originalCalled[0] = true; + return null; + }; + + BatchEligibility.begin(SAFE, 0L); + DroppedItemInstancer.glint(new Tessellator(), 1f, 0f, 0f, 1f, 16, 16, 0.0625f, original); + assertEquals(SAFE, BatchEligibility.end(SAFE, 0L)); + + assertFalse(originalCalled[0], "the shadow-pass early return must not fall back to the original draw"); + assertEquals(glintBefore, DroppedItemInstancer.statGlintInstanced(), "no instanced draw was queued"); + assertEquals(fallbackBefore, DroppedItemInstancer.statFallback(), "no fallback was recorded"); + } finally { + Reflect.set(ModelPartBatcher.INSTANCE, "active", false); + Reflect.set(ModelPartBatcher.INSTANCE, "shadow", false); + Reflect.setStatic(DroppedItemInstancer.class, "basePart", false); + DroppedItemInstancer.clear(); + } + } } diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java index 173585aa5..45a23ff94 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/EntityMaterialsTest.java @@ -46,6 +46,7 @@ class EntityMaterialsTest { @Test void glintStateMapsToGlintOnlyWhenTexAnimated() { assertSame(EntityMaterials.GLINT, EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false)); + assertNull(EntityMaterials.fromState(true, true, true, GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false), () -> "an alpha-blended animated decal such as a CIT armor overlay is not glint"); assertNull(EntityMaterials.fromState(true, false, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, false), () -> "glint blend without texture animation must stay live"); assertNull(EntityMaterials.fromState(true, true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_EQUAL, true), () -> "glint blend with depth write is not vanilla glint"); } @@ -64,6 +65,24 @@ class EntityMaterialsTest { assertSame(EntityMaterials.ADDITIVE_ALPHA_NO_DEPTH_WRITE, EntityMaterials.fromState(true, false, true, SA, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_LEQUAL, false)); } + @Test + void itemStateCutoutVsTranslucent() { + assertSame(EntityMaterials.DROPPED_ITEM_CUTOUT, EntityMaterials.itemFromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.HELD_BLOCK_CUTOUT, EntityMaterials.itemFromState(false, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.DROPPED_ITEM_TRANSLUCENT, EntityMaterials.itemFromState(true, true, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true)); + assertSame(EntityMaterials.HELD_BLOCK_TRANSLUCENT, EntityMaterials.itemFromState(false, true, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true)); + } + + @Test + void itemStateRejectsWrongAlphaRefOrFunc() { + assertNull(EntityMaterials.itemFromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.3f, GL11.GL_LEQUAL, true), "nonstandard alpha ref must stay live"); + assertNull(EntityMaterials.itemFromState(true, false, SA, OMSA, true, GL11.GL_LESS, 0.1f, GL11.GL_LEQUAL, true), "non-GREATER alpha func must stay live"); + assertNull(EntityMaterials.itemFromState(true, false, SA, OMSA, false, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true), "alpha test disabled must stay live"); + assertNull(EntityMaterials.itemFromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, false), "depth mask off must stay live"); + assertNull(EntityMaterials.itemFromState(true, false, SA, OMSA, true, GL11.GL_GREATER, 0.1f, GL11.GL_ALWAYS, true), "non-LEQUAL/LESS depth func must stay live"); + assertNull(EntityMaterials.itemFromState(true, true, GL11.GL_ONE, GL11.GL_ONE, true, GL11.GL_GREATER, 0.1f, GL11.GL_LEQUAL, true), "additive blend has no item material"); + } + @Test void unrecognizedStatesFallBackToLive() { assertNull(EntityMaterials.fromState(true, true, GL11.GL_SRC_COLOR, GL11.GL_ONE, false, GL11.GL_ALWAYS, 0f, GL11.GL_EQUAL, false), () -> "glint blend at EQUAL must stay live"); diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCaptureTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCaptureTest.java new file mode 100644 index 000000000..36aecbf5f --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/ModelBoxCaptureTest.java @@ -0,0 +1,221 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.UnitCubeMesh; +import net.coderbot.iris.vertices.IrisQuadView; +import net.coderbot.iris.vertices.NormalHelper; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.model.ModelBox; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.model.PositionTextureVertex; +import net.minecraft.client.model.TexturedQuad; +import org.joml.Vector3f; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ModelBoxCaptureTest { + + private static final float EPSILON = 1.0e-4f; + + private static final ByteBuffer CUBE = writeCube(); + + private static ByteBuffer writeCube() { + final ByteBuffer buffer = memAlloc(UnitCubeMesh.VERTEX_COUNT * UnitCubeMesh.VERTEX_STRIDE); + UnitCubeMesh.write(memAddress0(buffer)); + return buffer; + } + + private static float cube(int vertex, int offset) { + return CUBE.getFloat(vertex * UnitCubeMesh.VERTEX_STRIDE + offset); + } + + private static ModelRenderer part(int texWidth, int texHeight, boolean mirror) { + final ModelBase base = new ModelBase() {}; + base.textureWidth = texWidth; + base.textureHeight = texHeight; + final ModelRenderer part = new ModelRenderer(base, "test"); + part.mirror = mirror; + return part; + } + + private static TexturedQuad[] quadsOf(ModelBox box) { + try { + final Field field = ModelBox.class.getDeclaredField("quadList"); + field.setAccessible(true); + return (TexturedQuad[]) field.get(box); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + private static CubeParams capture(ModelRenderer part, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate) { + final ModelBox box = new ModelBox(part, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + return ModelBoxCapture.capture(quadsOf(box), part.textureWidth, part.textureHeight, part.mirror, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + } + + @ParameterizedTest + @CsvSource({ + "64, 32, false, 0, 0, -4, -8, -2, 8, 12, 4, 0.0", + "64, 32, true, 0, 0, -4, -8, -2, 8, 12, 4, 0.0", + "128, 64, false, 33, 17, 0.5, 1.5, -3.5, 5, 7, 11, 0.5", + "128, 64, true, 33, 17, 0.5, 1.5, -3.5, 5, 7, 11, 0.5", + "64, 32, false, 0, 0, -8, 0, -8, 16, 0, 16, 0.125", + "64, 32, true, 20, 4, -2, -2, 0, 4, 4, 0, 0.0625", + }) + void unitCubeReproducesVanillaBox(int texWidth, int texHeight, boolean mirror, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate) { + final ModelRenderer part = part(texWidth, texHeight, mirror); + final ModelBox box = new ModelBox(part, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + final CubeParams params = ModelBoxCapture.capture(quadsOf(box), part.textureWidth, part.textureHeight, mirror, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate); + assertNotNull(params, "vanilla box must verify"); + + final List vanilla = new ArrayList<>(); + for (TexturedQuad quad : quadsOf(box)) { + for (PositionTextureVertex vertex : quad.vertexPositions) { + vanilla.add(new float[] { (float) vertex.vector3D.xCoord, (float) vertex.vector3D.yCoord, (float) vertex.vector3D.zCoord, vertex.texturePositionX, vertex.texturePositionY }); + } + } + + for (int v = 0; v < UnitCubeMesh.VERTEX_COUNT; v++) { + final float[] expanded = expand(params, v); + if (!consume(vanilla, expanded)) { + fail("unit cube vertex " + v + " has no vanilla counterpart: pos=" + expanded[0] + "," + expanded[1] + "," + expanded[2] + " uv=" + expanded[3] + "," + expanded[4]); + } + } + assertTrue(vanilla.isEmpty(), "vanilla vertices left unmatched: " + vanilla.size()); + } + + private static float[] expand(CubeParams params, int vertex) { + final float mirror = params.uScaleX() < 0.0f ? 1.0f : 0.0f; + final float normalX = cube(vertex, UnitCubeMesh.OFFSET_NORMAL); + final float midUK = cube(vertex, UnitCubeMesh.OFFSET_MID) - mirror * normalX; + final float midUM = cube(vertex, UnitCubeMesh.OFFSET_MID + 4) - mirror * normalX; + final float sign = 1.0f - 2.0f * mirror; + final float uK = midUK + sign * cube(vertex, UnitCubeMesh.OFFSET_DELTA); + final float uM = midUM + sign * cube(vertex, UnitCubeMesh.OFFSET_DELTA + 4); + final float vL = cube(vertex, UnitCubeMesh.OFFSET_MID + 8) + cube(vertex, UnitCubeMesh.OFFSET_DELTA + 8); + final float vM = cube(vertex, UnitCubeMesh.OFFSET_MID + 12) + cube(vertex, UnitCubeMesh.OFFSET_DELTA + 12); + return new float[] { + params.minX() + cube(vertex, UnitCubeMesh.OFFSET_POSITION) * params.spanX(), + params.minY() + cube(vertex, UnitCubeMesh.OFFSET_POSITION + 4) * params.spanY(), + params.minZ() + cube(vertex, UnitCubeMesh.OFFSET_POSITION + 8) * params.spanZ(), + params.u0() + uK * Math.abs(params.uScaleX()) + uM * params.uScaleZ(), + params.v0() + vL * params.vScaleY() + vM * params.vScaleZ(), + }; + } + + private static boolean consume(List pool, float[] wanted) { + for (int i = 0; i < pool.size(); i++) { + final float[] candidate = pool.get(i); + boolean match = true; + for (int c = 0; c < 5; c++) { + if (Math.abs(candidate[c] - wanted[c]) >= EPSILON) { + match = false; + break; + } + } + if (match) { + pool.remove(i); + return true; + } + } + return false; + } + + @Test + void mutatedQuadListIsRejected() { + final ModelRenderer part = part(64, 32, false); + final ModelBox box = new ModelBox(part, 0, 0, -4, -8, -2, 8, 12, 4, 0.0f); + final TexturedQuad[] quads = quadsOf(box); + quads[3].vertexPositions[2] = quads[3].vertexPositions[2].setTexturePosition(0.75f, 0.75f); + + assertNull(ModelBoxCapture.capture(quads, part.textureWidth, part.textureHeight, false, 0, 0, -4, -8, -2, 8, 12, 4, 0.0f), "a rewritten uv must not verify"); + + final TexturedQuad[] replaced = quadsOf(new ModelBox(part, 0, 0, -4, -8, -2, 8, 12, 4, 0.0f)); + replaced[0] = new TexturedQuad(new PositionTextureVertex[] { + new PositionTextureVertex(0, 0, 0, 0, 0), new PositionTextureVertex(1, 0, 0, 1, 0), + new PositionTextureVertex(1, 1, 0, 1, 1), new PositionTextureVertex(0, 1, 0, 0, 1) }); + + assertNull(ModelBoxCapture.capture(replaced, part.textureWidth, part.textureHeight, false, 0, 0, -4, -8, -2, 8, 12, 4, 0.0f), "a replaced face must not verify"); + } + + @Test + void degenerateBoxIsRejected() { + final ModelRenderer part = part(64, 32, false); + assertNull(capture(part, 0, 0, -4, 0, -2, 8, 0, 4, 0.0f), "a flat box has no face normal to reproduce"); + + final ModelRenderer mirrored = part(64, 32, true); + assertNull(capture(mirrored, 0, 0, 0, -8, -2, 0, 12, 4, 0.25f), "the mirror flag needs a nonzero width to ride on"); + } + + private record QuadView(TexturedQuad quad) implements IrisQuadView { + + @Override + public float x(int index) { + return (float) quad.vertexPositions[index].vector3D.xCoord; + } + + @Override + public float y(int index) { + return (float) quad.vertexPositions[index].vector3D.yCoord; + } + + @Override + public float z(int index) { + return (float) quad.vertexPositions[index].vector3D.zCoord; + } + + @Override + public float u(int index) { + return quad.vertexPositions[index].texturePositionX; + } + + @Override + public float v(int index) { + return quad.vertexPositions[index].texturePositionY; + } + } + + @ParameterizedTest + @CsvSource({ "false", "true" }) + void cubeTangentsMatchVanillaQuads(boolean mirror) { + final ModelRenderer part = part(64, 32, mirror); + final ModelBox box = new ModelBox(part, 0, 0, -4, -8, -2, 8, 12, 4, 0.0f); + final float s = mirror ? -1.0f : 1.0f; + final Vector3f normal = new Vector3f(); + + for (TexturedQuad quad : quadsOf(box)) { + final QuadView view = new QuadView(quad); + NormalHelper.computeFaceNormal(normal, view); + final int face = faceOf(normal); + final float[] tangent = UnitCubeMesh.FACES[face].tangent(); + assertEquals(NormalHelper.packNormal(s * tangent[0], s * tangent[1], s * tangent[2], s * tangent[3]), NormalHelper.computeTangent(normal.x, normal.y, normal.z, view), "face " + face + " tangent"); + } + } + + private static int faceOf(Vector3f normal) { + int found = -1; + for (int face = 0; face < UnitCubeMesh.FACE_COUNT; face++) { + final float[] expected = UnitCubeMesh.FACES[face].normal(); + if (Math.abs(normal.x - expected[0]) < EPSILON && Math.abs(normal.y - expected[1]) < EPSILON && Math.abs(normal.z - expected[2]) < EPSILON) { + assertEquals(-1, found, "normal " + normal + " matches more than one cube face"); + found = face; + } + } + assertTrue(found >= 0, "no cube face has normal " + normal); + return found; + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java new file mode 100644 index 000000000..08390ec6d --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsGLTest.java @@ -0,0 +1,511 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParityFixture; +import com.gtnewhorizons.angelica.glsm.ffp.FfpFixture; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.rendering.GlintClock; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.TexRun; +import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroupsTest.CountingPipeline; +import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; +import net.minecraft.client.renderer.Tessellator; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class RetainedTesrGroupsGLTest { + + private static final int SIZE = 256; + private static final int BACKGROUND = 0xFF000000; + private static final float CUBE_SCALE = 0.1f; + private static final int COLOR_ABGR = 0xFF0000FF; + private static final float[] TRIANGLE = { -0.1f, -0.1f, 0f, 0.1f, -0.1f, 0f, 0f, 0.15f, 0f }; + + private static boolean overridesRegistered; + private static boolean skipClientArrays; + + private AngelicaBufferSource source; + private InstanceRing ring; + private InstancedTemplateRenderer instanced; + private RetainedTesrGroups groups; + private RetainedTesrGroupsTest.TestLayer layer; + + private int baseTexture; + private int glintTexture; + private Matrix4f glintMatrixA; + private Matrix4f glintMatrixB; + private final Matrix4f templateE1 = new Matrix4f().translation(-0.5f, 0f, 0f); + private final Matrix4f templateE2 = new Matrix4f().translation(0.5f, 0f, 0f); + private final Matrix4f cubeE1 = new Matrix4f().translation(-0.55f, 0f, 0f); + private final Matrix4f cubeE2 = new Matrix4f().translation(0.55f, 0f, 0f); + private TemplateBuffer glintTemplate; + private CubeParams[] glintCubes; + + @BeforeAll + static void registerClientArrayOverrides() { + if (overridesRegistered) return; + overridesRegistered = true; + VertexFormat.registerSetupBufferStateOverride((format, offset) -> skipClientArrays); + VertexFormat.registerClearBufferStateOverride(format -> skipClientArrays); + } + + @BeforeEach + void drawableState() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); + GLStateManager.glViewport(0, 0, 800, 600); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.disableFog(); + GLStateManager.disableLighting(); + GLStateManager.glColor4f(1f, 1f, 1f, 1f); + + final ShaderManager ffp = ShaderManager.getInstance(); + ffp.enable(); + ffp.activate(); + + source = new AngelicaBufferSource(); + ring = new InstanceRing(); + instanced = new InstancedTemplateRenderer(ring); + groups = new RetainedTesrGroups(source); + layer = new RetainedTesrGroupsTest.TestLayer(); + } + + @AfterEach + void cleanup() { + skipClientArrays = false; + GLStateManager.ffpInstancing = Instancing.NONE; + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + groups.clear(); + instanced.clear(); + ring.delete(); + final ShaderManager ffp = ShaderManager.getInstance(); + if (ffp.isActive()) ffp.deactivate(); + ffp.disable(); + if (baseTexture != 0) GLStateManager.glDeleteTextures(baseTexture); + if (glintTexture != 0) GLStateManager.glDeleteTextures(glintTexture); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glDepthMask(true); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDisable(GL11.GL_DEPTH_TEST); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + } + + private static TemplateBuffer template(float[] xyz, int colorABGR, int drawMode) { + final int vertexCount = xyz.length / 3; + final int[] data = new int[vertexCount * VERTEX_SIZE]; + for (int v = 0; v < vertexCount; v++) { + final int base = v * VERTEX_SIZE; + data[base + X_INDEX] = Float.floatToRawIntBits(xyz[v * 3]); + data[base + X_INDEX + 1] = Float.floatToRawIntBits(xyz[v * 3 + 1]); + data[base + X_INDEX + 2] = Float.floatToRawIntBits(xyz[v * 3 + 2]); + data[base + COLOR_INDEX] = colorABGR; + } + return new TemplateBuffer(data, vertexCount, drawMode); + } + + private static TemplateBuffer capturedQuad(double halfExtent) { + final AngelicaTesrMeshCache.GtnhMeshBackend backend = new AngelicaTesrMeshCache.GtnhMeshBackend(); + final Tessellator direct = backend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL); + direct.startDrawingQuads(); + direct.addVertexWithUV(-halfExtent, -halfExtent, 0.0, 0.0, 1.0); + direct.addVertexWithUV(halfExtent, -halfExtent, 0.0, 1.0, 1.0); + direct.addVertexWithUV(halfExtent, halfExtent, 0.0, 1.0, 0.0); + direct.addVertexWithUV(-halfExtent, halfExtent, 0.0, 0.0, 0.0); + direct.draw(); + return backend.endCaptureToTemplate(); + } + + private static TexRun run(int parts, int instances) { + final TexRun run = new TexRun(); + run.end = parts; + run.parts = parts; + run.instances = instances; + run.last = run; + return run; + } + + private static void drawSingleInstance(InstancedTemplateRenderer renderer, TemplateBuffer template, Matrix4fc mv, int colorABGR) { + final InstanceColumns cols = new InstanceColumns(); + cols.add(template, mv, 0, colorABGR, 0, 0L); + renderer.drawTemplates(cols, run(1, 1), System.currentTimeMillis()); + renderer.endFrame(); + } + + private void queueThreeEntities(CountingPipeline pipeline) { + final TemplateBuffer template = RetainedTesrGroupsTest.template(); + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced, pipeline); + for (int id = 1; id <= 3; id++) { + final Matrix4f mv = new Matrix4f().translation(id, 0f, 0f); + groups.queue(template, layer, RetainedTesrGroupsTest.STREAM, mv, 0, -1, 0, 0L, id, null); + groups.queue(template, RetainedTesrGroupsTest.cubes(1), 0.0625f, layer, RetainedTesrGroupsTest.STREAM, mv, 0, -1, 0, 0L, id, null); + } + } + + @Test + void bothVariantsBindOncePerLayer() { + final CountingPipeline pipeline = new CountingPipeline(true, true); + queueThreeEntities(pipeline); + + groups.drawLayer(layer); + + assertEquals(1, pipeline.matrixBinds, "one matrix variant bind for the whole layer"); + assertEquals(1, pipeline.cubeBinds, "one cube variant bind for the whole layer"); + assertEquals(2, pipeline.rebinds, "one resolve, one release"); + assertEquals(3, groups.instancedInstances); + assertEquals(3, groups.cubeInstances); + assertEquals(2, groups.instancedDraws, "the three ids collapse into one group: one template-run draw, one cube-run draw"); + assertEquals(0, groups.streamedInstances); + } + + @Test + void cubePartsRideTheMatrixVariantWhenTheCubeVariantIsMissing() { + final CountingPipeline pipeline = new CountingPipeline(true, false); + queueThreeEntities(pipeline); + + groups.drawLayer(layer); + + assertEquals(1, pipeline.matrixBinds); + assertEquals(0, pipeline.cubeBinds); + assertEquals(2, pipeline.rebinds, "one resolve, one release"); + assertEquals(6, groups.instancedInstances, "cube parts draw as their own templates"); + assertEquals(0, groups.cubeInstances); + assertEquals(0, groups.streamedInstances); + assertEquals(2, groups.instancedDraws, "one template-run draw, one cube-as-template-run draw"); + } + + @Test + void textureMatrixRunsDrawInsideTheSingleBind() { + final CountingPipeline pipeline = new CountingPipeline(true, true); + final TemplateBuffer template = RetainedTesrGroupsTest.template(); + final Matrix4f matrixA = new Matrix4f().translation(0.5f, 0f, 0f); + final Matrix4f matrixB = new Matrix4f().translation(0f, 0.5f, 0f); + final Matrix4f[] texMatrices = {matrixA, matrixB, matrixA}; + + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced, pipeline); + for (int id = 1; id <= 3; id++) { + final Matrix4f mv = new Matrix4f().translation(id, 0f, 0f); + groups.queue(template, layer, RetainedTesrGroupsTest.STREAM, mv, 0, -1, 0, 0L, id, texMatrices[id - 1]); + groups.queue(template, RetainedTesrGroupsTest.cubes(1), 0.0625f, layer, RetainedTesrGroupsTest.STREAM, mv, 0, -1, 0, 0L, id, null); + } + + groups.drawLayer(layer); + + assertEquals(4, groups.instancedDraws, "three texture-matrix template runs (A,B,A never merge non-adjacent) plus the single identity cube run"); + assertEquals(3, groups.texMatrixRuns, "one non-identity glLoadMatrix per drawn template run, not per distinct matrix value"); + assertEquals(GL11.GL_MODELVIEW, GLStateManager.getMatrixMode().getMode(), "matrix mode must be restored after the texture-matrix runs"); + assertTrue(MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)), "unit-0 texture matrix must be restored to identity"); + } + + @Test + void interleavedTemplatesBucketOncePerTemplate() { + final CountingPipeline pipeline = new CountingPipeline(true, false); + final TemplateBuffer first = RetainedTesrGroupsTest.template(); + final TemplateBuffer second = RetainedTesrGroupsTest.template(); + + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced, pipeline); + groups.queue(first, layer, EntityMaterials.GLINT, new Matrix4f().translation(1f, 0f, 0f), 0, -1, 0, 0L, 1, null); + groups.queue(second, layer, EntityMaterials.GLINT, new Matrix4f().translation(2f, 0f, 0f), 0, -1, 0, 0L, 2, null); + groups.queue(first, layer, EntityMaterials.GLINT, new Matrix4f().translation(3f, 0f, 0f), 0, -1, 0, 0L, 3, null); + + groups.drawLayer(layer); + + assertEquals(2, groups.instancedDraws, "one draw per distinct template, not per template change"); + assertEquals(3, groups.instancedInstances); + } + + @Test + void cpuFallbackVisitsEverySegmentOnce() { + final CountingPipeline pipeline = new CountingPipeline(false, false); + final TemplateBuffer template = template(new float[] { 0f, 0f, 0f, 1f, 0f, 0f, 2f, 0f, 0f }, 0xFFFFFFFF, GL11.GL_TRIANGLES); + final Matrix4f matrixA = new Matrix4f().translation(0.5f, 0f, 0f); + final Matrix4f matrixB = new Matrix4f().translation(0f, 0.5f, 0f); + final Matrix4f[] texMatrices = {matrixA, matrixB, matrixA}; + + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced, pipeline); + for (int id = 1; id <= 3; id++) { + final Matrix4f mv = new Matrix4f().translation(id, 0f, 0f); + groups.queue(template, layer, EntityMaterials.GLINT, mv, 0, -1, 0, 0L, id, texMatrices[id - 1]); + groups.queue(template, RetainedTesrGroupsTest.cubes(1), 0.0625f, layer, EntityMaterials.GLINT, mv, 0, -1, 0, 0L, id, texMatrices[id - 1]); + } + + final RetainedTesrGroups.Group group = RetainedTesrGroupsTest.onlyGroup(groups); + assertEquals(2, group.templateColumns.runs.size(), "sanity: template runs A,B,A merge into two heads"); + assertNotNull(group.templateColumns.runs.get(0).next, "sanity: the template A head must carry a second segment"); + assertEquals(2, group.cubeColumns.runs.size(), "sanity: cube runs A,B,A merge into two heads"); + assertNotNull(group.cubeColumns.runs.get(0).next, "sanity: the cube A head must carry a second segment"); + + skipClientArrays = true; + groups.drawLayer(layer); + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} + + assertEquals(0, pipeline.matrixBinds); + assertEquals(0, pipeline.cubeBinds); + assertEquals(1, pipeline.rebinds, "one resolve, no release when no variant was bound"); + assertEquals(0, groups.instancedDraws); + assertEquals(6, groups.streamedInstances, "three template instances plus three cube parts, every chained segment streamed exactly once"); + } + + @Test + void drawTemplatesBakesThePerInstanceModelviewIntoScreenPosition() { + GLStateManager.disableBlend(); + GLStateManager.disableAlphaTest(); + GLStateManager.disableTexture(); + + final Matrix4f translated = new Matrix4f().translation(0.3f, -0.2f, 0f); + final int tx = (int) ((translated.m30() * 0.5f + 0.5f) * 800); + final int ty = (int) ((translated.m31() * 0.5f + 0.5f) * 600); + final int originX = 400; + final int originY = 300; + final TemplateBuffer template = template(TRIANGLE, COLOR_ABGR, GL11.GL_TRIANGLES); + + GLStateManager.glClearColor(0f, 0f, 0f, 1f); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + drawSingleInstance(instanced, template, translated, COLOR_ABGR); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced draw must not raise a GL error"); + + final int[] atTranslation = FfpFixture.readPixel(tx, ty); + assertTrue(atTranslation[0] > 200 && atTranslation[1] < 50 && atTranslation[2] < 50, "translated instance must render red at (" + tx + "," + ty + "), got " + atTranslation[0] + "," + atTranslation[1] + "," + atTranslation[2]); + + final int[] atOrigin = FfpFixture.readPixel(originX, originY); + assertTrue(atOrigin[0] < 50 && atOrigin[1] < 50 && atOrigin[2] < 50, "the untranslated origin must stay background, got " + atOrigin[0] + "," + atOrigin[1] + "," + atOrigin[2]); + + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); + drawSingleInstance(instanced, template, new Matrix4f(), COLOR_ABGR); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "instanced draw must not raise a GL error"); + + final int[] identityAtOrigin = FfpFixture.readPixel(originX, originY); + assertTrue(identityAtOrigin[0] > 200 && identityAtOrigin[1] < 50 && identityAtOrigin[2] < 50, "an identity instance must render red at the origin, got " + identityAtOrigin[0] + "," + identityAtOrigin[1] + "," + identityAtOrigin[2]); + } + + private void glintState() { + GLStateManager.glViewport(0, 0, SIZE, SIZE); + + GlintClock.beginFrame(123456789L); + final float u0 = Reflect.getStatic(GlintClock.class, "armorU0"); + final float v0 = Reflect.getStatic(GlintClock.class, "armorV0"); + final float u1 = Reflect.getStatic(GlintClock.class, "armorU1"); + final float v1 = Reflect.getStatic(GlintClock.class, "armorV1"); + glintMatrixA = new Matrix4f().scale(1f / 3f).rotateZ((float) Math.toRadians(30.0)).translate(u0, v0, 0f); + glintMatrixB = new Matrix4f().scale(1f / 3f).rotateZ((float) Math.toRadians(-30.0)).translate(u1, v1, 0f); + + baseTexture = FfpFixture.solidTexture(60, 60, 60, 255); + glintTexture = createGlintTexture(); + glintTemplate = capturedQuad(0.35); + glintCubes = RetainedTesrGroupsTest.cubes(1); + } + + private static int createGlintTexture() { + final int id = GLStateManager.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); + 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); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); + final ByteBuffer texels = BufferUtils.createByteBuffer(4 * 4 * 4); + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 4; x++) { + texels.put((byte) (64 + 48 * x)).put((byte) (64 + 48 * y)).put((byte) 200).put((byte) (64 + 48 * x)); + } + } + texels.flip(); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, 4, 4, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + return id; + } + + private void bindBase() { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, baseTexture); + GLStateManager.enableTexture(); + GLStateManager.disableBlend(); + GLStateManager.disableAlphaTest(); + GLStateManager.enableDepthTest(); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + } + + private static void setGlintBlendState() { + GLStateManager.disableAlphaTest(); + GLStateManager.glDepthFunc(GL11.GL_EQUAL); + GLStateManager.glDepthMask(false); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } + + private void applyGlintTexMatrix(Matrix4f m) { + bindGlint(); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + final FloatBuffer buf = BufferUtils.createFloatBuffer(16); + m.get(buf); + GLStateManager.glLoadMatrix(buf); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + private static void restoreTexMatrix() { + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + private void bindGlint() { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, glintTexture); + } + + private int[] drawBaseTemplates() { + FfpFixture.clear(); + bindBase(); + final InstanceColumns cols = new InstanceColumns(); + cols.add(glintTemplate, templateE1, 0, 0xFFFFFFFF, 0, 0L); + cols.add(glintTemplate, templateE2, 0, 0xFFFFFFFF, 0, 0L); + instanced.drawTemplates(cols, run(2, 2), System.currentTimeMillis()); + instanced.endFrame(); + return FfpFixture.readRegion(SIZE); + } + + private int[] drawBaseCubes() { + FfpFixture.clear(); + bindBase(); + final InstanceColumns cols = new InstanceColumns(); + cols.addCubes(null, glintCubes, CUBE_SCALE, cubeE1, 0, 0xFFFFFFFF, 0, 0L); + cols.addCubes(null, glintCubes, CUBE_SCALE, cubeE2, 0, 0xFFFFFFFF, 0, 0L); + instanced.drawCubes(cols, run(2, 2 * glintCubes.length)); + instanced.endFrame(); + return FfpFixture.readRegion(SIZE); + } + + private void drawCubeInstance(Matrix4f mv) { + final InstanceColumns cols = new InstanceColumns(); + cols.addCubes(null, glintCubes, CUBE_SCALE, mv, 0, 0xFFFFFFFF, 0, 0L); + instanced.drawCubes(cols, run(1, glintCubes.length)); + instanced.endFrame(); + } + + private int[] templateReference(boolean swapFirstEmitter) { + drawBaseTemplates(); + setGlintBlendState(); + applyGlintTexMatrix(swapFirstEmitter ? glintMatrixB : glintMatrixA); + drawSingleInstance(instanced, glintTemplate, templateE1, 0xFFFFFFFF); + applyGlintTexMatrix(swapFirstEmitter ? glintMatrixA : glintMatrixB); + drawSingleInstance(instanced, glintTemplate, templateE1, 0xFFFFFFFF); + applyGlintTexMatrix(glintMatrixA); + drawSingleInstance(instanced, glintTemplate, templateE2, 0xFFFFFFFF); + applyGlintTexMatrix(glintMatrixB); + drawSingleInstance(instanced, glintTemplate, templateE2, 0xFFFFFFFF); + restoreTexMatrix(); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "the sequential reference draws must not raise a GL error"); + return FfpFixture.readRegion(SIZE); + } + + private int[] templateCandidate() { + drawBaseTemplates(); + setGlintBlendState(); + bindGlint(); + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); + groups.queue(glintTemplate, layer, EntityMaterials.GLINT, templateE1, 0, -1, 0, 0L, 1, glintMatrixA); + groups.queue(glintTemplate, layer, EntityMaterials.GLINT, templateE1, 0, -1, 0, 0L, 1, glintMatrixB); + groups.queue(glintTemplate, layer, EntityMaterials.GLINT, templateE2, 0, -1, 0, 0L, 2, glintMatrixA); + groups.queue(glintTemplate, layer, EntityMaterials.GLINT, templateE2, 0, -1, 0, 0L, 2, glintMatrixB); + groups.drawLayer(layer); + instanced.endFrame(); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "the merged candidate draw must not raise a GL error"); + return FfpFixture.readRegion(SIZE); + } + + private int[] cubeReference() { + drawBaseCubes(); + setGlintBlendState(); + applyGlintTexMatrix(glintMatrixA); + drawCubeInstance(cubeE1); + applyGlintTexMatrix(glintMatrixB); + drawCubeInstance(cubeE1); + applyGlintTexMatrix(glintMatrixA); + drawCubeInstance(cubeE2); + applyGlintTexMatrix(glintMatrixB); + drawCubeInstance(cubeE2); + restoreTexMatrix(); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "the sequential reference draws must not raise a GL error"); + return FfpFixture.readRegion(SIZE); + } + + private int[] cubeCandidate() { + drawBaseCubes(); + setGlintBlendState(); + bindGlint(); + groups.beginPass(new Matrix4f(), 0, 0, 0, instanced); + groups.queue(null, glintCubes, CUBE_SCALE, layer, EntityMaterials.GLINT, cubeE1, 0, -1, 0, 0L, 1, glintMatrixA); + groups.queue(null, glintCubes, CUBE_SCALE, layer, EntityMaterials.GLINT, cubeE1, 0, -1, 0, 0L, 1, glintMatrixB); + groups.queue(null, glintCubes, CUBE_SCALE, layer, EntityMaterials.GLINT, cubeE2, 0, -1, 0, 0L, 2, glintMatrixA); + groups.queue(null, glintCubes, CUBE_SCALE, layer, EntityMaterials.GLINT, cubeE2, 0, -1, 0, 0L, 2, glintMatrixB); + groups.drawLayer(layer); + instanced.endFrame(); + assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "the merged candidate draw must not raise a GL error"); + return FfpFixture.readRegion(SIZE); + } + + private static String describe(int pixel) { + return "0x" + Integer.toHexString(pixel); + } + + @Test + void templateGlintRunsMatchSequentialDrawsUnderAlphaBlend() { + glintState(); + final int[] base = drawBaseTemplates(); + final int[] reference = templateReference(false); + FfpFixture.assertOverlayFootprint(base, reference, BACKGROUND, "glint"); + + final int[] swapped = templateReference(true); + int differing = 0; + for (int i = 0; i < reference.length; i++) { + if (reference[i] != swapped[i]) differing++; + } + assertTrue(differing > 0, "swapping e1's k0/k1 draw order under alpha blending must change the rendered " + "pixels, otherwise the parity tests could not detect a reversed emitter order"); + + CubeParityFixture.assertPixelParity(reference, templateCandidate(), SIZE, BACKGROUND, RetainedTesrGroupsGLTest::describe); + } + + @Test + void cubeGlintRunsMatchSequentialDrawsUnderAlphaBlend() { + glintState(); + final int[] base = drawBaseCubes(); + final int[] reference = cubeReference(); + FfpFixture.assertOverlayFootprint(base, reference, BACKGROUND, "glint"); + CubeParityFixture.assertPixelParity(reference, cubeCandidate(), SIZE, BACKGROUND, RetainedTesrGroupsGLTest::describe); + } +} 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 90a93a545..996e9767a 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/RetainedTesrGroupsTest.java @@ -2,11 +2,18 @@ package com.gtnewhorizons.angelica.rendering.tesr; import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; +import com.gtnewhorizons.angelica.glsm.ffp.CubeParams; +import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource; import net.coderbot.batchedentityrendering.impl.BatchVertexFormats; import net.coderbot.batchedentityrendering.impl.BufferSegment; import net.coderbot.batchedentityrendering.impl.BufferSourceProbe; import org.joml.Matrix4f; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; @@ -17,25 +24,36 @@ import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VE import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; class RetainedTesrGroupsTest { - private static final class TestLayer extends RenderLayer { + private final InstanceRing ring = new InstanceRing(); + private AngelicaBufferSource source; + private RetainedTesrGroups groups; + private TestLayer layer; + + static final class TestLayer extends RenderLayer { TestLayer() { super("test", BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 256, () -> {}, () -> {}); } } + @BeforeEach + void freshGroups() { + source = new AngelicaBufferSource(); + groups = new RetainedTesrGroups(source); + layer = new TestLayer(); + } + @Test void retainedGroupAccumulatesInsteadOfStreaming() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 5, null); assertTrue(groups.hasDraws(layer)); assertEquals(0, groups.streamedInstances); @@ -46,16 +64,13 @@ class RetainedTesrGroupsTest { @Test void streamingGroupStreamsIntoDynamicSegments() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); assertEquals(1, groups.streamPromotions); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); - groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(4f, 5f, 6f), 0, -1, 5, null, false); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 0, 0L, 5, null); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(4f, 5f, 6f), 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), "volatile group must not report retained draws"); assertEquals(2, groups.streamedInstances); @@ -69,9 +84,6 @@ class RetainedTesrGroupsTest { @Test void stableTransformsDemoteStreamingGroup() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TemplateBuffer template = template(); final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); @@ -79,7 +91,7 @@ class RetainedTesrGroupsTest { long streamedFrames = 0; for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) { groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, fixed, 0, -1, 5, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, fixed, 0, -1, 0, 0L, 5, null); if (groups.hasDraws(layer)) break; streamedFrames++; } @@ -90,30 +102,24 @@ class RetainedTesrGroupsTest { @Test void movingTransformsStayStreaming() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TemplateBuffer template = template(); groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); for (int frame = 0; frame < RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; frame++) { groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(frame, 0f, 0f), 0, -1, 5, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f().translation(frame, 0f, 0f), 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), "moving group must keep streaming at frame " + frame); } } @Test void idleGapResetsVolatility() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); groups.forceStreaming(layer, TesrMaterial.CURRENT_STATE, 5); for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) { groups.beginPass(new Matrix4f(), 0, 0, 0); } - groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 5, null, false); + groups.queue(template(), layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 5, null); assertTrue(groups.hasDraws(layer), "idle reset must demote the group back to retained"); assertEquals(0, groups.streamedInstances); @@ -121,9 +127,6 @@ class RetainedTesrGroupsTest { @Test void translucentStreamingGroupNeverDemotes() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TesrMaterial translucent = TesrMaterial.builder().translucent().build(); final TemplateBuffer template = template(); final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); @@ -132,7 +135,7 @@ class RetainedTesrGroupsTest { final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; for (int frame = 0; frame < frames; frame++) { groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, translucent, fixed, 0, -1, 5, null, false); + groups.queue(template, layer, translucent, fixed, 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), "translucent group must keep streaming at frame " + frame); } assertEquals(frames, groups.streamedInstances); @@ -140,13 +143,10 @@ class RetainedTesrGroupsTest { @Test void streamMaterialStreamsFromFirstQueue() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); + groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), "stream group must not report retained draws"); assertEquals(1, groups.streamedInstances); @@ -163,16 +163,14 @@ class RetainedTesrGroupsTest { for (final TesrMaterial material : new TesrMaterial[] { TesrMaterial.builder().stream().build(), TesrMaterial.builder().translucent().stream().build()}) { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); + freshGroups(); final TemplateBuffer template = template(); final Matrix4f fixed = new Matrix4f().translation(1f, 2f, 3f); final int frames = RetainedTesrGroups.DEMOTE_AFTER_STABLE_FRAMES + 4; for (int frame = 0; frame < frames; frame++) { groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, material, fixed, 0, -1, 5, null, false); + groups.queue(template, layer, material, fixed, 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), material.transparency() + " stream group must keep streaming at frame " + frame); } assertEquals(frames, groups.streamedInstances); @@ -181,17 +179,14 @@ class RetainedTesrGroupsTest { @Test void idleGapKeepsStreamGroupStreaming() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false); + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 0, 0L, 5, null); for (long i = 0; i <= RetainedTesrGroups.IDLE_RESET_FRAMES + 1; i++) { groups.beginPass(new Matrix4f(), 0, 0, 0); } - groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, null, false); + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 0, 0L, 5, null); assertFalse(groups.hasDraws(layer), "idle reset must not move a stream group to retained"); assertEquals(2, groups.streamedInstances); @@ -199,13 +194,10 @@ class RetainedTesrGroupsTest { @Test void streamGroupRoutesToInstanceArraysWhenInstancedCapable() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); - groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); - groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, false); + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 0, 0L, 5, null); assertTrue(groups.hasDraws(layer), "instanced-capable stream group accumulates for the hook draw"); assertEquals(0, groups.streamedInstances, "no segment streaming when instanced"); @@ -214,44 +206,29 @@ class RetainedTesrGroupsTest { } @Test - void forceStreamSkipsInstanceArraysEvenWhenInstancedCapable() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); + void streamGroupTexMatrixOpensARun() { final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); + final Matrix4f texMatrix = new Matrix4f().translation(0.5f, 0.5f, 0f); - groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); - groups.queue(template(), layer, stream, new Matrix4f().translation(1f, 2f, 3f), 0, -1, 5, null, true); + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 0, 0L, 5, texMatrix); + texMatrix.translation(9f, 9f, 9f); - assertFalse(groups.hasDraws(layer), "forceStream instance must not enter the instance arrays"); - assertEquals(1, groups.streamedInstances); - } - - @Test - void streamGroupTexMatrixFallsBackToSegmentStream() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); - final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); - - groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer()); - groups.queue(template(), layer, stream, new Matrix4f(), 0, -1, 5, new Matrix4f().translation(0.5f, 0.5f, 0f), false); - - assertFalse(groups.hasDraws(layer), "texMatrix instance must not enter the instance arrays"); - assertEquals(1, groups.streamedInstances); + assertTrue(groups.hasDraws(layer), "a texture matrix now opens an instanced run instead of falling back to streaming"); + assertEquals(0, groups.streamedInstances); + final RetainedTesrGroups.Group group = onlyGroup(groups); + assertEquals(1, group.templateColumns.runs.size()); + assertEquals(new Matrix4f().translation(0.5f, 0.5f, 0f), group.templateColumns.runs.get(0).matrix, "the run holds a copy, not the caller's matrix"); } @Test void streamGroupDrawModeMismatchFallsBackToRetained() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TesrMaterial stream = TesrMaterial.builder().translucent().stream().build(); final int[] data = new int[3 * VERTEX_SIZE]; final TemplateBuffer triangles = new TemplateBuffer(data, 3, GL11.GL_TRIANGLES); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(triangles, layer, stream, new Matrix4f(), 0, -1, 5, null, false); + groups.queue(triangles, layer, stream, new Matrix4f(), 0, -1, 0, 0L, 5, null); assertTrue(groups.hasDraws(layer), "mismatched drawMode must fall back to retained accumulation"); assertEquals(0, groups.streamedInstances); @@ -260,50 +237,45 @@ class RetainedTesrGroupsTest { @Test void sweepEvictsIdleGroupsAndKeepsLive() { final long[] clock = {1_000L}; - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source, () -> clock[0]); - final TestLayer layer = new TestLayer(); + groups = new RetainedTesrGroups(source, () -> clock[0]); final TemplateBuffer template = template(); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 2, null); assertEquals(2, groups.groupCount()); clock[0] += RetainedTesrGroups.GROUP_TTL_MS + 1; groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); groups.sweep(clock[0]); assertEquals(1, groups.groupCount(), "idle group must be evicted, live group kept"); assertTrue(groups.hasDraws(layer), "live group still draws this frame"); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 2, null); assertEquals(2, groups.groupCount(), "evicted id must be re-creatable"); } @Test void clearEmptiesAllGroups() { - final AngelicaBufferSource source = new AngelicaBufferSource(); - final RetainedTesrGroups groups = new RetainedTesrGroups(source); - final TestLayer layer = new TestLayer(); final TemplateBuffer template = template(); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 2, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 2, null); groups.clear(); assertEquals(0, groups.groupCount()); assertFalse(groups.hasDraws(layer)); groups.beginPass(new Matrix4f(), 0, 0, 0); - groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 1, null, false); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); assertEquals(1, groups.groupCount()); assertTrue(groups.hasDraws(layer)); } - private static TemplateBuffer template() { + static TemplateBuffer template() { final int[] data = new int[4 * VERTEX_SIZE]; for (int v = 0; v < 4; v++) { final int base = v * VERTEX_SIZE; @@ -312,4 +284,202 @@ class RetainedTesrGroupsTest { } return new TemplateBuffer(data, 4, GL11.GL_QUADS); } + + static final TesrMaterial STREAM = TesrMaterial.builder().stream().build(); + + static CubeParams[] cubes(int count) { + final CubeParams[] params = new CubeParams[count]; + for (int i = 0; i < count; i++) { + params[i] = CubeParams.of(64f, 32f, i % 2 == 1, i * 8, 0, -4f, -4f, -2f, 8, 8, 4, 0f); + assertNotNull(params[i], "cube " + i + " must pack"); + } + return params; + } + + private static int cubeInstances(RetainedTesrGroups groups) { + final Reference2ObjectOpenHashMap> byLayer = Reflect.get(groups, "byLayer"); + int total = 0; + for (final ObjectArrayList list : byLayer.values()) { + for (int i = 0; i < list.size(); i++) { + final ObjectArrayList runs = list.get(i).cubeColumns.runs; + for (int r = 0; r < runs.size(); r++) total += runs.get(r).instances; + } + } + return total; + } + + static RetainedTesrGroups.Group onlyGroup(RetainedTesrGroups groups) { + final Reference2ObjectOpenHashMap> byLayer = Reflect.get(groups, "byLayer"); + assertEquals(1, byLayer.size()); + final ObjectArrayList list = byLayer.values().iterator().next(); + assertEquals(1, list.size()); + return list.get(0); + } + + @Test + void cubePartsRouteToPerPartRecordsThatKeepTheirTemplate() { + final TemplateBuffer template = template(); + final Matrix4f mv = new Matrix4f().translation(1f, 2f, 3f); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template, cubes(3), 0.0625f, layer, STREAM, mv, 7, -1, 0, 0L, 5, null); + groups.queue(template, cubes(2), 0.0625f, layer, STREAM, new Matrix4f(), 7, -1, 0, 0L, 5, null); + + assertTrue(groups.hasDraws(layer)); + assertEquals(0, groups.streamedInstances); + final RetainedTesrGroups.Group group = onlyGroup(groups); + assertEquals(0, group.templateColumns.size, "cube parts stay out of the template columns"); + assertEquals(2, group.cubeColumns.size, "one record per part, not per cube"); + assertEquals(5, cubeInstances(groups)); + assertTrue(group.cubeColumns.templates.isEmpty(), "the FFP cube path has no fallback that needs the template"); + + final RetainedTesrGroups piped = new RetainedTesrGroups(source); + piped.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring), new CountingPipeline(false, false)); + piped.queue(template, cubes(3), 0.0625f, layer, STREAM, mv, 7, -1, 0, 0L, 5, null); + piped.queue(template, cubes(2), 0.0625f, layer, STREAM, new Matrix4f(), 7, -1, 0, 0L, 5, null); + + final RetainedTesrGroups.Group pipedGroup = onlyGroup(piped); + assertEquals(2, pipedGroup.cubeColumns.templates.size(), "a pipeline can fall back to the per-part template"); + assertSame(template, pipedGroup.cubeColumns.templates.get(0)); + } + + static final class CountingPipeline implements TesrInstancingPipeline { + + private final boolean matrixVariant; + private final boolean cubeVariant; + int rebinds; + int matrixBinds; + int cubeBinds; + + CountingPipeline(boolean matrixVariant, boolean cubeVariant) { + this.matrixVariant = matrixVariant; + this.cubeVariant = cubeVariant; + } + + @Override + public void rebindCurrentPass() { + rebinds++; + } + + @Override + public boolean hasInstancedVariant(Instancing kind) { + return switch (kind) { + case TEMPLATE -> matrixVariant; + case CUBE -> cubeVariant; + default -> false; + }; + } + + @Override + public void bindInstancedVariant(Instancing kind) { + switch (kind) { + case TEMPLATE -> matrixBinds++; + case CUBE -> cubeBinds++; + default -> throw new AssertionError(kind); + } + } + } + + @Test + void cubePartsFallBackToTemplatesWithoutAnInstancedRenderer() { + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template(), cubes(2), 0.0625f, layer, STREAM, new Matrix4f(), 0, -1, 0, 0L, 5, null); + + assertEquals(0, cubeInstances(groups)); + assertEquals(1, groups.streamedInstances); + } + + @Test + void cubeInstancesClearBetweenFrames() { + final CubeParams[] params = cubes(2); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template(), params, 0.0625f, layer, STREAM, new Matrix4f(), 0, -1, 0, 0L, 5, null); + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template(), params, 0.0625f, layer, STREAM, new Matrix4f(), 0, -1, 0, 0L, 5, null); + + assertEquals(2, cubeInstances(groups), "the previous frame's instances must not accumulate"); + } + + @Test + void groupIdOnlySplitsPerEntityWhenAPackIsLoaded() { + assertEquals(ModelPartBatcher.groupId(true, true, -1, 9), RetainedTesrGroups.entityFromInfo(InstancedAttribs.packEntityInfo(-1, 9, 0))); + } + + @Test + void overlayRunsDoNotMergeAcrossEmitters() { + final TemplateBuffer template = template(); + final Matrix4f matrixA = new Matrix4f().translation(0.5f, 0f, 0f); + final Matrix4f matrixB = new Matrix4f().translation(0f, 0.5f, 0f); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template, layer, EntityMaterials.OVERLAY, new Matrix4f(), 0, -1, 0, 0L, 1, matrixA); + groups.queue(template, layer, EntityMaterials.OVERLAY, new Matrix4f(), 0, -1, 0, 0L, 2, matrixA); + groups.queue(template, layer, EntityMaterials.OVERLAY, new Matrix4f(), 0, -1, 0, 0L, 3, matrixB); + groups.queue(template, layer, EntityMaterials.OVERLAY, new Matrix4f(), 0, -1, 0, 0L, 4, matrixA); + + final RetainedTesrGroups.Group group = onlyGroup(groups); + assertEquals(3, group.templateColumns.runs.size(), "OVERLAY is depth-equal but writes depth, so it must not merge like GLINT"); + } + + @Test + void pooledRunsDropStaleChains() { + final TemplateBuffer template = template(); + final Matrix4f matrixA = new Matrix4f().translation(0.5f, 0f, 0f); + final Matrix4f matrixB = new Matrix4f().translation(0f, 0.5f, 0f); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template, layer, EntityMaterials.GLINT, new Matrix4f(), 0, -1, 0, 0L, 1, matrixA); + groups.queue(template, layer, EntityMaterials.GLINT, new Matrix4f(), 0, -1, 0, 0L, 2, matrixB); + groups.queue(template, layer, EntityMaterials.GLINT, new Matrix4f(), 0, -1, 0, 0L, 3, matrixA); + final RetainedTesrGroups.Group frame1 = onlyGroup(groups); + assertEquals(2, frame1.templateColumns.runs.size()); + assertNotNull(frame1.templateColumns.runs.get(0).next, "sanity: frame 1 must build a chain"); + + groups.beginPass(new Matrix4f(), 0, 0, 0, new InstancedTemplateRenderer(ring)); + groups.queue(template, layer, EntityMaterials.GLINT, new Matrix4f(), 0, -1, 0, 0L, 1, matrixA); + + final RetainedTesrGroups.Group frame2 = onlyGroup(groups); + assertEquals(1, frame2.templateColumns.runs.size(), "only one distinct matrix was queued this frame"); + final RetainedTesrGroups.TexRun head = frame2.templateColumns.runs.get(0); + assertNull(head.next, "a pooled run reused from a previous chain must drop its stale next pointer"); + assertSame(head, head.last); + } + + @Test + void sweptGroupIsNotResurrectedByTheMemo() { + final long[] clock = {1_000L}; + groups = new RetainedTesrGroups(source, () -> clock[0]); + final TemplateBuffer template = template(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); + assertEquals(1, groups.groupCount()); + + clock[0] += RetainedTesrGroups.GROUP_TTL_MS + 1; + groups.sweep(clock[0]); + assertEquals(0, groups.groupCount(), "the idle group must be evicted"); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, TesrMaterial.CURRENT_STATE, new Matrix4f(), 0, -1, 0, 0L, 1, null); + + assertEquals(1, groups.groupCount(), "a fresh group must be created, not the evicted one resurrected by the last-group memo"); + assertTrue(groups.hasDraws(layer), "the new group must be reachable through the layer map for drawing"); + } + + @Test + void alternatingMaterialsRouteToTheirOwnGroups() { + final TemplateBuffer template = template(); + final TesrMaterial materialA = TesrMaterial.builder().stream().build(); + final TesrMaterial materialB = TesrMaterial.builder().translucent().stream().build(); + + groups.beginPass(new Matrix4f(), 0, 0, 0); + groups.queue(template, layer, materialA, new Matrix4f(), 0, -1, 0, 0L, 5, null); + groups.queue(template, layer, materialB, new Matrix4f(), 0, -1, 0, 0L, 5, null); + groups.queue(template, layer, materialA, new Matrix4f(), 0, -1, 0, 0L, 5, null); + groups.queue(template, layer, materialB, new Matrix4f(), 0, -1, 0, 0L, 5, null); + + assertEquals(2, groups.groupCount(), "the last-group memo must compare material, not just layer and id, on every queue call"); + } } 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 58f2ac1d7..4f29a7c72 100644 --- a/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/rendering/tesr/TesrLayerStateTest.java @@ -4,12 +4,23 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMaterial; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.glsm.GLCoreTest; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.shadercompat.ShaderGlint; +import net.coderbot.iris.gl.blending.AlphaTestStorage; +import net.coderbot.iris.gl.blending.DepthColorStorage; +import net.coderbot.iris.layer.PassOverride; +import org.joml.Matrix4f; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; 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.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @GLCoreTest @@ -28,10 +39,49 @@ class TesrLayerStateTest { GLStateManager.enableLighting(); } + @AfterEach + void tearDown() { + AlphaTestStorage.restoreAlphaTest(); + DepthColorStorage.unlockDepthColor(); + GLStateManager.getAlphaTest().setVanillaLayer(null); + GLStateManager.getAlphaState().setVanillaLayer(null); + GLStateManager.getDepthState().setVanillaLayer(null); + + ModelPartBatcher.INSTANCE.clear(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + final ShaderManager ffp = ShaderManager.getInstance(); + if (ffp.isActive()) ffp.deactivate(); + ffp.disable(); + + GLStateManager.disableBlend(); + GLStateManager.disableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_ALWAYS, 0f); + GLStateManager.glDepthFunc(GL11.GL_LESS); + GLStateManager.glDepthMask(true); + GLStateManager.glColorMask(true, true, true, true); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + } + private static RenderLayer layer(TesrMaterial material) { return RenderLayer.tesr(null, material); } + private static RenderLayer glint(int slot) { + return RenderLayer.tesr(null, EntityMaterials.GLINT, PassOverride.NONE, 0f, 0f, slot); + } + + @Test + void glintTintSlotsSplitLayers() { + assertSame(glint(0), glint(0), "the same slot must reuse the layer"); + assertNotSame(glint(1), glint(0), "distinct slots must not share a layer"); + assertNotSame(glint(ShaderGlint.NO_TINT), glint(0), "an untinted glint must not share a tinted layer"); + } + @Test void startDrawingLeavesUndeclaredPhasesToTheSurroundingContext() { layer(TesrMaterial.CURRENT_STATE).startDrawing(); @@ -63,7 +113,8 @@ class TesrLayerStateTest { @Test void everyMaterialToggleApplies() { final TesrMaterial material = TesrMaterial.builder().noCull().unlit().noDepthWrite().cutout(0.5f).translucent().depthEqual().build(); - layer(material).startDrawing(); + final RenderLayer layer = layer(material); + layer.startDrawing(); assertFalse(GLStateManager.getCullState().isEnabled(), "noCull"); assertFalse(GLStateManager.getLightingState().isEnabled(), "unlit"); @@ -74,5 +125,99 @@ class TesrLayerStateTest { assertEquals(GL11.GL_SRC_ALPHA, GLStateManager.getBlendState().getSrcRgb()); assertEquals(GL11.GL_ONE_MINUS_SRC_ALPHA, GLStateManager.getBlendState().getDstRgb()); assertEquals(GL11.GL_EQUAL, GLStateManager.getDepthState().getFunc(), "depthEqual"); + + layer.endDrawing(); + + assertFalse(GLStateManager.getBlendMode().isEnabled(), "blend restored"); + assertTrue(GLStateManager.getDepthState().isEnabled(), "depth write restored"); + assertTrue(GLStateManager.getLightingState().isEnabled(), "lighting restored"); + } + + @Test + void effectiveAlphaStateSurvivesAPackOverridingTheRawAlphaTest() { + GLStateManager.getAlphaTest().setVanillaLayer(AlphaTestStorage.ENABLE_LAYER); + GLStateManager.getAlphaState().setVanillaLayer(AlphaTestStorage.FUNC_LAYER); + + GLStateManager.disableBlend(); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.enableAlphaTest(); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1f); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + + AlphaTestStorage.overrideAlphaTest(null); + + assertSame(EntityMaterials.CUTOUT, EntityMaterials.fromCurrentState(true), "raw alpha test is disabled by the pack override; a raw read would give SOLID"); + assertSame(EntityMaterials.DROPPED_ITEM_CUTOUT, EntityMaterials.itemFromCurrentState(true)); + } + + @Test + void effectiveDepthMaskSurvivesAnotherPassHoldingItOff() { + GLStateManager.getDepthState().setVanillaLayer(DepthColorStorage.DEPTH_LAYER); + + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + + DepthColorStorage.disableDepthColor(); + + assertSame(EntityMaterials.TRANSLUCENT_DEPTH_WRITE, EntityMaterials.fromCurrentState(true), "raw depth mask held off by another pass; the effective vanilla mask must pick the depth-write variant"); + } + + private static boolean unitTexIdentity() { + return Reflect.invoke(ModelPartBatcher.INSTANCE, "unitTexIdentity", new Class[0]); + } + + private static Matrix4f texMatrixScratch() { + return Reflect.get(ModelPartBatcher.INSTANCE, "texMatrixScratch"); + } + + @Test + void memoTracksTextureModeOperationsOnUnitZero() { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + final ShaderManager ffp = ShaderManager.getInstance(); + ffp.enable(); + ffp.activate(); + + assertTrue(unitTexIdentity(), "a freshly loaded identity unit-0 matrix must read as identity"); + + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glTranslatef(0.3f, 0.1f, 0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + assertFalse(unitTexIdentity(), "a translate in texture mode must stop reading as identity"); + assertEquals(new Matrix4f().translation(0.3f, 0.1f, 0f), texMatrixScratch(), "the scratch copy must hold the unit-0 matrix once it stops being identity"); + + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + assertTrue(unitTexIdentity(), "loadIdentity after a push must read as identity again"); + + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + assertFalse(unitTexIdentity(), "popping back to the earlier translate must stop reading as identity"); + assertEquals(new Matrix4f().translation(0.3f, 0.1f, 0f), texMatrixScratch(), "pop must restore the memo to the popped matrix"); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glTranslatef(0.5f, 0.5f, 0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + assertFalse(unitTexIdentity(), "a unit-1 operation forces a recompute, but unit 0 itself is unchanged and stays non-identity"); + assertEquals(new Matrix4f().translation(0.3f, 0.1f, 0f), texMatrixScratch(), "the recompute must copy unit 0, not the active unit 1"); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glLoadIdentity(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glTranslatef(0.5f, 0.5f, 0f); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + assertTrue(unitTexIdentity(), "an identity unit 0 must read as identity while a non-identity unit 1 is active"); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } } diff --git a/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java b/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java index a8a12ced2..cbe9be40b 100644 --- a/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java +++ b/src/test/java/net/coderbot/batchedentityrendering/impl/AngelicaBufferSourceTest.java @@ -3,6 +3,7 @@ package net.coderbot.batchedentityrendering.impl; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilderTest.TestLayer; +import org.joml.Vector4f; import org.junit.jupiter.api.Test; import java.util.List; @@ -88,6 +89,14 @@ class AngelicaBufferSourceTest { assertSame(translucent, remaining.get(0)); } + @Test + void packAbgrPacksRedGreenBlueAlpha() { + assertEquals(0xFF0000FF, AngelicaBufferSource.packEntityColor(new Vector4f(1f, 0f, 0f, 1f))); + final int packed = AngelicaBufferSource.packEntityColor(new Vector4f(0f, 0.5f, 0f, 0f)); + assertEquals(0, packed & 0xFF0000FF, "red, blue and alpha bytes must be zero"); + assertTrue((packed & 0x0000FF00) != 0, "green byte must be nonzero"); + } + @Test void declaredLayersAppearInOrderWithoutSegments() { final AngelicaBufferSource source = new AngelicaBufferSource(); diff --git a/src/test/java/net/coderbot/iris/pipeline/CubeInstancingGateTest.java b/src/test/java/net/coderbot/iris/pipeline/CubeInstancingGateTest.java new file mode 100644 index 000000000..e7b33bc4a --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/CubeInstancingGateTest.java @@ -0,0 +1,45 @@ +package net.coderbot.iris.pipeline; + +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CubeInstancingGateTest { + + private final boolean savedBatching = AngelicaConfig.enableEntityBatching; + private final boolean savedCubes = AngelicaConfig.enableCubeInstancing; + + @AfterEach + void restore() { + AngelicaConfig.enableEntityBatching = savedBatching; + AngelicaConfig.enableCubeInstancing = savedCubes; + } + + @Test + void cubeSupportRequiresBothFlags() { + assertTrue(cubeSupport(true, true)); + assertFalse(cubeSupport(true, false)); + assertFalse(cubeSupport(false, true)); + assertFalse(cubeSupport(false, false)); + } + + @Test + void otherKindsIgnoreTheCubeFlags() { + AngelicaConfig.enableEntityBatching = false; + AngelicaConfig.enableCubeInstancing = false; + final boolean[] support = DeferredWorldRenderingPipeline.initialInstancingSupport(); + assertFalse(support[Instancing.NONE.ordinal()]); + assertTrue(support[Instancing.TEMPLATE.ordinal()]); + assertTrue(support[Instancing.PARTICLE.ordinal()]); + } + + private static boolean cubeSupport(boolean batching, boolean cubes) { + AngelicaConfig.enableEntityBatching = batching; + AngelicaConfig.enableCubeInstancing = cubes; + return DeferredWorldRenderingPipeline.initialInstancingSupport()[Instancing.CUBE.ordinal()]; + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/IrisInstancingGLTest.java b/src/test/java/net/coderbot/iris/pipeline/IrisInstancingGLTest.java new file mode 100644 index 000000000..a077e2c9c --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/IrisInstancingGLTest.java @@ -0,0 +1,340 @@ +package net.coderbot.iris.pipeline; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.gbuffer_overrides.matching.ProgramTable; +import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition; +import net.coderbot.iris.gl.shader.GlShader; +import net.coderbot.iris.gl.shader.ProgramCreator; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline.Pass; +import net.coderbot.iris.pipeline.transform.PatchShaderType; +import net.coderbot.iris.pipeline.transform.ShaderTransformer; +import net.coderbot.iris.pipeline.transform.TransformPatcher; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@GLCoreTest +class IrisInstancingGLTest { + + private static final InputAvailability TEX_LM = InputAvailability.of(true, true); + + private static final String CUBE_VERTEX = """ + #version 120 + attribute vec4 mc_Entity; + attribute vec4 at_tangent; + attribute vec4 mc_midTexCoord; + varying vec2 texcoord; + varying vec2 lmcoord; + varying vec4 color; + varying float mats; + varying vec3 nrm; + varying vec3 tang; + varying vec2 midtex; + uniform int entityId; + uniform int blockEntityId; + uniform vec4 entityColor; + void main() { + texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; + lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + color = gl_Color + entityColor + vec4(float(entityId + blockEntityId)); + mats = mc_Entity.x; + nrm = normalize(gl_NormalMatrix * gl_Normal); + tang = normalize(gl_NormalMatrix * at_tangent.xyz) * at_tangent.w; + midtex = mc_midTexCoord.st; + gl_Position = ftransform(); + } + """; + + private static final String CUBE_FRAGMENT = """ + #version 120 + varying vec2 texcoord; + varying vec4 color; + uniform sampler2D tex; + uniform int entityId; + uniform vec4 entityColor; + void main() { + gl_FragData[0] = texture2D(tex, texcoord) * color * entityColor + vec4(float(entityId)); + } + """; + + private static final String TEMPLATE_VERTEX = """ + #version 120 + in ivec4 iris_Entity; + out vec4 entityColor; + uniform int entityId; + varying float mats; + void main() { + entityColor = vec4(1.0); + mats = float(entityId); + gl_Position = ftransform(); + } + """; + + private static final String TEMPLATE_GEOMETRY = """ + #version 150 + layout(triangles) in; + layout(triangle_strip, max_vertices = 3) out; + void main() { + for (int i = 0; i < 3; i++) { + gl_Position = gl_in[i].gl_Position; + EmitVertex(); + } + EndPrimitive(); + } + """; + + private static final String TEMPLATE_FRAGMENT = """ + #version 120 + uniform int entityId; + uniform vec4 entityColor; + void main() { + gl_FragData[0] = entityColor + vec4(float(entityId)); + } + """; + + private static final String PARTICLE_VERTEX = """ + #version 120 + attribute vec4 mc_Entity; + attribute vec2 mc_midTexCoord; + attribute vec4 at_tangent; + varying vec2 texcoord; + varying vec2 lmcoord; + varying vec4 color; + varying float mats; + varying vec2 midtex; + varying vec3 tang; + varying vec3 wpos; + void main() { + texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; + lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + color = gl_Color; + mats = mc_Entity.x; + midtex = mc_midTexCoord.st; + tang = at_tangent.xyz * at_tangent.w; + wpos = (gl_ModelViewMatrixInverse * (gl_ModelViewMatrix * gl_Vertex)).xyz; + gl_Position = ftransform(); + } + """; + + private static final String PARTICLE_FRAGMENT = """ + #version 120 + varying vec2 texcoord; + varying vec2 midtex; + varying vec4 color; + varying vec3 tang; + varying vec3 wpos; + uniform sampler2D tex; + void main() { + gl_FragData[0] = texture2D(tex, texcoord) * color * vec4(midtex, 1.0, 1.0) + vec4(tang + wpos, 0.0); + } + """; + + private static int previousMaxGlslVersion; + + @BeforeAll + static void pinGlslVersion() { + previousMaxGlslVersion = RenderSystem.getMaxGlslVersion(); + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 330); + ShaderTransformer.init(); + } + + @AfterAll + static void restoreGlslVersion() { + Reflect.setStatic(RenderSystem.class, "maxGlslVersion", previousMaxGlslVersion); + ShaderTransformer.init(); + } + + @BeforeEach + void setUp() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + GLStateManager.disableBlend(); + } + + @AfterEach + void tearDown() { + GLSMHooks.pendingProgramSelection = null; + Reflect.setStatic(BatchEligibility.class, "depth", 0); + Reflect.setStatic(BatchEligibility.class, "allowed", false); + Reflect.setStatic(GLStateManager.class, "foreignDrawDepth", 0); + } + + private static DeferredWorldRenderingPipeline newPipeline(WorldRenderingPhase phase, boolean isMainBound) { + final DeferredWorldRenderingPipeline pipeline = Reflect.allocate(DeferredWorldRenderingPipeline.class); + Reflect.set(pipeline, "table", new ProgramTable((condition, availability) -> null)); + Reflect.set(pipeline, "isRenderingWorld", true); + Reflect.set(pipeline, "isMainBound", isMainBound); + Reflect.set(pipeline, "phase", phase); + Reflect.set(pipeline, "pushedPhase", WorldRenderingPhase.NONE); + Reflect.set(pipeline, "inputs", InputAvailability.of(false, false)); + return pipeline; + } + + private static RenderCondition currentCondition(DeferredWorldRenderingPipeline pipeline) { + return Reflect.get(pipeline, "currentCondition"); + } + + @Test + void settersDeferInsideASafeBatchWindowAndResolveWhenItCloses() { + final DeferredWorldRenderingPipeline pipeline = newPipeline(WorldRenderingPhase.ENTITIES, true); + final long dc = GLStateManager.drawCalls; + + BatchEligibility.begin(BatchEligibility.SAFE, dc); + BatchEligibility.begin(BatchEligibility.SAFE, dc); + pipeline.setInputs(InputAvailability.of(true, false)); + assertSame(pipeline, GLSMHooks.pendingProgramSelection, "setInputs must defer inside a SAFE window"); + assertNull(currentCondition(pipeline), "a deferred setter must not match yet"); + + BatchEligibility.end(BatchEligibility.SAFE, dc); + assertSame(pipeline, GLSMHooks.pendingProgramSelection, "a nested end must not resolve the pending match"); + + BatchEligibility.end(BatchEligibility.SAFE, dc); + assertNull(GLSMHooks.pendingProgramSelection, "the outermost end must resolve the pending match"); + assertEquals(RenderCondition.ENTITIES, currentCondition(pipeline)); + } + + @Test + void onModProgramOverrideDropsThePendingMarker() { + final DeferredWorldRenderingPipeline pipeline = newPipeline(WorldRenderingPhase.ENTITIES, true); + GLSMHooks.pendingProgramSelection = pipeline; + + pipeline.onModProgramOverride(); + + assertNull(GLSMHooks.pendingProgramSelection, "a mod program override must clobber the pending match"); + } + + @Test + void foreignDrawOnlyDeferralResolvesAtEndForeignDraw() { + final DeferredWorldRenderingPipeline pipeline = newPipeline(WorldRenderingPhase.ENTITIES, true); + + GLStateManager.beginForeignDraw(); + pipeline.setInputs(InputAvailability.of(true, false)); + assertSame(pipeline, GLSMHooks.pendingProgramSelection, "a foreign draw alone must defer the match"); + + GLStateManager.endForeignDraw(); + assertNull(GLSMHooks.pendingProgramSelection, "endForeignDraw at depth zero must resolve the match"); + } + + @Test + void onEntityRenderBoundaryResolvesBeforeCheckingForAStaleCondition() { + final DeferredWorldRenderingPipeline pipeline = newPipeline(WorldRenderingPhase.ENTITIES, true); + Reflect.set(pipeline, "currentCondition", RenderCondition.ENTITIES); + + final long dc = GLStateManager.drawCalls; + BatchEligibility.begin(BatchEligibility.SAFE, dc); + pipeline.setInputs(InputAvailability.of(true, true)); + assertSame(pipeline, GLSMHooks.pendingProgramSelection); + + pipeline.onEntityRenderBoundary(); + + assertNull(GLSMHooks.pendingProgramSelection, "onEntityRenderBoundary must resolve before the same-enum staleness check skips it"); + + BatchEligibility.end(BatchEligibility.SAFE, dc); + } + + @Test + void rebindCurrentPassResolvesBeforeItsOwnNullPassFallback() { + final DeferredWorldRenderingPipeline pipeline = newPipeline(WorldRenderingPhase.ENTITIES, true); + + final int program = GLStateManager.glCreateProgram(); + GLStateManager.glUseProgram(program); + try { + final long dc = GLStateManager.drawCalls; + BatchEligibility.begin(BatchEligibility.SAFE, dc); + pipeline.setInputs(InputAvailability.of(true, true)); + assertSame(pipeline, GLSMHooks.pendingProgramSelection); + + pipeline.rebindCurrentPass(); + + assertNull(GLSMHooks.pendingProgramSelection, "rebindCurrentPass must resolve the pending match; its null-pass fallback needs no bound program"); + + BatchEligibility.end(BatchEligibility.SAFE, dc); + } finally { + GLStateManager.glUseProgram(0); + GLStateManager.glDeleteProgram(program); + } + } + + @Test + void cubeVariantCompiles() { + final Map result = TransformPatcher.patchAttributesInstanced(CUBE_VERTEX, null, null, null, CUBE_FRAGMENT, TEX_LM, false, Instancing.CUBE); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + final String f = result.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + assertTrue(v.startsWith("#version 330"), () -> "expected a 3.3 core vertex shader:\n" + v); + compile(GL20.GL_VERTEX_SHADER, v); + compile(GL20.GL_FRAGMENT_SHADER, f); + } + + @Test + void particleVariantCompiles() { + final Map result = TransformPatcher.patchAttributesInstanced(PARTICLE_VERTEX, null, null, null, PARTICLE_FRAGMENT, TEX_LM, false, Instancing.PARTICLE); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + assertNotNull(v); + assertTrue(v.startsWith("#version 330"), () -> "expected a 3.3 core vertex shader:\n" + v); + link("particleVariant", result); + } + + @Test + void templateVariantCompilesAndLinksWithGeometryStage() { + final Map result = TransformPatcher.patchAttributesInstanced(TEMPLATE_VERTEX, TEMPLATE_GEOMETRY, null, null, TEMPLATE_FRAGMENT, TEX_LM, false, Instancing.TEMPLATE); + assertNotNull(result); + assertNotNull(result.get(PatchShaderType.GEOMETRY)); + link("templateVariant", result); + } + + private static void link(String name, Map result) { + final String v = result.get(PatchShaderType.VERTEX); + final String g = result.get(PatchShaderType.GEOMETRY); + final String f = result.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + + final GlShader vertex = new GlShader(ShaderType.VERTEX, name + "Vertex", v); + final GlShader geometry = g == null ? null : new GlShader(ShaderType.GEOMETRY, name + "Geometry", g); + final GlShader fragment = new GlShader(ShaderType.FRAGMENT, name + "Fragment", f); + try { + final int program = geometry == null + ? ProgramCreator.create(name, vertex, fragment) + : ProgramCreator.create(name, vertex, geometry, fragment); + GLStateManager.glDeleteProgram(program); + } finally { + vertex.destroy(); + if (geometry != null) { + geometry.destroy(); + } + fragment.destroy(); + } + } + + private static void compile(int type, String source) { + final int shader = GLStateManager.glCreateShader(type); + GLStateManager.glShaderSource(shader, source); + GLStateManager.glCompileShader(shader); + assertEquals(GL11.GL_TRUE, GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS), () -> "shader failed to compile:\n" + GLStateManager.glGetShaderInfoLog(shader, 4096) + "\n" + source); + GLStateManager.glDeleteShader(shader); + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java b/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java index e534d6117..1209676a5 100644 --- a/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java +++ b/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java @@ -1,28 +1,74 @@ package net.coderbot.iris.pipeline.transform; -import static org.junit.jupiter.api.Assertions.assertNull; -import java.util.HashMap; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import net.coderbot.iris.gl.shader.ProgramCreator; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.ffp.CubeInstancedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs; +import com.gtnewhorizons.angelica.glsm.ffp.Instancing; +import com.gtnewhorizons.angelica.glsm.ffp.ParticleInstancedAttribs; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.glsm.testutil.Reflect; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.taumc.glsl.ShaderParser; +import java.util.HashMap; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class AttributeTransformerInstancedTest { - private static final InputAvailability TEX_LM = new InputAvailability(true, true); + private static final Pattern ATTRIBUTE_LOCATION = Pattern.compile("layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*in\\s+\\w+\\s+(\\w+)"); + + private static final InputAvailability TEX_LM = InputAvailability.of(true, true); + + private static final String PARTICLE_VERTEX = """ + #version 120 + attribute vec4 mc_Entity; + varying vec2 texcoord; + varying vec2 lmcoord; + varying vec4 color; + varying float mats; + varying vec3 nrm; + void main() { + texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; + lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + color = gl_Color; + mats = mc_Entity.x; + nrm = normalize(gl_NormalMatrix * gl_Normal); + gl_Position = ftransform(); + } + """; + + private static final String VERTEX_ENTITY_AND_COLOR = """ + #version 120 + uniform int entityId; + uniform vec4 entityColor; + varying vec4 vColor; + void main() { + vColor = entityColor * float(entityId); + gl_Position = ftransform(); + } + """; + + private static final String FRAGMENT_ENTITY_AND_COLOR = """ + #version 120 + uniform int entityId; + uniform vec4 entityColor; + varying vec4 vColor; + void main() { + gl_FragData[0] = vColor + entityColor + vec4(float(entityId)); + } + """; private static final String VERTEX = """ #version 120 @@ -62,6 +108,45 @@ class AttributeTransformerInstancedTest { } """; + private static final String VERTEX_ENTITY = """ + #version 120 + uniform int entityId; + uniform int blockEntityId; + uniform int currentRenderedItemId; + varying float idSum; + void main() { + idSum = float(entityId + blockEntityId + currentRenderedItemId); + gl_Position = ftransform(); + } + """; + + private static final String FRAGMENT_ENTITY = """ + #version 120 + uniform int entityId; + varying float idSum; + void main() { + gl_FragData[0] = vec4(idSum, float(entityId), 0.0, 1.0); + } + """; + + private static final String VERTEX_OVERLAY = """ + #version 120 + uniform vec4 entityColor; + varying vec4 overlay; + void main() { + overlay = entityColor; + gl_Position = ftransform(); + } + """; + + private static final String FRAGMENT_OVERLAY = """ + #version 120 + uniform vec4 entityColor; + void main() { + gl_FragData[0] = entityColor; + } + """; + @BeforeAll static void initShaderTransformer() throws Exception { Reflect.setStatic(RenderSystem.class, "maxGlslVersion", 460); @@ -74,35 +159,24 @@ class AttributeTransformerInstancedTest { ShaderTransformer.clearCache(); } - private static String instancedVertex(String vertex) { - Map result = TransformPatcher.patchAttributesInstanced(vertex, null, null, null, FRAGMENT, TEX_LM, false); - assertNotNull(result); - String v = result.get(PatchShaderType.VERTEX); - assertNotNull(v); - ShaderParser.parseShader(v); - return v; - } - private static String squash(String s) { return s.replaceAll("\\s+", ""); } private static void assertHas(String shader, String snippet) { - assertTrue(squash(shader).contains(squash(snippet)), "expected snippet: " + snippet); + assertTrue(squash(shader).contains(squash(snippet)), "expected snippet: " + snippet + "\nin:\n" + shader); } private static void assertLacks(String shader, String snippet) { - assertFalse(squash(shader).contains(squash(snippet)), "unexpected snippet: " + snippet); + assertFalse(squash(shader).contains(squash(snippet)), "unexpected snippet: " + snippet + "\nin:\n" + shader); } private static int indexOfSquashed(String shader, String snippet) { return squash(shader).indexOf(squash(snippet)); } - @Test - void generatedInstancedShaderHasNoOverlappingAttributeLocations() { - final String v = instancedVertex(VERTEX); - final Matcher m = Pattern.compile("layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*in\\s+\\w+\\s+(\\w+)").matcher(v); + private static Map attributeLocations(String shader) { + final Matcher m = ATTRIBUTE_LOCATION.matcher(shader); final Map byLocation = new HashMap<>(); while (m.find()) { final int loc = Integer.parseInt(m.group(1)); @@ -110,23 +184,99 @@ class AttributeTransformerInstancedTest { final String previous = byLocation.put(loc, name); assertNull(previous, "location " + loc + " declared twice: " + previous + " and " + name); } + return byLocation; + } + + private static int locationOf(Map byLocation, String name) { + for (final Map.Entry e : byLocation.entrySet()) { + if (e.getValue().equals(name)) return e.getKey(); + } + throw new AssertionError("expected " + name + " to be declared at a layout location, found: " + byLocation); + } + + private static String instancedVertex(String vertex) { + return instancedVertex(vertex, Instancing.TEMPLATE); + } + + private static String particleVertex(String vertex) { + return instancedVertex(vertex, Instancing.PARTICLE); + } + + private static String cubeVertex(String vertex) { + return instancedVertex(vertex, Instancing.CUBE); + } + + private static String instancedVertex(String vertex, Instancing instancing) { + Map result = TransformPatcher.patchAttributesInstanced(vertex, null, null, null, FRAGMENT, TEX_LM, false, instancing); + assertNotNull(result); + String v = result.get(PatchShaderType.VERTEX); + assertNotNull(v); + ShaderParser.parseShader(v); + return v; + } + + @Test + void generatedInstancedShaderHasNoOverlappingAttributeLocations() { + final Map byLocation = attributeLocations(instancedVertex(VERTEX)); assertFalse(byLocation.isEmpty(), "expected the instanced variant to declare attribute locations"); } @Test void declaresInstanceAttribsAndGlobalMatrices() { final String v = instancedVertex(VERTEX); - assertHas(v, "layout(location = " + InstancedAttribs.LOC_MATRIX_COL0 + ") in vec4 iris_InstMat0"); - assertHas(v, "layout(location = " + InstancedAttribs.LOC_MATRIX_COL1 + ") in vec4 iris_InstMat1"); - assertHas(v, "layout(location = " + InstancedAttribs.LOC_MATRIX_COL2 + ") in vec4 iris_InstMat2"); - assertHas(v, "layout(location = " + InstancedAttribs.LOC_MATRIX_COL3 + ") in vec4 iris_InstMat3"); + assertHas(v, "layout(location = " + InstancedAttribs.LOC_ROW0 + ") in vec4 iris_InstRow0"); + assertHas(v, "layout(location = " + InstancedAttribs.LOC_ROW1 + ") in vec4 iris_InstRow1"); + assertHas(v, "layout(location = " + InstancedAttribs.LOC_ROW2 + ") in vec4 iris_InstRow2"); assertHas(v, "layout(location = " + InstancedAttribs.LOC_COLOR + ") in vec4 iris_InstColor"); + assertHas(v, "layout(location = " + InstancedAttribs.LOC_OVERLAY + ") in vec4 iris_InstOverlay"); assertHas(v, "layout(location = " + InstancedAttribs.LOC_LIGHTMAP + ") in vec2 iris_InstLightmap"); assertLacks(v, "uniform mat4 iris_ModelViewMatrix;"); assertLacks(v, "uniform mat3 iris_NormalMatrix;"); assertHas(v, "mat4 iris_ModelViewMatrix;"); - assertHas(v, "iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3)"); - assertHas(v, "iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz))"); + assertHas(v, "iris_ModelViewMatrix = mat4(vec4(iris_InstRow0.x, iris_InstRow1.x, iris_InstRow2.x, 0.0), vec4(iris_InstRow0.y, iris_InstRow1.y, iris_InstRow2.y, 0.0), vec4(iris_InstRow0.z, iris_InstRow1.z, iris_InstRow2.z, 0.0), vec4(iris_InstRow0.w, iris_InstRow1.w, iris_InstRow2.w, 1.0))"); + assertHas(v, "iris_NormalMatrix = mat3(normalize(vec3(iris_InstRow0.x, iris_InstRow1.x, iris_InstRow2.x)), normalize(vec3(iris_InstRow0.y, iris_InstRow1.y, iris_InstRow2.y)), normalize(vec3(iris_InstRow0.z, iris_InstRow1.z, iris_InstRow2.z)))"); + } + + @Test + void entityIdsRideTheInstanceAttribute() { + final Map result = TransformPatcher.patchAttributesInstanced(VERTEX_ENTITY, null, null, null, FRAGMENT_ENTITY, TEX_LM, false, Instancing.TEMPLATE); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + final String f = result.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + ShaderParser.parseShader(v); + ShaderParser.parseShader(f); + + assertLacks(v, "uniform int entityId;"); + assertLacks(v, "uniform int blockEntityId;"); + assertLacks(v, "uniform int currentRenderedItemId;"); + assertHas(v, "layout(location = " + InstancedAttribs.LOC_ENTITY + ") in ivec4 iris_Entity;"); + assertHas(v, "flat out ivec3 iris_entityInfo;"); + assertHas(v, "iris_entityInfo = iris_Entity.xyz;"); + + assertLacks(f, "uniform int entityId;"); + assertHas(f, "flat in ivec3 iris_entityInfo;"); + } + + @Test + void entityColorIsAVaryingFromTheOverlaySlot() { + final Map result = TransformPatcher.patchAttributesInstanced(VERTEX_OVERLAY, null, null, null, FRAGMENT_OVERLAY, TEX_LM, false, Instancing.TEMPLATE); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + final String f = result.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + ShaderParser.parseShader(v); + ShaderParser.parseShader(f); + + assertLacks(v, "uniform vec4 entityColor;"); + assertHas(v, "out vec4 entityColor;"); + assertHas(v, "entityColor = iris_InstOverlay;"); + assertHas(v, "entityColor.rgb *= float(entityColor.a != 0.0);"); + + assertLacks(f, "uniform vec4 entityColor;"); + assertHas(f, "in vec4 entityColor;"); } @Test @@ -170,14 +320,136 @@ class AttributeTransformerInstancedTest { assertTrue(bodyUseIdx > assignIdx); } + private static final String VERTEX_TANGENT = """ + #version 120 + attribute vec4 at_tangent; + varying vec3 tang; + void main() { + tang = at_tangent.xyz * at_tangent.w; + gl_Position = ftransform(); + } + """; + + private static final String VERTEX_TANGENT_VEC3 = """ + #version 120 + attribute vec3 at_tangent; + varying vec3 tang; + void main() { + tang = at_tangent; + gl_Position = ftransform(); + } + """; + + @Test + void cubeVariantDeclaresTheCubeNetInsteadOfAUv() { + final String v = cubeVertex(VERTEX); + assertHas(v, "layout(location = 2) in vec4 iris_CubeMid"); + assertHas(v, "layout(location = 3) in vec4 iris_CubeDelta"); + assertHas(v, "layout(location = " + CubeInstancedAttribs.LOC_CUBE_TEX + ") in vec4 iris_CubeTex"); + assertHas(v, "layout(location = " + CubeInstancedAttribs.LOC_LIGHTMAP_SCALE + ") in vec4 iris_InstLightmapScale"); + assertLacks(v, "layout(location = 2) in vec4 iris_MultiTexCoord0"); + assertHas(v, "vec4 iris_MultiTexCoord0;"); + assertHas(v, "iris_MultiTexCoord1 = vec4(iris_InstLightmapScale.xy, 0.0, 1.0)"); + assertLacks(v, "in vec4 mc_midTexCoord"); + + final int uvAssign = indexOfSquashed(v, "iris_MultiTexCoord0 = "); + final int uvUse = indexOfSquashed(v, "iris_TextureMatrix * iris_MultiTexCoord0"); + assertTrue(uvAssign >= 0 && uvUse > uvAssign, "the synthesized uv must be assigned before it is read"); + + final int midAssign = indexOfSquashed(v, "mc_midTexCoord = ("); + final int midUse = indexOfSquashed(v, "mc_midTexCoord.st"); + assertTrue(midAssign >= 0 && midUse > midAssign, "the synthesized mid uv must be assigned before it is read"); + + attributeLocations(v); + } + + @Test + void cubeVariantFeedsTangentFromTheCube() { + final String v = cubeVertex(VERTEX_TANGENT); + assertHas(v, "layout(location = 13) in vec4 iris_CubeTangent"); + assertLacks(v, "in vec4 at_tangent"); + assertLacks(v, "attribute vec4 at_tangent"); + assertHas(v, "vec4 at_tangent;"); + final int assign = indexOfSquashed(v, "at_tangent = (iris_CubeTangent * (1.0 - 2.0 * iris_cubeMirror));"); + final int use = indexOfSquashed(v, "at_tangent.xyz * at_tangent.w"); + assertTrue(assign >= 0, "the cube variant must synthesize at_tangent"); + assertTrue(use > assign, "the synthesized tangent must be assigned before it is read"); + + final String v3 = cubeVertex(VERTEX_TANGENT_VEC3); + assertHas(v3, "vec3 at_tangent;"); + assertHas(v3, "at_tangent = (iris_CubeTangent * (1.0 - 2.0 * iris_cubeMirror)).xyz;"); + } + + @Test + void modesProduceDistinctCacheKeys() { + final InputAvailability avail = TEX_LM; + final AttributeParameters cube = new AttributeParameters(Patch.ATTRIBUTES, false, false, avail, false, Instancing.CUBE); + final AttributeParameters cubeAgain = new AttributeParameters(Patch.ATTRIBUTES, false, false, avail, false, Instancing.CUBE); + final AttributeParameters template = new AttributeParameters(Patch.ATTRIBUTES, false, false, avail, false, Instancing.TEMPLATE); + assertEquals(cube, cubeAgain); + assertFalse(cube.equals(template)); + assertFalse(new AttributeParameters(Patch.ATTRIBUTES, false, false, avail, false, Instancing.NONE).equals(new AttributeParameters(Patch.ATTRIBUTES, false, false, avail, false, Instancing.CUBE))); + } + + @Test + void declaresTheSixParticleAttributesAtTheStatedLocations() { + final String v = particleVertex(PARTICLE_VERTEX); + final Map byLocation = attributeLocations(v); + + assertEquals(VertexFormatElement.Usage.POSITION.getAttributeLocation(), locationOf(byLocation, "iris_ParticleOffset")); + assertEquals(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(), locationOf(byLocation, "iris_ParticleCorner")); + assertEquals(ParticleInstancedAttribs.LOC_CENTER_HALF, locationOf(byLocation, "iris_InstCenterHalf")); + assertEquals(ParticleInstancedAttribs.LOC_UV, locationOf(byLocation, "iris_InstUv")); + assertEquals(InstancedAttribs.LOC_COLOR, locationOf(byLocation, "iris_InstColor")); + assertEquals(InstancedAttribs.LOC_LIGHTMAP, locationOf(byLocation, "iris_InstLightmap")); + + assertFalse(byLocation.containsKey(7), "location 7 is unused"); + for (final int loc : byLocation.keySet()) { + assertTrue(loc < 11, "unexpected attribute location " + loc + " declared for the particle variant"); + } + } + + @Test + void particleColorComposesFrontColorWithoutInstanceOverlay() { + assertHas(particleVertex(PARTICLE_VERTEX), "iris_Color * iris_ColorModulator"); + assertLacks(particleVertex(PARTICLE_VERTEX), "iris_Color * iris_ColorModulator * iris_InstColor"); + } + + @Test + void particleEntityIdAndOverlayColorStayAsPlainUniformsLikeTheNonePath() { + final Map result = TransformPatcher.patchAttributesInstanced(VERTEX_ENTITY_AND_COLOR, null, null, null, FRAGMENT_ENTITY_AND_COLOR, TEX_LM, false, Instancing.PARTICLE); + assertNotNull(result); + final String v = result.get(PatchShaderType.VERTEX); + final String f = result.get(PatchShaderType.FRAGMENT); + assertNotNull(v); + assertNotNull(f); + ShaderParser.parseShader(v); + ShaderParser.parseShader(f); + + assertHas(v, "uniform int entityId;"); + assertHas(v, "uniform vec4 entityColor;"); + assertLacks(v, "iris_entityInfo"); + assertLacks(v, "iris_InstOverlay"); + assertLacks(v, "out vec4 entityColor;"); + + assertHas(f, "uniform int entityId;"); + assertHas(f, "uniform vec4 entityColor;"); + assertLacks(f, "in vec4 entityColor;"); + assertLacks(f, "flat in ivec3 iris_entityInfo;"); + } + @Test void standardPathUnchanged() { - Map result = TransformPatcher.patchAttributes(VERTEX, null, null, null, FRAGMENT, TEX_LM, false); + final Map result = TransformPatcher.patchAttributes(VERTEX, null, null, null, FRAGMENT, TEX_LM, false); assertNotNull(result); final String v = result.get(PatchShaderType.VERTEX); assertHas(v, "uniform mat4 iris_ModelViewMatrix;"); assertHas(v, "layout(location = 3) in vec4 iris_MultiTexCoord1"); assertHas(v, "mc_Entity"); - assertLacks(v, "iris_InstMat0"); + assertLacks(v, "iris_InstRow0"); + + final Map entityResult = TransformPatcher.patchAttributes(VERTEX_ENTITY, null, null, null, FRAGMENT_ENTITY, TEX_LM, false); + assertNotNull(entityResult); + assertHas(entityResult.get(PatchShaderType.VERTEX), "uniform int entityId;"); } }