diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java index 76df251e4..387a05f16 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLContextState.java @@ -262,7 +262,7 @@ public class GLContextState { public int savedFilterMin = -1; public int savedFilterMag = -1; public float savedFilterAniso = -1.0f; - public boolean wideLineEmulationActive = false; + public boolean lineQuadsActive = false; public boolean lineStippleActive = false; public Instancing ffpInstancing = Instancing.NONE; public float lastBrightnessX; 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 f89a00871..0aaba4c95 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -67,6 +67,8 @@ import com.gtnewhorizons.angelica.glsm.states.SamplerUnitArray; import com.gtnewhorizons.angelica.glsm.states.ImageUnitBinding; import com.gtnewhorizons.angelica.glsm.states.TextureBinding; import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; +import com.gtnewhorizons.angelica.glsm.streaming.LineQuads; +import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.glsm.texture.TextureStaging; @@ -524,9 +526,8 @@ public class GLStateManager { // Line width range queried at init from GL_ALIASED_LINE_WIDTH_RANGE static float lineWidthMin = 1.0f; static float lineWidthMax = 1.0f; - /** True when the driver cannot render wide lines natively (Mesa forward-compat). GS emulation handles widths > 1.0. */ + // The driver cannot draw wide lines (Mesa forward-compat, SDL_GPU), so FFP widens them from LineQuads in the vertex shader public static boolean wideLineEmulationEnabled = false; - public static boolean supportsGeometryShaders() { return RENDER_BACKEND.supportsGeometryShaders(); } public static boolean framebufferCompletenessIsMeaningful() { return RENDER_BACKEND.framebufferCompletenessIsMeaningful(); } public static void setFfpInstancing(Instancing mode) { ctx().ffpInstancing = mode; @@ -728,7 +729,7 @@ public class GLStateManager { } wideLineEmulationEnabled = lineWidthMax <= 1.0f; if (wideLineEmulationEnabled) { - LOGGER.info("GL line width: aliased range [{}, {}], probe at {} rejected, native [{}, {}], GS emulation active for [{}, {}]", lineWidthMin, queriedMax, queriedMax, lineWidthMin, lineWidthMax, lineWidthMax, queriedMax); + LOGGER.info("GL line width: aliased range [{}, {}], probe at {} rejected, native [{}, {}], line quads widen ({}, {}]", lineWidthMin, queriedMax, queriedMax, lineWidthMin, lineWidthMax, lineWidthMax, queriedMax); } else { LOGGER.info("GL line width: aliased range [{}, {}], probe at {} accepted, native [{}, {}]", lineWidthMin, queriedMax, queriedMax, lineWidthMin, lineWidthMax); } @@ -2777,6 +2778,10 @@ public class GLStateManager { QuadConverter.drawQuadElementsAsTriangles(glCtx, indices.remaining(), GL11.GL_UNSIGNED_BYTE, indices); return; } + if (widensLineDraw(mode, indices.remaining())) { + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawElementsFromAttribs(mode, indices.remaining(), GL11.GL_UNSIGNED_BYTE, MemoryUtilities.memAddress(indices))); + return; + } preDraw(glCtx, mode); RENDER_BACKEND.drawElements(mode, indices); } finally { @@ -2805,6 +2810,10 @@ public class GLStateManager { QuadConverter.drawQuadElementsAsTriangles(glCtx, indices); return; } + if (widensLineDraw(mode, indices.remaining())) { + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawElementsFromAttribs(mode, indices.remaining(), GL11.GL_UNSIGNED_INT, MemoryUtilities.memAddress(indices))); + return; + } preDraw(glCtx, mode); RENDER_BACKEND.drawElements(mode, indices); } finally { @@ -2833,6 +2842,10 @@ public class GLStateManager { QuadConverter.drawQuadElementsAsTriangles(glCtx, indices); return; } + if (widensLineDraw(mode, indices.remaining())) { + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawElementsFromAttribs(mode, indices.remaining(), GL11.GL_UNSIGNED_SHORT, MemoryUtilities.memAddress(indices))); + return; + } preDraw(glCtx, mode); RENDER_BACKEND.drawElements(mode, indices); } finally { @@ -2861,6 +2874,10 @@ public class GLStateManager { QuadConverter.drawQuadElementsAsTriangles(glCtx, count, type, indices); return; } + if (widensLineDraw(mode, count)) { + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawElementsFromAttribs(mode, count, type, MemoryUtilities.memAddress(indices))); + return; + } preDraw(glCtx, mode); RENDER_BACKEND.drawElements(mode, count, type, indices); } finally { @@ -2891,6 +2908,10 @@ public class GLStateManager { } final boolean locked = acquireDrawLock(); try { + if (widensLineDraw(mode, indices_count)) { + drawLinesAsQuads(glCtx, lineElementsFromBuffer(glCtx, mode, indices_count, type, indices_buffer_offset)); + return; + } final boolean ffpExt = FfpExtendedAttribs.maybeBindIndexed(glCtx, mode, indices_count, type, indices_buffer_offset); try { if (mode == GL11.GL_QUADS) { @@ -2945,6 +2966,7 @@ public class GLStateManager { QuadConverter.drawQuadElementsAsTrianglesInstanced(glCtx, count, type, indices, primcount); return; } + warnIfInstancedWideLines(mode); preDraw(glCtx, mode); RENDER_BACKEND.drawElementsInstanced(mode, count, type, indices, primcount); } finally { @@ -2966,6 +2988,7 @@ public class GLStateManager { preDraw(glCtx, GL11.GL_TRIANGLES); RENDER_BACKEND.drawArraysInstanced(GL11.GL_TRIANGLE_FAN, first, count, primcount); } else { + warnIfInstancedWideLines(mode); preDraw(glCtx, mode); RENDER_BACKEND.drawArraysInstanced(mode, first, count, primcount); } @@ -2978,6 +3001,10 @@ public class GLStateManager { final GLContextState glCtx = ctx(); final boolean locked = acquireDrawLock(); try { + if (widensLineDraw(mode, count)) { + drawLinesAsQuads(glCtx, lineElementsFromBuffer(glCtx, mode, count, type, indices)); + return; + } preDraw(glCtx, mode); RENDER_BACKEND.drawRangeElements(mode, start, end, count, type, indices); } finally { @@ -2993,6 +3020,14 @@ public class GLStateManager { final GLContextState glCtx = ctx(); final boolean locked = acquireDrawLock(); try { + if (LineQuads.isLineMode(mode) && ffpWidensLineQuads()) { + for (int i = firsts.position(); i < firsts.limit(); i++) { + final int count = counts.get(counts.position() + i - firsts.position()); + if (LineQuads.segmentCount(mode, count) == 0) continue; + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawArraysFromAttribs(mode, firsts.get(i), count)); + } + return; + } preDraw(glCtx, mode); RENDER_BACKEND.multiDrawArrays(mode, firsts, counts); } finally { @@ -3039,6 +3074,10 @@ public class GLStateManager { final GLContextState glCtx = ctx(); final boolean locked = acquireDrawLock(); try { + if (widensLineDraw(mode, count)) { + drawLinesAsQuads(glCtx, ImmediateModeRecorder.processDrawArraysFromAttribs(mode, first, count)); + return; + } final boolean ffpExt = FfpExtendedAttribs.maybeBind(glCtx, mode, first, count); try { if (mode == GL11.GL_QUADS) { @@ -6041,10 +6080,55 @@ public class GLStateManager { } } + public static boolean ffpWidensLineQuads() { + final GLContextState glCtx = ctx(); + return wideLineEmulationEnabled && glCtx.activeProgram == 0 && glCtx.lineState.getWidth() > 1.0f + && !DisplayListManager.isRecording(); + } + + private static boolean widensLineDraw(int mode, int count) { + return LineQuads.isLineMode(mode) && LineQuads.segmentCount(mode, count) > 0 && ffpWidensLineQuads(); + } + + private static void drawLinesAsQuads(GLContextState glCtx, DirectTessellator lines) { + if (lines == null) return; + if (readsBufferObject(glCtx.vaos)) { + warnOnce("line-readback", "Wide GL_LINES drawn from a buffer object; widening them reads the buffer back, which waits for the GPU"); + } + final int vao = glCtx.boundVAO; + final int vbo = glCtx.boundVBO; + TessellatorStreamingDrawer.drawDirect(lines); + glBindVertexArray(vao); + glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + } + + private static DirectTessellator lineElementsFromBuffer(GLContextState glCtx, int mode, int count, int type, long offset) { + if (glCtx.vaos.boundEBO == 0) return null; + final ByteBuffer indices = MemoryUtilities.memAlloc(count * GLTypes.sizeBytes(type)); + try { + glGetBufferSubData(GL15.GL_ELEMENT_ARRAY_BUFFER, offset, indices); + return ImmediateModeRecorder.processDrawElementsFromAttribs(mode, count, type, MemoryUtilities.memAddress0(indices)); + } finally { + MemoryUtilities.memFree(indices); + } + } + + private static void warnIfInstancedWideLines(int mode) { + if (LineQuads.isLineMode(mode) && ffpWidensLineQuads()) { + warnOnce("instanced-wide-lines", "Instanced wide GL_LINES are not widened and draw 1 px wide"); + } + } + + private static boolean readsBufferObject(VAOManager vaos) { + for (int i = 0; i < VAOManager.MAX_ATTRIBS; i++) { + final VAOManager.Attrib attrib = vaos.attrib(i); + if (attrib != null && attrib.enabled && attrib.vboId != 0) return true; + } + return false; + } + private static void prepareLineEmulation(GLContextState glCtx, int drawMode) { - final boolean isLine = drawMode == GL11.GL_LINES || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP; - glCtx.wideLineEmulationActive = wideLineEmulationEnabled && RENDER_BACKEND.supportsGeometryShaders() && isLine && glCtx.lineState.getWidth() > 1.0f; - setLineStippleActive(glCtx, isLine && glCtx.lineStippleState.isEnabled()); + setLineStippleActive(glCtx, (LineQuads.isLineMode(drawMode) || glCtx.lineQuadsActive) && glCtx.lineStippleState.isEnabled()); } private static void setLineStippleActive(GLContextState glCtx, boolean active) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java deleted file mode 100644 index 7c41268ce..000000000 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/GeometryShaderGenerator.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.gtnewhorizons.angelica.glsm.ffp; - -/** - * Generates GLSL 330 core geometry shaders for wide line emulation. - */ -public final class GeometryShaderGenerator { - - private GeometryShaderGenerator() {} - - public static String generate(VertexKey key) { - final StringBuilder sb = new StringBuilder(1024); - sb.append("#version 330 core\n\n"); - - sb.append("layout(lines) in;\n"); - sb.append("layout(triangle_strip, max_vertices = 4) out;\n\n"); - - sb.append(FFPUniformBlock.GLSL_DECL); - sb.append('\n'); - - sb.append("// Pass-through varyings\n"); - sb.append("in vec4 v_Color_gs[];\n"); - if (key.separateSpecular()) { - sb.append("in vec3 v_SpecularColor_gs[];\n"); - } - if (key.unitTexCoordEnabled(0) || key.texGenEnabled()) sb.append("in vec4 v_TexCoord0_gs[];\n"); - if (key.lightmapEnabled()) sb.append("in vec4 v_TexCoord1_gs[];\n"); - if (key.unitTexCoordEnabled(2)) sb.append("in vec4 v_TexCoord2_gs[];\n"); - if (key.unitTexCoordEnabled(3)) sb.append("in vec4 v_TexCoord3_gs[];\n"); - if (key.fogEnabled()) { - sb.append("in float v_FogCoord_gs[];\n"); - } - if (key.lineStipple()) { - sb.append("flat in vec2 v_LineStart_gs[];\n"); - } - sb.append('\n'); - - sb.append("out vec4 v_Color;\n"); - if (key.separateSpecular()) { - sb.append("out vec3 v_SpecularColor;\n"); - } - if (key.unitTexCoordEnabled(0) || key.texGenEnabled()) sb.append("out vec4 v_TexCoord0;\n"); - if (key.lightmapEnabled()) sb.append("out vec4 v_TexCoord1;\n"); - if (key.unitTexCoordEnabled(2)) sb.append("out vec4 v_TexCoord2;\n"); - if (key.unitTexCoordEnabled(3)) sb.append("out vec4 v_TexCoord3;\n"); - if (key.fogEnabled()) { - sb.append("out float v_FogCoord;\n"); - } - if (key.lineStipple()) { - sb.append("flat out vec2 v_LineStart;\n"); - } - sb.append('\n'); - - sb.append("void main() {\n"); - sb.append(" vec4 c0 = gl_in[0].gl_Position;\n"); - sb.append(" vec4 c1 = gl_in[1].gl_Position;\n\n"); - - sb.append(" float d0 = c0.z + c0.w;\n"); - sb.append(" float d1 = c1.z + c1.w;\n"); - sb.append(" if (d0 < 0.0 && d1 < 0.0) return;\n"); - sb.append(" float t0 = d0 < 0.0 ? d0 / (d0 - d1) : 0.0;\n"); - sb.append(" float t1 = d1 < 0.0 ? d0 / (d0 - d1) : 1.0;\n"); - sb.append(" vec4 p0 = mix(c0, c1, t0);\n"); - sb.append(" vec4 p1 = mix(c0, c1, t1);\n\n"); - - sb.append(" // NDC positions\n"); - sb.append(" vec2 n0 = p0.xy / p0.w;\n"); - sb.append(" vec2 n1 = p1.xy / p1.w;\n\n"); - - sb.append(" // Screen-space direction and perpendicular\n"); - sb.append(" vec2 dir = normalize((n1 - n0) * u_ViewportSize);\n"); - sb.append(" vec2 offset = vec2(-dir.y, dir.x) * u_LineWidth / u_ViewportSize;\n\n"); - - emitVertex(sb, key, 0, "+offset"); - emitVertex(sb, key, 0, "-offset"); - emitVertex(sb, key, 1, "+offset"); - emitVertex(sb, key, 1, "-offset"); - - sb.append(" EndPrimitive();\n"); - sb.append("}\n"); - - return sb.toString(); - } - - private static void emitVertex(StringBuilder sb, VertexKey key, int endpointIdx, String offsetExpr) { - final String pi = "p" + endpointIdx; - final String ni = "n" + endpointIdx; - final String ti = "t" + endpointIdx; - - sb.append(" // Endpoint ").append(endpointIdx).append(' ').append(offsetExpr).append('\n'); - - sb.append(" v_Color = ").append(lerp("v_Color_gs", ti)).append(";\n"); - if (key.separateSpecular()) { - sb.append(" v_SpecularColor = ").append(lerp("v_SpecularColor_gs", ti)).append(";\n"); - } - if (key.unitTexCoordEnabled(0) || key.texGenEnabled()) sb.append(" v_TexCoord0 = ").append(lerp("v_TexCoord0_gs", ti)).append(";\n"); - if (key.lightmapEnabled()) sb.append(" v_TexCoord1 = ").append(lerp("v_TexCoord1_gs", ti)).append(";\n"); - if (key.unitTexCoordEnabled(2)) sb.append(" v_TexCoord2 = ").append(lerp("v_TexCoord2_gs", ti)).append(";\n"); - if (key.unitTexCoordEnabled(3)) sb.append(" v_TexCoord3 = ").append(lerp("v_TexCoord3_gs", ti)).append(";\n"); - if (key.fogEnabled()) { - sb.append(" v_FogCoord = ").append(lerp("v_FogCoord_gs", ti)).append(";\n"); - } - if (key.lineStipple()) { - sb.append(" v_LineStart = v_LineStart_gs[0];\n"); - } - - if (key.clipPlanesEnabled()) { - for (int i = 0; i < 8; i++) { - sb.append(" gl_ClipDistance[").append(i).append("] = mix(gl_in[0].gl_ClipDistance[").append(i).append("], gl_in[1].gl_ClipDistance[").append(i).append("], ").append(ti).append(");\n"); - } - } - - sb.append(" gl_Position = vec4((").append(ni).append(' ').append(offsetExpr).append(") * ").append(pi).append(".w, ").append(pi).append(".z, ").append(pi).append(".w);\n"); - sb.append(" EmitVertex();\n\n"); - } - - private static String lerp(String input, String t) { - return "mix(" + input + "[0], " + input + "[1], " + t + ")"; - } -} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java index 0d67c94ec..6934717ff 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java @@ -23,7 +23,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; /** - * A compiled and linked FFP emulation program (vertex + fragment + optional geometry shaders). Owns the GL program handle and caches uniform locations. + * A compiled and linked FFP emulation program (vertex + fragment shaders). Owns the GL program handle and caches uniform locations. */ public class Program { @@ -49,23 +49,19 @@ public class Program { } /** - * Compile vertex + fragment + optional geometry shaders, link into a program, and return the FFPProgram. + * Compile vertex + fragment shaders, link into a program, and return the FFPProgram. */ - static Program create(VertexKey vk, FragmentKey fk, String vertSrc, String fragSrc, String geomSrc) { + static Program create(VertexKey vk, FragmentKey fk, String vertSrc, String fragSrc) { final RenderBackend backend = RENDER_BACKEND; final int id = PROGRAM_COUNTER.getAndIncrement(); final String vkHex = Long.toHexString(vk.pack()); - final boolean hasGeom = geomSrc != null; int shaderCount = 0; - final int[] shaders = new int[5]; // vertex, fragment, geometry, tess control, tess evaluation + final int[] shaders = new int[2]; int program = 0; try { shaders[shaderCount++] = compileShader(GL20.GL_VERTEX_SHADER, vertSrc, "ffp_v_" + vkHex); shaders[shaderCount++] = compileShader(GL20.GL_FRAGMENT_SHADER, fragSrc, "ffp_f_" + id); - if (geomSrc != null) { - shaders[shaderCount++] = compileShader(GL32.GL_GEOMETRY_SHADER, geomSrc, "ffp_g_" + id); - } program = backend.createProgram(); for (int i = 0; i < shaderCount; i++) backend.attachShader(program, shaders[i]); @@ -80,7 +76,7 @@ public class Program { throw new RuntimeException("FFP shader link failed (vk=0x" + vkHex + ", fk=" + fk + "): " + log); } - final String debugName = "FFP(v=0x" + vkHex + ",f=" + id + (hasGeom ? ",g" : "") + ")"; + final String debugName = "FFP(v=0x" + vkHex + ",f=" + id + ")"; GLDebug.nameObject(KHRDebug.GL_PROGRAM, program, debugName); // Detach and delete individual shaders - they're linked into the program diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java index 9899fa82d..e331db02e 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java @@ -32,7 +32,6 @@ public class ShaderCache { private static final long EMPTY_MARKER = 0L; // slot [1] == 0 means empty (fkLen >= 1 guarantees nonzero) private final Long2ObjectOpenHashMap vertexSourceCache = new Long2ObjectOpenHashMap<>(); - private final Long2ObjectOpenHashMap geometrySourceCache = new Long2ObjectOpenHashMap<>(); // Open-addressed table — parallel arrays private long[] keys; @@ -103,7 +102,6 @@ public class ShaderCache { final FragmentKey fk = FragmentKey.fromPacked(fkPacked, fkLen); final String vertSrc; String fragSrc; - final String geomSrc; final Program program; if (Tracy.ENABLED) Tracy.beginZone(Z_FFP_SHADER_GEN); try { @@ -113,8 +111,7 @@ public class ShaderCache { fragSrc = FragmentShaderGenerator.generate(fk); uniqueFragCount++; } - geomSrc = vk.wideLineEmulation() ? getOrGenerateGeometry(vk) : null; - program = Program.create(vk, fk, vertSrc, fragSrc, geomSrc); + program = Program.create(vk, fk, vertSrc, fragSrc); } finally { if (Tracy.ENABLED) Tracy.endZone(); } @@ -135,9 +132,6 @@ public class ShaderCache { if (dumpDir != null) { dumpShader(Long.toHexString(vkPacked), ".vert.glsl", vertSrc); dumpShader("frag_" + fragmentDumpCounter++, ".frag.glsl", fragSrc); - if (geomSrc != null) { - dumpShader(Long.toHexString(vkPacked), ".geom.glsl", geomSrc); - } } return program; @@ -228,10 +222,6 @@ public class ShaderCache { return vertexSourceCache.computeIfAbsent(vk.pack(), k -> VertexShaderGenerator.generate(vk)); } - private String getOrGenerateGeometry(VertexKey vk) { - return geometrySourceCache.computeIfAbsent(vk.pack(), k -> GeometryShaderGenerator.generate(vk)); - } - private void dumpShader(String name, String suffix, String source) { if (dumpDir == null) return; try { @@ -260,11 +250,8 @@ public class ShaderCache { dumpShader("frag_" + idx, ".frag.glsl", fragSources[i]); } } - for (var entry : geometrySourceCache.entrySet()) { - dumpShader(Long.toHexString(entry.getKey()), ".geom.glsl", entry.getValue()); - } - GLStateManager.LOGGER.info("Dumped {} vertex, {} geometry, and {} fragment FFP shader sources to {}", - vertexSourceCache.size(), geometrySourceCache.size(), seen.size(), outputDir); + GLStateManager.LOGGER.info("Dumped {} vertex and {} fragment FFP shader sources to {}", + vertexSourceCache.size(), seen.size(), outputDir); } catch (IOException e) { GLStateManager.LOGGER.warn("Failed to dump FFP shaders: {}", e.getMessage()); } 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 a5b43b1a0..f41b9cbe1 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 @@ -100,7 +100,6 @@ public final class ShaderManager { 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 }; for (Class c : touched) { c.getName(); 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 a5266f64b..6e0c6c0d4 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 @@ -46,8 +46,8 @@ public final class VertexKey { private static final int BIT_TEXGEN_R = BIT_TEXGEN_T + 3; private static final int BIT_TEXGEN_Q = BIT_TEXGEN_R + 3; private static final int BIT_CLIP_PLANES = BIT_TEXGEN_Q + 3; - private static final int BIT_WIDE_LINE = BIT_CLIP_PLANES + 1; - private static final int BIT_UNIT_TEXMAT_BASE = BIT_WIDE_LINE + 1; + private static final int BIT_LINE_QUADS = BIT_CLIP_PLANES + 1; + private static final int BIT_UNIT_TEXMAT_BASE = BIT_LINE_QUADS + 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_INSTANCING = BIT_LINE_STIPPLE + 1; @@ -103,8 +103,8 @@ public final class VertexKey { public int texGenModeQ() { return (int)((packed >> BIT_TEXGEN_Q) & 0x7); } public boolean texGenEnabled() { return texGenModeS() != TG_NONE || texGenModeT() != TG_NONE || texGenModeR() != TG_NONE || texGenModeQ() != TG_NONE; } 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 lineQuads() { return bit(BIT_LINE_QUADS); } public Instancing instancing() { return Instancing.VALUES[(int) ((packed >> BIT_INSTANCING) & INSTANCING_MASK)]; } public boolean cmReplacesAmbient() { final int m = colorMaterialMode(); return m == CM_AMBIENT || m == CM_AMBIENT_AND_DIFFUSE; } @@ -226,7 +226,7 @@ public final class VertexKey { // Vertex format flags if (hasColor) bits |= (1L << BIT_HAS_VERTEX_COLOR); - if (hasNormal) bits |= (1L << BIT_HAS_VERTEX_NORMAL); + if (hasNormal && !glCtx.lineQuadsActive) bits |= (1L << BIT_HAS_VERTEX_NORMAL); if (hasTexCoord) bits |= (1L << BIT_HAS_VERTEX_TEX); if (hasLightmap) bits |= (1L << BIT_HAS_VERTEX_LIGHTMAP); @@ -238,14 +238,14 @@ public final class VertexKey { bits |= (1L << BIT_CLIP_PLANES); } - if (glCtx.wideLineEmulationActive) { - bits |= (1L << BIT_WIDE_LINE); - } - if (glCtx.lineStippleActive) { bits |= (1L << BIT_LINE_STIPPLE); } + if (glCtx.lineQuadsActive) { + bits |= (1L << BIT_LINE_QUADS); + } + bits |= (long) glCtx.ffpInstancing.ordinal() << BIT_INSTANCING; return bits; @@ -277,6 +277,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=%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()); + return String.format("FFPVertexKey[0x%012X: 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 lquads=%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(), lineQuads(), 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 bd3ce9604..a1e4d2495 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 @@ -34,28 +34,16 @@ public final class VertexShaderGenerator { } emitTexCoordPassthrough(sb, key); if (key.lineStipple()) { - emitLineStart(sb); + emitLineStart(sb, key.lineQuads() ? "lineCenter" : "gl_Position"); } if (key.fogEnabled()) { emitFogDistance(sb, key); } if (key.clipPlanesEnabled()) { - emitClipDistances(sb); + emitClipDistances(sb, key); } sb.append("}\n"); - - String source = sb.toString(); - if (key.wideLineEmulation()) { - source = source.replace("v_SpecularColor", "v_SpecularColor_gs") - .replace("v_TexCoord0", "v_TexCoord0_gs") - .replace("v_TexCoord1", "v_TexCoord1_gs") - .replace("v_TexCoord2", "v_TexCoord2_gs") - .replace("v_TexCoord3", "v_TexCoord3_gs") - .replace("v_FogCoord", "v_FogCoord_gs") - .replace("v_LineStart", "v_LineStart_gs") - .replace("v_Color", "v_Color_gs"); - } - return source; + return sb.toString(); } private static void emitAttributes(StringBuilder sb, VertexKey key) { @@ -78,6 +66,8 @@ public final class VertexShaderGenerator { } if (key.hasVertexNormal() || kind == Instancing.CUBE) { sb.append("layout(location = ").append(VertexFormatElement.Usage.NORMAL.getAttributeLocation()).append(") in vec3 a_Normal;\n"); + } else if (key.lineQuads()) { + sb.append("layout(location = ").append(VertexFormatElement.Usage.NORMAL.getAttributeLocation()).append(") in vec3 a_LineOtherEnd;\n"); } } for (String d : InstancedGlslHelpers.attributeDecls("a_", kind)) { @@ -97,8 +87,8 @@ public final class VertexShaderGenerator { }; } - private static void emitLineStart(StringBuilder sb) { - sb.append(" vec2 ndc = gl_Position.xy / gl_Position.w;\n"); + private static void emitLineStart(StringBuilder sb, String clipPosition) { + sb.append(" vec2 ndc = ").append(clipPosition).append(".xy / ").append(clipPosition).append(".w;\n"); sb.append(" v_LineStart = u_Viewport.xy + (ndc * 0.5 + 0.5) * u_Viewport.zw;\n\n"); } @@ -151,15 +141,59 @@ public final class VertexShaderGenerator { sb.append(" v_Overlay = a_InstOverlay;\n"); } else { sb.append(" gl_Position = u_MVPMatrix * pos4;\n"); + if (key.lineQuads()) { + emitLineQuadWidening(sb); + } // Eye position needed for lighting, fog, EYE_LINEAR texgen, and clip planes if (key.lightingEnabled() || key.fogEnabled() || texGenNeedsEyePos(key) || key.clipPlanesEnabled()) { sb.append(" vec4 eyePos = u_ModelViewMatrix * pos4;\n"); } + if (key.lineQuads() && (key.fogEnabled() || key.clipPlanesEnabled())) { + sb.append(" vec4 lineEyeOther = u_ModelViewMatrix * vec4(a_LineOtherEnd, 1.0);\n"); + } } sb.append('\n'); } + private static void emitLineQuadWidening(StringBuilder sb) { + sb.append(" int lineCorner = gl_VertexID % 6;\n"); + sb.append(" bool lineStart = lineCorner == 0 || lineCorner == 1 || lineCorner == 3;\n"); + sb.append(" vec4 lineOther = u_MVPMatrix * vec4(a_LineOtherEnd, 1.0);\n"); + sb.append(" vec4 lineC0 = lineStart ? gl_Position : lineOther;\n"); + sb.append(" vec4 lineC1 = lineStart ? lineOther : gl_Position;\n"); + sb.append(" vec4 lineCenter = lineC0;\n"); + sb.append(" float lineT = 0.0;\n"); + sb.append(" float lineD0 = lineC0.z + lineC0.w;\n"); + sb.append(" float lineD1 = lineC1.z + lineC1.w;\n"); + sb.append(" if (lineD0 < 0.0 && lineD1 < 0.0) {\n"); + sb.append(" gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n"); + sb.append(" } else {\n"); + sb.append(" float lineT0 = lineD0 < 0.0 ? lineD0 / (lineD0 - lineD1) : 0.0;\n"); + sb.append(" float lineT1 = lineD1 < 0.0 ? lineD0 / (lineD0 - lineD1) : 1.0;\n"); + sb.append(" lineT = lineStart ? lineT0 : lineT1;\n"); + sb.append(" vec4 lineP0 = mix(lineC0, lineC1, lineT0);\n"); + sb.append(" vec4 lineP1 = mix(lineC0, lineC1, lineT1);\n"); + sb.append(" vec2 lineN0 = lineP0.xy / lineP0.w;\n"); + sb.append(" vec2 lineN1 = lineP1.xy / lineP1.w;\n"); + sb.append(" vec2 linePixel = 2.0 / u_ViewportSize;\n"); + sb.append(" float lineHalfWidth = 0.5 * u_LineWidth;\n"); + sb.append(" vec2 lineOffset;\n"); + sb.append(" vec2 lineShift;\n"); + sb.append(" vec2 lineSpan = abs(lineN1 - lineN0) * u_ViewportSize;\n"); + sb.append(" if (lineSpan.x > lineSpan.y) {\n"); + sb.append(" lineOffset = vec2(0.0, lineHalfWidth * linePixel.y);\n"); + sb.append(" lineShift = vec2(lineN0.x < lineN1.x ? -0.5 : 0.5, -0.125) * linePixel;\n"); + sb.append(" } else {\n"); + sb.append(" lineOffset = vec2(lineHalfWidth * linePixel.x, 0.0);\n"); + sb.append(" lineShift = vec2(0.125, lineN0.y < lineN1.y ? -0.5 : 0.5) * linePixel;\n"); + sb.append(" }\n"); + sb.append(" vec4 lineP = lineStart ? lineP0 : lineP1;\n"); + sb.append(" vec2 lineN = lineStart ? lineN0 : lineN1;\n"); + sb.append(" gl_Position = vec4((lineN + (lineCorner % 2 == 0 ? lineOffset : -lineOffset) + lineShift) * lineP.w, lineP.z, lineP.w);\n"); + sb.append(" }\n"); + } + private static void emitNormalTransform(StringBuilder sb, VertexKey key) { sb.append(" // Normal transform\n"); final String srcNormal = key.hasVertexNormal() && key.instancing() != Instancing.PARTICLE ? "a_Normal" : "u_CurrentNormal"; @@ -380,24 +414,30 @@ public final class VertexShaderGenerator { private static void emitFogDistance(StringBuilder sb, VertexKey key) { sb.append(" // Fog distance\n"); - // Mesa ffvertex_prog.c build_fog(): FDM_EYE_RADIAL/EYE_PLANE/EYE_PLANE_ABS - final int fogDistMode = key.fogDistanceMode(); - switch (fogDistMode) { - case 0 -> // FDM_EYE_RADIAL: Euclidean distance - sb.append(" v_FogCoord = length(eyePos.xyz);\n"); - case 1 -> // FDM_EYE_PLANE: raw Z (can be negative, clamped by fog factor) - sb.append(" v_FogCoord = eyePos.z;\n"); - case 2 -> // FDM_EYE_PLANE_ABS: absolute Z - sb.append(" v_FogCoord = abs(eyePos.z);\n"); - default -> - sb.append(" v_FogCoord = abs(eyePos.z);\n"); + final String own = fogDistance(key, "eyePos"); + final String fog = key.lineQuads() ? acrossLine(own, fogDistance(key, "lineEyeOther")) : own; + sb.append(" v_FogCoord = ").append(fog).append(";\n"); + } + + // Mesa ffvertex_prog.c build_fog(): FDM_EYE_RADIAL/EYE_PLANE/EYE_PLANE_ABS + private static String fogDistance(VertexKey key, String eye) { + return switch (key.fogDistanceMode()) { + case 0 -> "length(" + eye + ".xyz)"; // FDM_EYE_RADIAL: Euclidean distance + case 1 -> eye + ".z"; // FDM_EYE_PLANE: raw Z (can be negative, clamped by fog factor) + default -> "abs(" + eye + ".z)"; // FDM_EYE_PLANE_ABS: absolute Z + }; + } + + private static void emitClipDistances(StringBuilder sb, VertexKey key) { + sb.append(" // Clip distances\n"); + for (int i = 0; i < 8; i++) { + final String own = "dot(u_ClipPlane[" + i + "], eyePos)"; + final String distance = key.lineQuads() ? acrossLine(own, "dot(u_ClipPlane[" + i + "], lineEyeOther)") : own; + sb.append(" gl_ClipDistance[").append(i).append("] = ").append(distance).append(";\n"); } } - private static void emitClipDistances(StringBuilder sb) { - sb.append(" // Clip distances\n"); - for (int i = 0; i < 8; i++) { - sb.append(" gl_ClipDistance[").append(i).append("] = dot(u_ClipPlane[").append(i).append("], eyePos);\n"); - } + private static String acrossLine(String own, String other) { + return "mix(lineStart ? " + own + " : " + other + ", lineStart ? " + other + " : " + own + ", lineT)"; } } 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 48f44ca70..94689f0d3 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 @@ -11,6 +11,7 @@ public final class GLSMHooks { public static DeferredDepthColorHandler depthColorHandler; public static GlintColorHandler glintColorHandler; public static ImmediateExtendedAttribHandler immediateExtendedHandler; + public static LineDrawHandler lineDrawHandler; public static ShaderTransformPostProcessor postTransformProcessor; public static PerFrameUniformBlock perFrameUniformBlock; public static PerFrameUniformBlock perPassUniformBlock; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/LineDrawHandler.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/LineDrawHandler.java new file mode 100644 index 000000000..17f58d8de --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/LineDrawHandler.java @@ -0,0 +1,8 @@ +package com.gtnewhorizons.angelica.glsm.hooks; + +public interface LineDrawHandler { + + boolean bindLineProgram(); + + void restoreProgram(); +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java index f4dd54644..193ab7320 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java @@ -1,8 +1,11 @@ package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; +import com.gtnewhorizons.angelica.glsm.GLContextState; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import com.gtnewhorizons.angelica.glsm.streaming.LineQuads; +import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; @@ -55,9 +58,20 @@ public final class DisplayListVBO { private final int count; private final int vertexFlags; private int pendingExtVbo = 0; + private IVertexArrayObject lineQuads; + private int lineQuadStart; + private int lineQuadCount; + private int lineQuadFlags; void setPendingExtVbo(int extVbo) { this.pendingExtVbo = extVbo; } + void setLineQuads(IVertexArrayObject quads, int start, int count, int flags) { + this.lineQuads = quads; + this.lineQuadStart = start; + this.lineQuadCount = count; + this.lineQuadFlags = flags; + } + public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count, int vertexFlags) { this.vao = vao; this.drawMode = drawMode; @@ -80,10 +94,15 @@ public final class DisplayListVBO { public void delete() { vao.delete(); + if (lineQuads != null) lineQuads.delete(); } public void render() { if (vao == null) return; + if (lineQuads != null && GLStateManager.ffpWidensLineQuads()) { + renderLineQuads(); + return; + } vao.bind(); if (pendingExtVbo != 0) { GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, pendingExtVbo); @@ -102,6 +121,22 @@ public final class DisplayListVBO { vao.unbind(); } + private void renderLineQuads() { + final GLContextState glCtx = GLStateManager.ctx(); + lineQuads.bind(); + VAOManager.setCurrentVertexFlags(lineQuadFlags); + final boolean culled = LineQuads.disableCulling(); + glCtx.lineQuadsActive = true; + FfpExtendedAttribs.beginInternalDraw(); + try { + lineQuads.draw(GL11.GL_TRIANGLES, lineQuadStart, lineQuadCount); + } finally { + FfpExtendedAttribs.endInternalDraw(); + glCtx.lineQuadsActive = false; + LineQuads.restoreCulling(culled); + } + lineQuads.unbind(); + } public IVertexArrayObject getVAO() { return vao; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java index f9830e2fb..e80c6c0e5 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java @@ -13,6 +13,7 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import com.gtnewhorizons.angelica.glsm.streaming.LineQuads; import it.unimi.dsi.fastutil.ints.IntArrayList; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; @@ -78,6 +79,8 @@ public final class DisplayListVBOBuilder { final IntArrayList extStarts = wantExt ? new IntArrayList() : null; final IntArrayList extCounts = wantExt ? new IntArrayList() : null; final IntArrayList extPrims = wantExt ? new IntArrayList() : null; + // drawIndex, start, vertexCount, drawMode for each line draw + final IntArrayList lineDraws = GLStateManager.wideLineEmulationEnabled ? new IntArrayList() : null; for (FormatData data : formatData) { int vertexCount; @@ -123,6 +126,12 @@ public final class DisplayListVBOBuilder { vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, GL11.GL_TRIANGLE_FAN, start, vertexCount, flags); } else { vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount, flags); + if (lineDraws != null && LineQuads.segmentCount(data.drawMode, vertexCount) > 0) { + lineDraws.add(data.drawIndex); + lineDraws.add(start); + lineDraws.add(vertexCount); + lineDraws.add(data.drawMode); + } } @@ -130,6 +139,9 @@ public final class DisplayListVBOBuilder { } ByteBuffer bigBuffer = mergeAndDelete(allBuffers); vbo.allocate(bigBuffer, start); + if (lineDraws != null && !lineDraws.isEmpty()) { + attachLineQuads(vbos, format, bigBuffer, lineDraws); + } if (wantExt && !extDrawIndexes.isEmpty()) { final int extVbo = buildExt(extHandler, format, bigBuffer, extStarts, extCounts, extPrims); @@ -148,6 +160,34 @@ public final class DisplayListVBOBuilder { return new DisplayListVBO(vbos, extVbos.toIntArray()); } + // The line width is only known at playback, so lines keep their own draw and also get quads to widen + private static void attachLineQuads(DisplayListVBO.SubVBO[] vbos, VertexFormat format, ByteBuffer vertices, IntArrayList lineDraws) { + final VertexFormat quadFormat = LineQuads.quadFormat(format); + final int quadSize = quadFormat.getVertexSize(); + int quadVertices = 0; + for (int i = 0; i < lineDraws.size(); i += 4) { + quadVertices += LineQuads.segmentCount(lineDraws.getInt(i + 3), lineDraws.getInt(i + 2)) * LineQuads.VERTICES_PER_SEGMENT; + } + + final ByteBuffer quads = memAlloc(quadVertices * quadSize); + final long src = memAddress0(vertices); + final long dst = memAddress0(quads); + final int stride = format.getVertexSize(); + final IVertexArrayObject quadVao = VAOManager.createStorageVAO(quadFormat, -1, 0); + int quadStart = 0; + for (int i = 0; i < lineDraws.size(); i += 4) { + final int start = lineDraws.getInt(i + 1); + final int count = lineDraws.getInt(i + 2); + final int mode = lineDraws.getInt(i + 3); + final int corners = LineQuads.segmentCount(mode, count) * LineQuads.VERTICES_PER_SEGMENT; + LineQuads.expandWithOtherEnd(src + (long) start * stride, format, mode, count, dst + (long) quadStart * quadSize); + vbos[lineDraws.getInt(i)].setLineQuads(quadVao, quadStart, corners, quadFormat.getVertexFlags()); + quadStart += corners; + } + quadVao.getVBO().allocate(quads, quadVertices); + memFree(quads); + } + private static int buildExt(ImmediateExtendedAttribHandler handler, VertexFormat format, ByteBuffer bigBuffer, IntArrayList extStarts, IntArrayList extCounts, IntArrayList extPrims) { final int extStride = ImmediateExtendedAttribHandler.EXT_STRIDE; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java index 703b570c0..3d6c36ddf 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java @@ -5,6 +5,8 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Usage; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.GLTypes; +import com.gtnewhorizons.angelica.glsm.QuadConverter; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; import org.lwjgl.opengl.GL11; @@ -13,6 +15,10 @@ import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetByte; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetShort; + /** * Records immediate mode GL calls (glBegin/glEnd/glVertex) via {@link DirectTessellator}. * Used both during display list compilation and for live immediate mode emulation in core profile. @@ -213,6 +219,34 @@ public final class ImmediateModeRecorder { } } + public static DirectTessellator processDrawElementsFromAttribs(int mode, int count, int indexType, long indices) { + final long minMax = QuadConverter.scanMinMaxIndex(indices, indexType, count); + if (minMax == -1L) return null; + final int minVertex = (int) (minMax & 0xFFFFFFFFL); + final int maxVertex = (int) (minMax >>> 32); + final AttribSnapshot snap = AttribSnapshot.snapshot(minVertex, maxVertex - minVertex + 1); + if (snap == null) return null; + try { + prepareReaders(snap); + if (positionReaderIndex < 0) return null; + begin(mode); + final DirectTessellator t = tessellator(); + final int indexSize = GLTypes.sizeBytes(indexType); + for (int i = 0; i < count; i++) { + final long at = indices + (long) i * indexSize; + final int vertex = switch (indexType) { + case GL11.GL_UNSIGNED_BYTE -> memGetByte(at) & 0xFF; + case GL11.GL_UNSIGNED_SHORT -> memGetShort(at) & 0xFFFF; + default -> memGetInt(at); + }; + readVertexFromBuffer(t, vertex); + } + return end(); + } finally { + snap.free(); + } + } + private static void prepareReaders(AttribSnapshot snap) { nonPositionCount = 0; positionReaderIndex = -1; diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuads.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuads.java new file mode 100644 index 000000000..bdfc55757 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuads.java @@ -0,0 +1,154 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopy; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; + +/** + * Rewrites line primitives as quads for shaders that widen lines in the vertex stage. + */ +public final class LineQuads { + + public static final int VERTICES_PER_SEGMENT = 6; + + private static final VertexFormatElement NORMAL_SLOT = new VertexFormatElement(0, VertexFormatElement.Type.FLOAT, + VertexFormatElement.Usage.NORMAL, 3, VertexFlags.NORMAL_BIT, DefaultVertexFormat.NORMAL_ELEMENT.getWriter()); + + private static final VertexFormat[] QUAD_FORMATS = new VertexFormat[VertexFlags.BITSET_SIZE]; + private static final int[][] SOURCE_OFFSETS = new int[VertexFlags.BITSET_SIZE][]; + + static { + for (int flags = 0; flags < QUAD_FORMATS.length; flags++) { + if ((flags & VertexFlags.NORMAL_BIT) == 0) continue; + final VertexFormatElement[] elements = DefaultVertexFormat.ALL_FORMATS[flags].elementsArray.clone(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] == DefaultVertexFormat.NORMAL_ELEMENT) elements[i] = NORMAL_SLOT; + } + QUAD_FORMATS[flags] = new VertexFormat(elements); + } + for (int flags = 0; flags < SOURCE_OFFSETS.length; flags++) { + final VertexFormatElement[] quadElements = QUAD_FORMATS[flags | VertexFlags.NORMAL_BIT].elementsArray; + final int[] offsets = new int[quadElements.length]; + for (int i = 0; i < quadElements.length; i++) { + offsets[i] = offsetOf(DefaultVertexFormat.ALL_FORMATS[flags], quadElements[i]); + } + SOURCE_OFFSETS[flags] = offsets; + } + } + + private LineQuads() {} + + public static boolean isLineMode(int drawMode) { + return drawMode == GL11.GL_LINES || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP; + } + + public static int segmentCount(int drawMode, int vertexCount) { + return switch (drawMode) { + case GL11.GL_LINES -> vertexCount / 2; + case GL11.GL_LINE_STRIP -> Math.max(0, vertexCount - 1); + case GL11.GL_LINE_LOOP -> vertexCount < 2 ? 0 : vertexCount; + default -> 0; + }; + } + + public static boolean disableCulling() { + final boolean wasEnabled = GLStateManager.getCullState().isEnabled(); + if (wasEnabled) { + GLStateManager.disableCull(); + } + return wasEnabled; + } + + public static void restoreCulling(boolean wasEnabled) { + if (wasEnabled) { + GLStateManager.enableCull(); + } + } + + public static VertexFormat quadFormat(VertexFormat lineFormat) { + return QUAD_FORMATS[lineFormat.getVertexFlags() | VertexFlags.NORMAL_BIT]; + } + + public static boolean isQuadFormat(VertexFormat format) { + return QUAD_FORMATS[format.getVertexFlags()] == format; + } + + public static void expandWithDirection(long src, VertexFormat srcFormat, int drawMode, int vertexCount, long dst) { + expand(src, srcFormat, drawMode, vertexCount, dst, false); + } + + public static void expandWithOtherEnd(long src, VertexFormat srcFormat, int drawMode, int vertexCount, long dst) { + expand(src, srcFormat, drawMode, vertexCount, dst, true); + } + + private static void expand(long src, VertexFormat srcFormat, int drawMode, int vertexCount, long dst, boolean otherEnd) { + final VertexFormatElement[] dstElements = quadFormat(srcFormat).elementsArray; + final int[] srcOffsets = SOURCE_OFFSETS[srcFormat.getVertexFlags()]; + final int srcStride = srcFormat.getVertexSize(); + final int segments = segmentCount(drawMode, vertexCount); + long out = dst; + for (int s = 0; s < segments; s++) { + final int a = drawMode == GL11.GL_LINES ? s * 2 : s; + final int b = drawMode == GL11.GL_LINE_LOOP && s == vertexCount - 1 ? 0 : a + 1; + final long srcA = src + (long) a * srcStride; + final long srcB = src + (long) b * srcStride; + // What A's and B's corners carry in the normal slot + final float ax, ay, az, bx, by, bz; + if (otherEnd) { + ax = memGetFloat(srcB); ay = memGetFloat(srcB + 4); az = memGetFloat(srcB + 8); + bx = memGetFloat(srcA); by = memGetFloat(srcA + 4); bz = memGetFloat(srcA + 8); + } else { + final float x = memGetFloat(srcB) - memGetFloat(srcA); + final float y = memGetFloat(srcB + 4) - memGetFloat(srcA + 4); + final float z = memGetFloat(srcB + 8) - memGetFloat(srcA + 8); + final float lengthSquared = x * x + y * y + z * z; + final float scale = lengthSquared == 0.0f ? 0.0f : 1.0f / (float) Math.sqrt(lengthSquared); + ax = bx = x * scale; + ay = by = y * scale; + az = bz = z * scale; + } + + out = writeVertex(srcA, out, dstElements, srcOffsets, ax, ay, az); + out = writeVertex(srcA, out, dstElements, srcOffsets, ax, ay, az); + out = writeVertex(srcB, out, dstElements, srcOffsets, bx, by, bz); + out = writeVertex(srcA, out, dstElements, srcOffsets, ax, ay, az); + out = writeVertex(srcB, out, dstElements, srcOffsets, bx, by, bz); + out = writeVertex(srcB, out, dstElements, srcOffsets, bx, by, bz); + } + } + + private static long writeVertex(long src, long dst, VertexFormatElement[] dstElements, int[] srcOffsets, float x, float y, float z) { + long out = dst; + for (int i = 0; i < dstElements.length; i++) { + final VertexFormatElement element = dstElements[i]; + final int size = element.getByteSize(); + if (element == NORMAL_SLOT) { + memPutFloat(out, x); + memPutFloat(out + 4, y); + memPutFloat(out + 8, z); + } else { + memCopy(src + srcOffsets[i], out, size); + } + out += size; + } + return out; + } + + private static int offsetOf(VertexFormat format, VertexFormatElement element) { + int offset = 0; + for (VertexFormatElement candidate : format.elementsArray) { + if (candidate == element) { + return offset; + } + offset += candidate.getByteSize(); + } + return -1; + } +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingVaos.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingVaos.java index 951c88b6c..2e8c2b53d 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingVaos.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/StreamingVaos.java @@ -10,4 +10,7 @@ public final class StreamingVaos { final int[] extendedPersistentVAOs = new int[FORMAT_COUNT]; final int[] extendedOrphanVAOs = new int[FORMAT_COUNT]; + + final int[] lineQuadPersistentVAOs = new int[FORMAT_COUNT]; + final int[] lineQuadOrphanVAOs = new int[FORMAT_COUNT]; } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java index c195d7eca..07270ce76 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/streaming/TessellatorStreamingDrawer.java @@ -15,6 +15,7 @@ import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler; +import com.gtnewhorizons.angelica.glsm.hooks.LineDrawHandler; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import net.minecraft.client.renderer.Tessellator; import org.apache.logging.log4j.LogManager; @@ -56,6 +57,10 @@ public class TessellatorStreamingDrawer { private static long repackAddress; private static int repackCapacity; + private static ByteBuffer lineQuadBuffer; + private static long lineQuadAddress; + private static int lineQuadCapacity; + private static boolean initialized = false; // Tracy profiling counters @@ -315,12 +320,18 @@ public class TessellatorStreamingDrawer { * Tries the persistent ring buffer first, falls back to orphan buffer on overflow. */ private static void uploadAndDraw(ByteBuffer packed, int flags, VertexFormat format, int vertexSize, int drawMode, int vertexCount) { + if (LineQuads.isLineMode(drawMode) && drawLinesAsQuads(packed, format, drawMode, vertexCount)) { + return; + } Tracy.beginZone(Z_SDL_STREAM_DRAW); final boolean locked = GLStateManager.acquireDrawLock(); try { final GLContextState glCtx = GLStateManager.ctx(); final StreamingVaos vaos = glCtx.streamingVaos; - ensureVAO(vaos, flags, format); + final boolean lineQuads = LineQuads.isQuadFormat(format); + final int[] persistentVAOs = lineQuads ? vaos.lineQuadPersistentVAOs : vaos.persistentVAOs; + final int[] orphanVAOs = lineQuads ? vaos.lineQuadOrphanVAOs : vaos.orphanVAOs; + ensureVAO(persistentVAOs, orphanVAOs, flags, format); if (Tracy.ENABLED) { streamedBytes += packed.remaining(); @@ -330,15 +341,16 @@ public class TessellatorStreamingDrawer { int firstVertex = -1; if (persistentBuffer != null) { - firstVertex = persistentBuffer.upload(packed, vertexSize, drawMode == GL11.GL_QUADS ? 4 : 1); + final int alignment = drawMode == GL11.GL_QUADS ? 4 : lineQuads ? LineQuads.VERTICES_PER_SEGMENT : 1; + firstVertex = persistentBuffer.upload(packed, vertexSize, alignment); } final boolean fromRing = firstVertex >= 0; if (fromRing) { - GLStateManager.glBindVertexArray(vaos.persistentVAOs[flags]); + GLStateManager.glBindVertexArray(persistentVAOs[flags]); } else { if (Tracy.ENABLED && persistentBuffer != null) orphanFallbacks++; - GLStateManager.glBindVertexArray(vaos.orphanVAOs[flags]); + GLStateManager.glBindVertexArray(orphanVAOs[flags]); orphanBuffers[flags].upload(packed); firstVertex = 0; } @@ -357,6 +369,72 @@ public class TessellatorStreamingDrawer { } } + private static boolean drawLinesAsQuads(ByteBuffer packed, VertexFormat format, int drawMode, int vertexCount) { + final int segments = LineQuads.segmentCount(drawMode, vertexCount); + if (segments == 0) { + return false; + } + final LineDrawHandler handler = GLSMHooks.lineDrawHandler; + if (handler != null && handler.bindLineProgram()) { + try { + drawLineQuads(packed, format, drawMode, vertexCount, segments, false); + } finally { + handler.restoreProgram(); + } + return true; + } + if (GLStateManager.ffpWidensLineQuads()) { + final GLContextState glCtx = GLStateManager.ctx(); + glCtx.lineQuadsActive = true; + try { + drawLineQuads(packed, format, drawMode, vertexCount, segments, true); + } finally { + glCtx.lineQuadsActive = false; + } + return true; + } + return false; + } + + private static void drawLineQuads(ByteBuffer packed, VertexFormat format, int drawMode, int vertexCount, int segments, boolean otherEnd) { + final VertexFormat quadFormat = LineQuads.quadFormat(format); + final int quadVertices = segments * LineQuads.VERTICES_PER_SEGMENT; + final int quadBytes = quadVertices * quadFormat.getVertexSize(); + ensureLineQuadCapacity(quadBytes); + final long src = memAddress0(packed) + packed.position(); + if (otherEnd) { + LineQuads.expandWithOtherEnd(src, format, drawMode, vertexCount, lineQuadAddress); + } else { + LineQuads.expandWithDirection(src, format, drawMode, vertexCount, lineQuadAddress); + } + lineQuadBuffer.position(0); + lineQuadBuffer.limit(quadBytes); + final boolean culled = LineQuads.disableCulling(); + try { + uploadAndDraw(lineQuadBuffer, quadFormat.getVertexFlags(), quadFormat, quadFormat.getVertexSize(), GL11.GL_TRIANGLES, quadVertices); + } finally { + LineQuads.restoreCulling(culled); + } + if (lineQuadCapacity > 0x20000 && quadBytes < (lineQuadCapacity >> 3)) { + memFree(lineQuadBuffer); + lineQuadBuffer = null; + lineQuadCapacity = 0; + } + } + + private static void ensureLineQuadCapacity(int requiredBytes) { + if (lineQuadBuffer != null && requiredBytes <= lineQuadCapacity) return; + + int newCapacity = Math.max(0x4000, lineQuadCapacity); + while (newCapacity < requiredBytes) { + newCapacity *= 2; + } + if (lineQuadBuffer != null) memFree(lineQuadBuffer); + lineQuadBuffer = memAlloc(newCapacity); + lineQuadAddress = memAddress0(lineQuadBuffer); + lineQuadCapacity = newCapacity; + } + public static long ringWraps() { return persistentBuffer == null ? 0L : persistentBuffer.getWraps(); } @@ -377,7 +455,7 @@ public class TessellatorStreamingDrawer { private static void uploadAndDrawExtended(ByteBuffer combined, int flags, VertexFormat format, int combinedStride, int drawMode, int vertexCount) { final GLContextState glCtx = GLStateManager.ctx(); final StreamingVaos vaos = glCtx.streamingVaos; - ensureVAO(vaos, flags, format); + ensureVAO(vaos.persistentVAOs, vaos.orphanVAOs, flags, format); ensureExtendedVAOs(vaos, flags, format); int firstVertex = -1; @@ -480,11 +558,9 @@ public class TessellatorStreamingDrawer { return repackBuffer; } - private static void ensureVAO(StreamingVaos vaos, int flags, VertexFormat format) { + private static void ensureVAO(int[] persistentVAOs, int[] orphanVAOs, int flags, VertexFormat format) { init(); if (orphanBuffers[flags] == null) orphanBuffers[flags] = new OrphanStreamingBuffer(); - final int[] orphanVAOs = vaos.orphanVAOs; - final int[] persistentVAOs = vaos.persistentVAOs; if (orphanVAOs[flags] == 0) { orphanVAOs[flags] = GLStateManager.glGenVertexArrays(); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java index 8707b19e1..80132629d 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformBlockLayoutGLTest.java @@ -18,7 +18,7 @@ class FFPUniformBlockLayoutGLTest { void driverOffsetsMatchJavaConstants() { final VertexKey vk = VertexKey.fromState(false, false, false, false, 0); final FragmentKey fk = FragmentKey.fromState(); - final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk), null); + final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk)); try { final int programId = program.getProgramId(); final int blockIndex = GL31.glGetUniformBlockIndex(programId, FFPUniformBlock.BLOCK_NAME); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java index c05830088..e2617b805 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPUniformValuesTest.java @@ -42,7 +42,7 @@ class FFPUniformValuesTest { final VertexKey vk = VertexKey.fromState(false, false, false, false, 0); final FragmentKey fk = FragmentKey.fromState(); - final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk), null); + final Program program = Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk)); final Uniforms uniforms = new Uniforms(); try { GL20.glUseProgram(program.getProgramId()); diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java index bd3473152..b768eddc5 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/ProgramUniformTrackingTest.java @@ -15,7 +15,7 @@ class ProgramUniformTrackingTest { private static Program buildProgram(boolean hasColor) { final VertexKey vk = VertexKey.fromState(hasColor, false, false, false, 0); final FragmentKey fk = FragmentKey.fromState(); - return Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk), null); + return Program.create(vk, fk, VertexShaderGenerator.generate(vk), FragmentShaderGenerator.generate(fk)); } @Test diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/WideLineClipGLTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/WideLineClipGLTest.java index c189730b4..1a85e1674 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/WideLineClipGLTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/WideLineClipGLTest.java @@ -13,7 +13,6 @@ import java.nio.FloatBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; @GLCoreTest class WideLineClipGLTest { @@ -23,7 +22,7 @@ class WideLineClipGLTest { private static final float LINE_WIDTH = 3.0f; private static final int BACKGROUND = 0xFF000000; - private static final float[] IN_FRONT = { 0f, -1f, -2f }; + private static final float[] IN_FRONT = { 0f, -0.9875f, -2f }; private static final float[] BEHIND = { 0f, 0.8f, 2f }; private boolean savedEmulation; @@ -32,7 +31,7 @@ class WideLineClipGLTest { @BeforeEach void setUp() { - assumeTrue(GLStateManager.supportsGeometryShaders()); + FfpFixture.routeVertexFormats(true); savedEmulation = GLStateManager.wideLineEmulationEnabled; GLStateManager.wideLineEmulationEnabled = true; @@ -51,6 +50,7 @@ class WideLineClipGLTest { @AfterEach void tearDown() { + FfpFixture.routeVertexFormats(false); GLStateManager.wideLineEmulationEnabled = savedEmulation; GLStateManager.glLineWidth(1.0f); if (vbo != 0) { GLStateManager.glDeleteBuffers(vbo); vbo = 0; } @@ -80,6 +80,60 @@ class WideLineClipGLTest { } } + private static void orthographic() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + private static float pixelCenter(int pixel) { + return (pixel + 0.5f) * 2.0f / SIZE - 1.0f; + } + + private static int litInColumn(int[] pixels, int x) { + int lit = 0; + for (int row = 0; row < SIZE; row++) { + if (pixels[row * SIZE + x] != BACKGROUND) lit++; + } + return lit; + } + + private int[] drawLineOnce(float[] start, float[] end) { + final int[] pixels = drawLine(start, end); + GLStateManager.glDeleteBuffers(vbo); + GLStateManager.glDeleteVertexArrays(vao); + vbo = 0; + vao = 0; + return pixels; + } + + @Test + void wideLineCoversItsFirstPixelButNotItsLast() { + orthographic(); + GLStateManager.glLineWidth(2.0f); + final float y = pixelCenter(16); + final int[] pixels = drawLineOnce(new float[] { pixelCenter(40), y, 0f }, new float[] { pixelCenter(20), y, 0f }); + assertEquals(2, litInColumn(pixels, 40), "first pixel of a right-to-left line"); + assertEquals(0, litInColumn(pixels, 20), "last pixel of a right-to-left line"); + assertEquals(2, litInColumn(pixels, 21), "pixel next to the last"); + } + + @Test + void cullingKeepsWideLinesInBothDirections() { + orthographic(); + GLStateManager.glLineWidth(2.0f); + GLStateManager.glEnable(GL11.GL_CULL_FACE); + try { + final int[] rightward = drawLineOnce(new float[] { -0.8f, 0f, 0f }, new float[] { 0.8f, 0f, 0f }); + final int[] leftward = drawLineOnce(new float[] { 0.8f, 0f, 0f }, new float[] { -0.8f, 0f, 0f }); + assertEquals(2, litInColumn(rightward, SIZE / 2), "left-to-right line with culling on"); + assertEquals(2, litInColumn(leftward, SIZE / 2), "right-to-left line with culling on"); + assertTrue(GLStateManager.getCullState().isEnabled(), "the game's cull state survives"); + } finally { + GLStateManager.glDisable(GL11.GL_CULL_FACE); + } + } + private void assertConstantWidth(float[] start, float[] end) { final int[] pixels = drawLine(start, end); for (int row = 0; row < SIZE / 4; row++) { diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuadsTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuadsTest.java new file mode 100644 index 000000000..f7cb4f894 --- /dev/null +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/streaming/LineQuadsTest.java @@ -0,0 +1,98 @@ +package com.gtnewhorizons.angelica.glsm.streaming; + +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LineQuadsTest { + + private static final int RED = 0xFF0000FF; + private static final int GREEN = 0xFF00FF00; + private static final int BLUE = 0xFFFF0000; + + private static ByteBuffer positionColor(float[][] positions, int[] colors) { + final ByteBuffer buf = ByteBuffer.allocateDirect(positions.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0; i < positions.length; i++) { + buf.putFloat(positions[i][0]).putFloat(positions[i][1]).putFloat(positions[i][2]).putInt(colors[i]); + } + return buf.flip(); + } + + private static ByteBuffer allocateQuads(int drawMode, int vertexCount) { + final VertexFormat quadFormat = LineQuads.quadFormat(DefaultVertexFormat.POSITION_COLOR); + final int quadVertices = LineQuads.segmentCount(drawMode, vertexCount) * LineQuads.VERTICES_PER_SEGMENT; + return ByteBuffer.allocateDirect(quadVertices * quadFormat.getVertexSize()).order(ByteOrder.nativeOrder()); + } + + private static ByteBuffer expand(ByteBuffer src, int drawMode, int vertexCount) { + final ByteBuffer dst = allocateQuads(drawMode, vertexCount); + LineQuads.expandWithDirection(memAddress0(src), DefaultVertexFormat.POSITION_COLOR, drawMode, vertexCount, memAddress0(dst)); + return dst; + } + + @Test + void otherEndCornersCarryTheOppositeEndpoint() { + final ByteBuffer src = positionColor(new float[][] {{0, 0, 0}, {2, 0, 3}}, new int[] {RED, GREEN}); + final ByteBuffer quads = allocateQuads(GL11.GL_LINES, 2); + LineQuads.expandWithOtherEnd(memAddress0(src), DefaultVertexFormat.POSITION_COLOR, GL11.GL_LINES, 2, memAddress0(quads)); + + final float[] end = {2, 0, 3}; + final float[] start = {0, 0, 0}; + final float[] ownX = {0, 0, 2, 0, 2, 2}; + final int[] color = {RED, RED, GREEN, RED, GREEN, GREEN}; + for (int i = 0; i < 6; i++) { + final boolean isStart = i == 0 || i == 1 || i == 3; + assertVertex(quads, i, ownX[i], isStart ? end : start, color[i]); + } + } + + private static final int STRIDE = 28; + + private static void assertVertex(ByteBuffer quads, int index, float x, float[] direction, int color) { + final int base = index * STRIDE; + assertEquals(x, quads.getFloat(base), "x of vertex " + index); + for (int axis = 0; axis < 3; axis++) { + assertEquals(direction[axis], quads.getFloat(base + 12 + axis * 4), "direction of vertex " + index); + } + assertEquals(color, quads.getInt(base + 24), "color of vertex " + index); + } + + @Test + void stripSegmentsFollowTheGeometryShaderCornerOrder() { + assertEquals(STRIDE, LineQuads.quadFormat(DefaultVertexFormat.POSITION_COLOR).getVertexSize()); + + final ByteBuffer src = positionColor(new float[][] {{0, 0, 0}, {2, 0, 0}, {2, 0, 3}}, new int[] {RED, GREEN, BLUE}); + final ByteBuffer quads = expand(src, GL11.GL_LINE_STRIP, 3); + + final float[] alongX = {1, 0, 0}; + final float[] alongZ = {0, 0, 1}; + final float[] firstX = {0, 0, 2, 0, 2, 2}; + final int[] firstColor = {RED, RED, GREEN, RED, GREEN, GREEN}; + for (int i = 0; i < 6; i++) { + assertVertex(quads, i, firstX[i], alongX, firstColor[i]); + } + final int[] secondColor = {GREEN, GREEN, BLUE, GREEN, BLUE, BLUE}; + for (int i = 0; i < 6; i++) { + assertVertex(quads, 6 + i, 2, alongZ, secondColor[i]); + } + } + + @Test + void loopClosesBackToFirstVertex() { + final ByteBuffer src = positionColor(new float[][] {{0, 0, 0}, {2, 0, 0}, {2, 0, 3}}, new int[] {RED, GREEN, BLUE}); + assertEquals(3, LineQuads.segmentCount(GL11.GL_LINE_LOOP, 3)); + final ByteBuffer quads = expand(src, GL11.GL_LINE_LOOP, 3); + + final int[] closingColor = {BLUE, BLUE, RED, BLUE, RED, RED}; + for (int i = 0; i < 6; i++) { + assertEquals(closingColor[i], quads.getInt((12 + i) * STRIDE + 24), "color of closing vertex " + i); + } + } +} diff --git a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java index 0c83a67bf..3ed8d0baa 100644 --- a/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java +++ b/glsm/src/testFixtures/java/com/gtnewhorizons/angelica/glsm/ffp/FfpFixture.java @@ -1,5 +1,8 @@ package com.gtnewhorizons.angelica.glsm.ffp; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Usage; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; @@ -153,6 +156,27 @@ public final class FfpFixture { GLStateManager.glVertexAttribPointer(loc, size, type, normalized, stride, offset); } + private static boolean formatRoutingRegistered; + private static boolean routeFormats; + + public static void routeVertexFormats(boolean enabled) { + routeFormats = enabled; + if (formatRoutingRegistered) return; + formatRoutingRegistered = true; + VertexFormat.registerSetupBufferStateOverride((format, offset) -> { + if (!routeFormats) return false; + final int stride = format.getVertexSize(); + int elementOffset = (int) offset; + for (VertexFormatElement element : format.elementsArray) { + final Usage usage = element.getUsage(); + final boolean normalized = usage == Usage.COLOR || usage == Usage.NORMAL; + attrib(usage.getAttributeLocation(), element.getCount(), element.getType().getGlType(), normalized, stride, elementOffset); + elementOffset += element.getByteSize(); + } + return true; + }); + } + public static void clear() { GLStateManager.glClearColor(0f, 0f, 0f, 1f); GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); 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 baa336f26..0472c65c9 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 @@ -871,6 +871,9 @@ public class SDLGPURenderBackend extends RenderBackend { case GL11.GL_CULL_FACE -> { if (cs.pipeline.cullEnabled != on) { cs.pipeline.cullEnabled = on; cs.pipeline.markOutputDirty(); } } + case GL11.GL_POLYGON_OFFSET_FILL -> { + if (cs.pipeline.polygonOffsetFillEnabled != on) { cs.pipeline.polygonOffsetFillEnabled = on; cs.pipeline.markOutputDirty(); } + } case GL11.GL_STENCIL_TEST -> { if (cs.pipeline.stencilTestEnabled != on) { cs.pipeline.stencilTestEnabled = on; cs.pipeline.markOutputDirty(); } } @@ -1244,6 +1247,7 @@ public class SDLGPURenderBackend extends RenderBackend { if (rp == 0) return; final int firstIndex = (int) (indices / FormatMap.indexElementSize(type)); if (SystemProperties.FFP_TRACE) ffpTrace.trace(st, "elementsInstanced", mode, count, type, firstIndex, 0); + pipelineApplier.bindInstancedConstants(st, rp, primcount); drawDispatch.issueIndexedDraw(st, rp, st.currentVao.elementBuffer, type, count, primcount, firstIndex, 0); captureVertexWrites(st, 0, count, primcount, type, indices, 0); } @@ -4137,6 +4141,7 @@ public class SDLGPURenderBackend extends RenderBackend { case GL11.GL_DEPTH_TEST -> cs.pipeline.depthTestEnabled; case GL11.GL_BLEND -> cs.pipeline.blendEnabledPerDrawBuffer[0]; case GL11.GL_CULL_FACE -> cs.pipeline.cullEnabled; + case GL11.GL_POLYGON_OFFSET_FILL -> cs.pipeline.polygonOffsetFillEnabled; case GL11.GL_SCISSOR_TEST -> cs.scissorEnabled; case GL11.GL_STENCIL_TEST -> cs.pipeline.stencilTestEnabled; case GL11.GL_DEPTH_WRITEMASK -> cs.pipeline.depthWriteEnabled; @@ -4477,7 +4482,9 @@ public class SDLGPURenderBackend extends RenderBackend { if (!frameManager.isRenderPassActive()) return; if (!pipelineApplier.applyPipelineAndState(st)) return; if (SystemProperties.FFP_TRACE) ffpTrace.trace(st, "arraysInstanced", mode, count, 0, first, 0); - SDL_DrawGPUPrimitives(frameManager.getRenderPass(), count, primcount, first, 0); + final long rp = frameManager.getRenderPass(); + pipelineApplier.bindInstancedConstants(st, rp, primcount); + SDL_DrawGPUPrimitives(rp, count, primcount, first, 0); captureVertexWrites(st, first, count, primcount, 0, 0, 0); } diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java index 625e076cc..40c3e47f2 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/device/Device.java @@ -357,6 +357,10 @@ public final class Device { return driverName; } + public boolean isMetal() { + return isMetal(driverName); + } + public boolean isFencePollEnabled() { return fencePollEnabled; } diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/InstancedConstantBuffers.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/InstancedConstantBuffers.java new file mode 100644 index 000000000..dbcca8c4d --- /dev/null +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/InstancedConstantBuffers.java @@ -0,0 +1,82 @@ +package com.gtnewhorizons.angelica.sdlgpu.pipeline; + +import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +/** + * Metal cannot step a vertex buffer by zero bytes, and SDL cannot select Metal's constant step function, so a constant + * attribute bound per instance reads the next 16 bytes for every instance. + */ +final class InstancedConstantBuffers { + + private static final int BYTES_PER_VALUE = 16; + private static final int MAX_VALUES = 64; + + private final ResourceManager resources; + private final Long2ObjectOpenHashMap byValue = new Long2ObjectOpenHashMap<>(); + private ByteBuffer staging; + + private static final class Entry { + final long xy, zw; + long buffer; + int instances; + + Entry(long xy, long zw) { + this.xy = xy; + this.zw = zw; + } + } + + InstancedConstantBuffers(ResourceManager resources) { + this.resources = resources; + } + + long buffer(float x, float y, float z, float w, int instances, DrawDispatch.FanUploadSink upload) { + final long xy = Hashing.packHiLo(Float.floatToRawIntBits(x), Float.floatToRawIntBits(y)); + final long zw = Hashing.packHiLo(Float.floatToRawIntBits(z), Float.floatToRawIntBits(w)); + final long key = Hashing.fmix64(Hashing.fmix64(0L, xy), zw); + Entry entry = byValue.get(key); + if (entry != null && (entry.xy != xy || entry.zw != zw)) { + resources.releaseBufferDeferred(entry.buffer); + byValue.remove(key); + entry = null; + } + if (entry != null && entry.instances >= instances) return entry.buffer; + + if (entry == null) { + if (byValue.size() >= MAX_VALUES) clear(); + entry = new Entry(xy, zw); + byValue.put(key, entry); + } else { + resources.releaseBufferDeferred(entry.buffer); + } + + final int capacity = instances <= 1 ? 1 : Integer.highestOneBit(instances - 1) << 1; + final int bytes = capacity * BYTES_PER_VALUE; + entry.buffer = resources.createVertexBuffer(bytes); + entry.instances = entry.buffer == 0 ? 0 : capacity; + if (entry.buffer == 0) return 0; + + if (staging == null || staging.capacity() < bytes) { + if (staging != null) MemoryUtil.memFree(staging); + staging = MemoryUtil.memAlloc(bytes); + } + staging.clear(); + for (int i = 0; i < capacity; i++) { + staging.putFloat(x).putFloat(y).putFloat(z).putFloat(w); + } + staging.flip(); + upload.enqueuePreCopied(staging, entry.buffer, 0, false); + return entry.buffer; + } + + void clear() { + for (Entry entry : byValue.values()) { + resources.releaseBufferDeferred(entry.buffer); + } + byValue.clear(); + } +} 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 5152c18a4..f5392541d 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 @@ -62,6 +62,7 @@ public final class PipelineApplier { private DrawDispatch.FanUploadSink deferredUploadSink; public void setDeferredUploadSink(DrawDispatch.FanUploadSink sink) { this.deferredUploadSink = sink; } + private final InstancedConstantBuffers instancedConstants; private boolean ringOverflowWarned; private final IntOpenHashSet pipelineZeroWarned = new IntOpenHashSet(); @@ -86,6 +87,33 @@ public final class PipelineApplier { this.storageTextureBinder = storageTextureBinder; this.storageBufferBinder = storageBufferBinder; this.logicOpEmulator = new LogicOpEmulator(frameManager, resourceManager, shaderManager, this); + this.instancedConstants = new InstancedConstantBuffers(resourceManager); + } + + /** + * Runs after {@link #applyPipelineAndState} for an instanced draw. On Metal every attribute without an enabled array + * is rebound to a buffer repeating its value once per instance (see {@link InstancedConstantBuffers}). + */ + public void bindInstancedConstants(ContextState st, long rp, int instances) { + if (instances <= 1 || deferredUploadSink == null || !pipelineStore.device().isMetal()) return; + final ContextState.VAOState vao = st.currentVao; + final int usedMask = st.pipeline.shaderInputMask | vao.attribEnabledMask; + if (usedMask == 0) return; + final int bindingSize = SDL_GPUBufferBinding.SIZEOF; + final int maxSlot = 31 - Integer.numberOfLeadingZeros(usedMask); + int constants = ~vao.attribEnabledMask & ((1 << (maxSlot + 1)) - 1); + while (constants != 0) { + final int i = Integer.numberOfTrailingZeros(constants); + constants &= constants - 1; + final float[] d = st.attribDefaults; + final long buffer = instancedConstants.buffer(d[i * 4], d[i * 4 + 1], d[i * 4 + 2], d[i * 4 + 3], instances, deferredUploadSink); + if (buffer == 0) continue; + final long elemAddr = st.vboBindingsAddr + (long) i * bindingSize; + MemoryAccess.putAddress(elemAddr + SDL_GPUBufferBinding.BUFFER, buffer); + MemoryAccess.putInt(elemAddr + SDL_GPUBufferBinding.OFFSET, 0); + nSDL_BindGPUVertexBuffers(rp, i, elemAddr, 1); + } + st.lastAppliedVboBindGen = -1; } public void ensureDrawRenderPass(ContextState st) { 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 038c7c574..dae9307f2 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 @@ -108,10 +108,16 @@ public final class PipelineCache { return cullEnabled ? cullFaceMode : SDL_GPU_CULLMODE_NONE; } public int fillMode = SDL_GPU_FILLMODE_FILL; + public boolean polygonOffsetFillEnabled; public float depthBiasConstant; public float depthBiasSlopeFactor; public float depthBiasClamp; + public boolean effectiveDepthBiasEnabled() { + return polygonOffsetFillEnabled && fillMode == SDL_GPU_FILLMODE_FILL + && (primitiveType == SDL_GPU_PRIMITIVETYPE_TRIANGLELIST || primitiveType == SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP); + } + public int colorWriteMask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A; public long vertexShader; @@ -364,6 +370,7 @@ public final class PipelineCache { | ((depthWriteOn ? 1L : 0L) << 2) | ((stencilOn ? 1L : 0L) << 3) | ((hasDepthTarget ? 1L : 0L) << 4) + | ((effectiveDepthBiasEnabled() ? 1L : 0L) << 5) | (((long) blendBits & 0xFFFFFFFFL) << 32); long h = OUTPUT_SEED; h = Hashing.fmix64(h, bits); @@ -380,8 +387,10 @@ public final class PipelineCache { h = Hashing.fmix64(h, Hashing.packHiLo(stencilCompareMask, stencilWriteMask)); h = Hashing.fmix64(h, Hashing.packHiLo(getEffectiveCullMode(), effectiveFrontFace())); h = Hashing.fmix64(h, Hashing.packHiLo(fillMode, colorWriteMask)); - h = Hashing.fmix64(h, Hashing.packHiLo(Float.floatToRawIntBits(depthBiasConstant), Float.floatToRawIntBits(depthBiasSlopeFactor))); - h = Hashing.fmix64(h, Float.floatToRawIntBits(depthBiasClamp)); + if (effectiveDepthBiasEnabled()) { + h = Hashing.fmix64(h, Hashing.packHiLo(Float.floatToRawIntBits(depthBiasConstant), Float.floatToRawIntBits(depthBiasSlopeFactor))); + h = Hashing.fmix64(h, Float.floatToRawIntBits(depthBiasClamp)); + } h = Hashing.fmix64(h, Hashing.packHiLo(ctfLen, hasDepthTarget ? depthTargetFormat : 0)); for (int i = 0; i < ctfLen; i++) { h = Hashing.fmix64(h, colorTargetFormats()[i]); @@ -523,6 +532,7 @@ public final class PipelineCache { .cull_mode(getEffectiveCullMode()) .front_face(effectiveFrontFace()) .fill_mode(fillMode) + .enable_depth_bias(effectiveDepthBiasEnabled()) .depth_bias_constant_factor(depthBiasConstant) .depth_bias_slope_factor(depthBiasSlopeFactor) .depth_bias_clamp(depthBiasClamp); @@ -609,6 +619,7 @@ public final class PipelineCache { sb.append(" Rasterizer: cull=").append(getEffectiveCullMode()) .append(" front=").append(effectiveFrontFace()) .append(" fill=").append(fillMode) + .append(" biasEnabled=").append(effectiveDepthBiasEnabled()) .append(" biasConst=").append(depthBiasConstant) .append(" biasSlope=").append(depthBiasSlopeFactor) .append(" biasClamp=").append(depthBiasClamp).append('\n'); @@ -891,11 +902,12 @@ public final class PipelineCache { final int numAttributes = numBuffers; final SDL_GPUVertexAttribute.Buffer attrs = SDL_GPUVertexAttribute.calloc(numAttributes, stack); final SDL_GPUVertexBufferDescription.Buffer bindings = SDL_GPUVertexBufferDescription.calloc(numBuffers, stack); + final int constantPitch = store.device().isMetal() ? 16 : 0; for (int i = 0; i < numBuffers; i++) { if ((inputMask & (1 << i)) == 0) { bindings.get(i) - .slot(i).pitch(16) + .slot(i).pitch(constantPitch) .input_rate(SDL_GPU_VERTEXINPUTRATE_INSTANCE).instance_step_rate(0); attrs.get(i) .location(i).buffer_slot(i) @@ -955,7 +967,7 @@ public final class PipelineCache { } else { final int vecSize = i < shaderInputVecSize.length ? shaderInputVecSize[i] : 4; bindings.get(i) - .slot(i).pitch(16) // sizeof(vec4), one element + .slot(i).pitch(constantPitch) .input_rate(SDL_GPU_VERTEXINPUTRATE_INSTANCE).instance_step_rate(0); attrs.get(i) .location(i).buffer_slot(i) diff --git a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java index 50dd1787c..d5b853cba 100644 --- a/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java +++ b/sdl-gpu/src/main/java/com/gtnewhorizons/angelica/sdlgpu/resource/ResourceManager.java @@ -2385,6 +2385,18 @@ public final class ResourceManager { return chunk * ATTRIB_RING_CHUNK_BLOCKS * DUMMY_VBO_SIZE; } + public long createVertexBuffer(int size) { + try (var stack = stackPush()) { + final long handle = SDL_CreateGPUBuffer(device.getDevice(), SDL_GPUBufferCreateInfo.calloc(stack).usage(SDL_GPU_BUFFERUSAGE_VERTEX).size(size)); + if (handle == 0) { + LOG.error("Failed to create vertex buffer size={}: {}", size, SDLError.SDL_GetError()); + return 0; + } + trackBufferHandle(handle); + return handle; + } + } + public long getOrCreateDummyVertexBuffer() { if (dummyVertexBuffer != 0) return dummyVertexBuffer; diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlInstancedConstantTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlInstancedConstantTest.java new file mode 100644 index 000000000..3306f62ff --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlInstancedConstantTest.java @@ -0,0 +1,109 @@ +package com.gtnewhorizons.angelica.sdlgpu.glsm; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; +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.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Metal steps a per-instance constant binding by 16 bytes per instance. + */ +@Tag("glsm-sdl") +@ExtendWith(GlsmSdlFrameExtension.class) +class GlsmSdlInstancedConstantTest { + + private static final int INSTANCES = 4; + private static final int TINT_LOCATION = 3; + + private static final String VERT = """ + #version 330 core + layout(location = 0) in vec2 a_Position; + layout(location = 3) in vec4 a_Tint; + out vec4 v_Tint; + void main() { + gl_Position = vec4(-1.0 + 0.5 * (float(gl_InstanceID) + a_Position.x), a_Position.y, 0.0, 1.0); + v_Tint = a_Tint; + } + """; + + private static final String FRAG = """ + #version 330 core + in vec4 v_Tint; + out vec4 fragColor; + void main() { + fragColor = v_Tint; + } + """; + + @BeforeAll + static void boot() { + GlsmSdlHeadlessRig.boot(); + } + + private static int compile(int type, String source) { + final int shader = GLStateManager.glCreateShader(type); + GLStateManager.glShaderSource(shader, source); + GLStateManager.glCompileShader(shader); + assertTrue(GLStateManager.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) != 0, () -> GLStateManager.glGetShaderInfoLog(shader)); + return shader; + } + + @Test + void everyInstanceReadsTheConstantWhenInstancesStepTheBinding() { + final Device device = SDLGPUGate.device(); + final String driver = device.getDriverName(); + Reflect.set(device, "driverName", "metal"); + final int program = GLStateManager.glCreateProgram(); + GLStateManager.glAttachShader(program, compile(GL20.GL_VERTEX_SHADER, VERT)); + GLStateManager.glAttachShader(program, compile(GL20.GL_FRAGMENT_SHADER, FRAG)); + GLStateManager.glLinkProgram(program); + assertTrue(GLStateManager.glGetProgrami(program, GL20.GL_LINK_STATUS) != 0, "program did not link"); + + final int vao = GLStateManager.glGenVertexArrays(); + final int vbo = GLStateManager.glGenBuffers(); + final FloatBuffer quad = MemoryUtil.memAllocFloat(12); + try { + quad.put(new float[] { 0, -1, 1, -1, 1, 1, 0, -1, 1, 1, 0, 1 }).flip(); + GLStateManager.glBindVertexArray(vao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, quad, GL15.GL_STATIC_DRAW); + GLStateManager.glEnableVertexAttribArray(0); + GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 8, 0L); + GLStateManager.glDisableVertexAttribArray(TINT_LOCATION); + GLStateManager.glVertexAttrib4f(TINT_LOCATION, 0.2f, 0.4f, 0.6f, 1.0f); + + GLStateManager.glUseProgram(program); + GLStateManager.glDrawArraysInstanced(GL11.GL_TRIANGLES, 0, 6, INSTANCES); + GLStateManager.glUseProgram(0); + + final int[] row = GlsmSdlHeadlessRig.readTarget(0, GlsmSdlHeadlessRig.SIZE / 2, GlsmSdlHeadlessRig.SIZE, 1); + final int expected = 0xFF000000 | (51 << 16) | (102 << 8) | 153; + for (int instance = 0; instance < INSTANCES; instance++) { + final int x = (2 * instance + 1) * GlsmSdlHeadlessRig.SIZE / (2 * INSTANCES); + final int got = row[x]; + assertEquals(Integer.toHexString(expected), Integer.toHexString(got), "instance " + instance); + } + } finally { + Reflect.set(device, "driverName", driver); + MemoryUtil.memFree(quad); + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glDeleteBuffers(vbo); + GLStateManager.glDeleteVertexArrays(vao); + GLStateManager.glDeleteProgram(program); + } + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlWideLineTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlWideLineTest.java new file mode 100644 index 000000000..5abc44b55 --- /dev/null +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/glsm/GlsmSdlWideLineTest.java @@ -0,0 +1,168 @@ +package com.gtnewhorizons.angelica.sdlgpu.glsm; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.junit.jupiter.api.AfterEach; +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 static com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig.SIZE; +import static com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig.pixelAt; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("glsm-sdl") +@ExtendWith(GlsmSdlFrameExtension.class) +class GlsmSdlWideLineTest { + + @BeforeAll + static void boot() { + GlsmSdlHeadlessRig.boot(); + } + + @AfterEach + void resetLineState() { + GLStateManager.glLineWidth(1.0f); + GLStateManager.glDisable(GL11.GL_LINE_STIPPLE); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + + private static void line(float[] start, float[] end) { + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBegin(GL11.GL_LINES); + GLStateManager.glVertex3f(start[0], start[1], start[2]); + GLStateManager.glVertex3f(end[0], end[1], end[2]); + GLStateManager.glEnd(); + } + + private static int litInRow(int[] pixels, int y) { + int lit = 0; + for (int x = 0; x < SIZE; x++) { + if ((pixelAt(pixels, SIZE, x, y) & 0x00FFFFFF) != 0) lit++; + } + return lit; + } + + @Test + void stippledWideLineKeepsOnePhaseAcrossItsWidth() { + GLStateManager.glLineWidth(3.0f); + GLStateManager.glEnable(GL11.GL_LINE_STIPPLE); + GLStateManager.glLineStipple(2, (short) 0x0F0F); + final float y = pixelCenter(32); + line(new float[] { pixelCenter(8), y, 0f }, new float[] { pixelCenter(56), y, 0f }); + + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + int fullColumns = 0; + int emptyColumns = 0; + for (int x = 9; x < 55; x++) { + final int lit = litInColumn(pixels, x); + final int column = x; + assertTrue(lit == 0 || lit == 3, () -> "column " + column + " has " + lit + " of 3 rows lit"); + if (lit == 3) fullColumns++; else emptyColumns++; + } + assertTrue(fullColumns > 0 && emptyColumns > 0, "stipple pattern visible"); + } + + private static final float[] IN_FRONT = { 0f, -0.9875f, -2f }; + private static final float[] BEHIND = { 0f, 0.8f, 2f }; + + private static void nearPlaneScene() { + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glFrustum(-0.05, 0.05, -0.05, 0.05, 0.05, 100.0); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLineWidth(3.0f); + } + + private static void assertWidthAcrossTheNearPlane(float[] start, float[] end) { + nearPlaneScene(); + line(start, end); + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + int rows = 0; + for (int y = 0; y < SIZE; y++) { + final int lit = litInRow(pixels, y); + if (lit == 0) continue; + rows++; + final int row = y; + assertTrue(lit <= 4, () -> "row " + row + " is " + lit + " pixels wide"); + } + final int drawnRows = rows; + assertTrue(drawnRows >= SIZE / 4, () -> "line covers only " + drawnRows + " rows"); + } + + @Test + void lineEndingBehindTheCameraKeepsItsWidth() { + assertWidthAcrossTheNearPlane(IN_FRONT, BEHIND); + } + + @Test + void lineStartingBehindTheCameraKeepsItsWidth() { + assertWidthAcrossTheNearPlane(BEHIND, IN_FRONT); + } + + @Test + void lineFullyBehindTheCameraDrawsNothing() { + nearPlaneScene(); + line(new float[] { 0f, -1f, 2f }, BEHIND); + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + for (int y = 0; y < SIZE; y++) { + assertEquals(0, litInRow(pixels, y), "row " + y); + } + } + + private static int litRowsInColumn(int[] pixels, int x, int fromRow, int toRow) { + int lit = 0; + for (int y = fromRow; y < toRow; y++) { + if ((pixelAt(pixels, SIZE, x, y) & 0x00FFFFFF) != 0) lit++; + } + return lit; + } + + private static void horizontalLines(float width, float lowerY, float upperY) { + GLStateManager.glEnable(GL11.GL_CULL_FACE); + GLStateManager.glLineWidth(width); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBegin(GL11.GL_LINES); + GLStateManager.glVertex3f(-0.8f, lowerY, 0.0f); + GLStateManager.glVertex3f(0.8f, lowerY, 0.0f); + GLStateManager.glVertex3f(0.8f, upperY, 0.0f); + GLStateManager.glVertex3f(-0.8f, upperY, 0.0f); + GLStateManager.glEnd(); + } + + @Test + void wideLinesKeepTheirWidthInBothDirections() { + horizontalLines(6.0f, -0.5f, 0.5f); + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + assertEquals(6, litRowsInColumn(pixels, SIZE / 2, 0, SIZE / 2), "left-to-right line thickness"); + assertEquals(6, litRowsInColumn(pixels, SIZE / 2, SIZE / 2, SIZE), "right-to-left line thickness"); + } + + private static float pixelCenter(int pixel) { + return (pixel + 0.5f) * 2.0f / SIZE - 1.0f; + } + + private static int litInColumn(int[] pixels, int x) { + return litRowsInColumn(pixels, x, 0, SIZE); + } + + @Test + void wideLineCoversItsFirstPixelButNotItsLast() { + final float y = pixelCenter(16); + GLStateManager.glLineWidth(2.0f); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBegin(GL11.GL_LINES); + GLStateManager.glVertex3f(pixelCenter(40), y, 0.0f); + GLStateManager.glVertex3f(pixelCenter(20), y, 0.0f); + GLStateManager.glEnd(); + + final int[] pixels = GlsmSdlHeadlessRig.readTarget(); + assertEquals(2, litInColumn(pixels, 40), "first pixel of a right-to-left line"); + assertEquals(0, litInColumn(pixels, 20), "last pixel of a right-to-left line"); + assertEquals(2, litInColumn(pixels, 21), "pixel next to the last"); + } +} diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java index a9b16d2fa..e7bbc1fab 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheKeyTest.java @@ -210,20 +210,51 @@ class PipelineCacheKeyTest { assertNotEquals(computeKey(a), computeKey(b), "Color target format change should produce different key"); } + @Test + void polygonOffsetEnableChangesKeyForFilledTrianglesOnly() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.polygonOffsetFillEnabled = true; + for (int primitive : new int[]{SDL_GPU_PRIMITIVETYPE_TRIANGLELIST, SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP}) { + a.primitiveType = b.primitiveType = primitive; + assertNotEquals(computeKey(a), computeKey(b), "filled triangle offset needs a distinct pipeline"); + } + for (int primitive : new int[]{SDL_GPU_PRIMITIVETYPE_LINELIST, SDL_GPU_PRIMITIVETYPE_LINESTRIP, SDL_GPU_PRIMITIVETYPE_POINTLIST}) { + a.primitiveType = b.primitiveType = primitive; + assertEquals(computeKey(a), computeKey(b), "polygon offset fill must not bias lines or points"); + } + a.primitiveType = b.primitiveType = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + a.fillMode = b.fillMode = SDL_GPU_FILLMODE_LINE; + assertEquals(computeKey(a), computeKey(b), "polygon offset fill must not bias wireframe polygons"); + } + @Test void testDepthBiasChangeProducesDifferentKey() { final PipelineCache a = createCache(); final PipelineCache b = createCache(); + a.polygonOffsetFillEnabled = b.polygonOffsetFillEnabled = true; b.depthBiasConstant = 1.0f; b.depthBiasSlopeFactor = 2.0f; assertNotEquals(computeKey(a), computeKey(b), "Depth bias change should produce different key"); } + @Test + void depthBiasValuesShareAPipelineWhileOffsetIsOff() { + final PipelineCache a = createCache(); + final PipelineCache b = createCache(); + b.depthBiasConstant = 1.0f; + b.depthBiasSlopeFactor = 2.0f; + b.depthBiasClamp = 0.5f; + + assertEquals(computeKey(a), computeKey(b), "glPolygonOffset with the offset disabled must not build a new pipeline"); + } + @Test void testDepthBiasClampProducesDifferentKey() { final PipelineCache a = createCache(); final PipelineCache b = createCache(); + a.polygonOffsetFillEnabled = b.polygonOffsetFillEnabled = true; a.depthBiasConstant = b.depthBiasConstant = 1.0f; a.depthBiasSlopeFactor = b.depthBiasSlopeFactor = 2.0f; b.depthBiasClamp = 0.5f; diff --git a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java index de4f10115..77e038c80 100644 --- a/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java +++ b/sdl-gpu/src/test/java/com/gtnewhorizons/angelica/sdlgpu/pipeline/PipelineCacheVertexInputTest.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.sdlgpu.pipeline; import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState; +import com.gtnewhorizons.angelica.sdlgpu.device.Device; import com.gtnewhorizons.angelica.glsm.testutil.Reflect; import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; import org.junit.jupiter.api.BeforeEach; @@ -24,14 +25,20 @@ import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXINPUTRATE_INSTANCE; import static org.lwjgl.sdl.SDLGPU.SDL_GPU_VERTEXINPUTRATE_VERTEX; class PipelineCacheVertexInputTest { - private static final int PLACEHOLDER_PITCH = 16; + private static final int PLACEHOLDER_PITCH = 0; private PipelineStore store; @BeforeEach void setUp() { PipelineCache.setSwapchainFormats(new int[]{SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM}); - store = new PipelineStore(null); + store = new PipelineStore(device("vulkan")); + } + + private static Device device(String driverName) { + final Device device = new Device(); + Reflect.set(device, "driverName", driverName); + return device; } private static int nextTestSetId = 1; @@ -269,7 +276,7 @@ class PipelineCacheVertexInputTest { } @Test - void shaderExpectsButVaoMissing_emitsInstanceExpansion() { + void shaderExpectsButVaoMissing_emitsConstantBinding() { final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; vecSizes[0] = 3; vecSizes[1] = 4; final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; @@ -292,6 +299,26 @@ class PipelineCacheVertexInputTest { } } + @Test + void constantBindingUsesZeroPitchExceptOnMetal() { + final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + vecSizes[4] = 3; + final int[] baseTypes = new int[ContextState.MAX_VERTEX_ATTRIBS]; + baseTypes[4] = Spvc.SPVC_BASETYPE_FP32; + final PipelineCache c = cache(1 << 4, vecSizes, baseTypes); + final ContextState cs = new ContextState(); + + for (String driver : new String[] { "vulkan", "metal", "direct3d12" }) { + try (MemoryStack stack = MemoryStack.stackPush()) { + final PipelineCache.VertexInputResult r = c.buildVertexInput(new PipelineStore(device(driver)), cs, stack); + assertNotNull(r); + final int expectedPitch = driver.equals("metal") ? 16 : 0; + assertEquals(expectedPitch, r.bindings().get(4).pitch(), driver + " current normal"); + assertEquals(expectedPitch, r.bindings().get(0).pitch(), driver + " unused slot"); + } + } + } + @Test void vaoExtraAttribNotInShader_droppedFromPipeline() { final int[] vecSizes = new int[ContextState.MAX_VERTEX_ATTRIBS]; diff --git a/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat3Array.java b/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat3Array.java new file mode 100644 index 000000000..b3b74d128 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat3Array.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.client.rendering; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniform; + +import java.nio.FloatBuffer; + +public class GlUniformFloat3Array extends GlUniform { + + public GlUniformFloat3Array(int index) { + super(index); + } + + @Override + public void set(FloatBuffer value) { + GLStateManager.glUniform3(this.index, value); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat4Array.java b/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat4Array.java new file mode 100644 index 000000000..b24172386 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/rendering/GlUniformFloat4Array.java @@ -0,0 +1,18 @@ +package com.gtnewhorizons.angelica.client.rendering; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniform; + +import java.nio.FloatBuffer; + +public class GlUniformFloat4Array extends GlUniform { + + public GlUniformFloat4Array(int index) { + super(index); + } + + @Override + public void set(FloatBuffer value) { + GLStateManager.glUniform4(this.index, value); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawer.java b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawer.java new file mode 100644 index 000000000..30e9a740d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawer.java @@ -0,0 +1,472 @@ +package com.gtnewhorizons.angelica.compat.thaumcraft; + +import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat2v; +import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat3Array; +import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat4Array; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.StateSet; +import com.gtnewhorizons.angelica.glsm.states.FogState; +import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; +import net.coderbot.iris.gl.framebuffer.GlFramebuffer; +import org.embeddedt.embeddium.impl.gl.shader.GlProgram; +import org.embeddedt.embeddium.impl.gl.shader.GlShader; +import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext; +import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; +import org.embeddedt.embeddium.impl.gl.shader.ShaderType; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; +import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; +import org.joml.Matrix4f; +import org.joml.Vector4f; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.util.Arrays; +import java.util.Random; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Y; + +/** + * GL side of the Thaumcraft portal renderer. + */ +final class PortalDrawer { + static final int LAYERS = 16; + static final int FLOATS_PER_FACE = 16; + static final int ATLAS_SIZE = 2048; + static final int MIN_SLOT = 16; + static final int MAX_SLOT = 512; + private static final int FLOATS_PER_PLANE = LAYERS * 3; + private static final int TUNNEL_UNIT = 0; + private static final int LIGHTMAP_UNIT = 1; + private static final int FIELD_UNIT = 2; + private static final int FACE_BYTES = FLOATS_PER_FACE * Float.BYTES; + private static final double LN2 = Math.log(2.0); + private static final double SQRT_LN2 = Math.sqrt(LN2); + private static final float[] LAYER_DEPTH = new float[LAYERS]; + private static final float[] LAYER_SCALE = new float[LAYERS]; + private static final float[] LAYER_ANGLE = new float[LAYERS]; + private static final float[] FOG_PARAMS = new float[4]; + private static int maxPlanes; + + static { + for (int i = 0; i < LAYERS; i++) { + LAYER_DEPTH[i] = i == 0 ? 65.0F : 16 - i; + LAYER_SCALE[i] = i == 0 ? 0.125F : i == 1 ? 0.5F : 0.0625F; + // GLStateManager.glRotatef's float radians + LAYER_ANGLE[i] = (float) Math.toRadians((float) (i * i * 4321 + i * 9) * 2.0F); + } + } + + private GlProgram direct; + private GlProgram directFogged; + private GlProgram capture; + private FloatBuffer upload; + private FloatBuffer planeUpload; + private int vao, vbo, ebo; + private GlFramebuffer atlasFramebuffer; + private int atlasTexture; + + static int maxPlanes() { + if (maxPlanes == 0) { + final int vectors = GLStateManager.glGetInteger(GL20.GL_MAX_VERTEX_UNIFORM_COMPONENTS) / 4; + maxPlanes = Math.clamp((vectors - 128) / 12, 1, 64); + } + return maxPlanes; + } + + static void putFace(float[] faces, int index, int axis, int plane, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + int i = index * FLOATS_PER_FACE; + faces[i++] = (float) x0; + faces[i++] = (float) y0; + faces[i++] = (float) z0; + faces[i++] = axis + 4 * plane; + faces[i++] = (float) x1; + faces[i++] = (float) y1; + faces[i++] = (float) z1; + faces[i++] = 0.0F; + faces[i++] = (float) (x1 + x3 - x0); + faces[i++] = (float) (y1 + y3 - y0); + faces[i++] = (float) (z1 + z3 - z0); + faces[i++] = 0.0F; + faces[i++] = (float) x3; + faces[i++] = (float) y3; + faces[i++] = (float) z3; + faces[i] = 0.0F; + } + + private static int fogMode() { + if (!GLStateManager.getFogMode().isEnabled()) return 0; + return switch (GLStateManager.getFogState().getFogMode()) { + case GL11.GL_LINEAR -> 1; + case GL11.GL_EXP -> 2; + case GL11.GL_EXP2 -> 3; + default -> 0; + }; + } + + private static void uploadFog(Uniforms uniforms, int fogMode) { + final FogState fog = GLStateManager.getFogState(); + final float start = fog.getStart(); + final float end = fog.getEnd(); + final float density = fog.getDensity(); + final float range = end - start; + FOG_PARAMS[0] = range != 0.0f ? -1.0f / range : 0.0f; + FOG_PARAMS[1] = range != 0.0f ? end / range : 1.0f; + FOG_PARAMS[2] = (float) (density / LN2); + FOG_PARAMS[3] = (float) (density / SQRT_LN2); + uniforms.fogParams.set(FOG_PARAMS); + uniforms.fogColor.set((float) fog.getFogColor().x, (float) fog.getFogColor().y, (float) fog.getFogColor().z); + uniforms.fogMode.setInt(fogMode); + uniforms.fogDistanceMode.setInt(fog.getFogDistanceMode()); + } + + private static void instanced(int attribute, int size, int floatOffset) { + GLStateManager.glEnableVertexAttribArray(attribute); + GLStateManager.glVertexAttribPointer(attribute, size, GL11.GL_FLOAT, false, FACE_BYTES, (long) floatOffset * Float.BYTES); + GLStateManager.glVertexAttribDivisor(attribute, 1); + } + + private static GlProgram buildProgram(boolean capturing, boolean fogged) { + final ShaderConstants.Builder defines = ShaderConstants.builder().add("MAX_PLANES", Integer.toString(maxPlanes())); + if (capturing) defines.add("CAPTURE"); + if (fogged) defines.add("FOG"); + final ShaderConstants constants = defines.build(); + final GlShader vert = ShaderLoader.loadShader(ShaderType.VERTEX, "angelica:thaumcraft_portal.vert", constants); + final GlShader frag = ShaderLoader.loadShader(ShaderType.FRAGMENT, "angelica:thaumcraft_portal.frag", constants); + final GlProgram program; + try { + program = GlProgram.builder("angelica:thaumcraft_portal").attachShader(vert).attachShader(frag).link(Uniforms::new); + } finally { + vert.delete(); + frag.delete(); + } + + final int previous = GLStateManager.getActiveProgram(); + final int handle = program.handle(); + GLStateManager.glUseProgram(handle); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(handle, "u_Tunnel"), TUNNEL_UNIT); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(handle, "u_Lightmap"), LIGHTMAP_UNIT); + GLStateManager.glUniform1i(GLStateManager.glGetUniformLocation(handle, "u_Field"), FIELD_UNIT); + GLStateManager.glUniform4f(GLStateManager.glGetUniformLocation(handle, "u_ObjectPlaneR"), 0.0F, 0.0F, 0.0F, 1.0F); + GLStateManager.glUniform3(GLStateManager.glGetUniformLocation(handle, "u_LayerColor"), floatBuffer(layerColors())); + GLStateManager.glUseProgram(previous); + return program; + } + + private static FloatBuffer floatBuffer(float[] values) { + final FloatBuffer buffer = BufferUtils.createFloatBuffer(values.length); + buffer.put(values).flip(); + return buffer; + } + + static float[] layerColors() { + final float[] colors = new float[LAYERS * 3]; + final Random random = new Random(31100L); + for (int i = 0; i < LAYERS; i++) { + final float f7 = i == 0 ? 0.1F : 1.0F / ((float) (16 - i) + 1.0F); + float red = random.nextFloat() * 0.5F + 0.1F; + float green = random.nextFloat() * 0.5F + 0.4F; + float blue = random.nextFloat() * 0.5F + 0.5F; + if (i == 0) red = green = blue = 1.0F; + colors[i * 3] = (int) (red * f7 * 255.0F) / 255.0F; + colors[i * 3 + 1] = (int) (green * f7 * 255.0F) / 255.0F; + colors[i * 3 + 2] = (int) (blue * f7 * 255.0F) / 255.0F; + } + return colors; + } + + void drawDirect(float[] faces, int count, int tunnelTexture, int fieldTexture, Frame frame, boolean fogged) { + final int fogMode = fogged ? fogMode() : 0; + final GlProgram program; + if (fogMode == 0) { + if (direct == null) direct = buildProgram(false, false); + program = direct; + } else { + if (directFogged == null) directFogged = buildProgram(false, true); + program = directFogged; + } + draw(program, faces, 0, count, tunnelTexture, fieldTexture, frame, fogMode); + } + + void drawCapture(float[] faces, int first, int count, int tunnelTexture, int fieldTexture, Frame frame) { + if (capture == null) capture = buildProgram(true, false); + draw(capture, faces, first, count, tunnelTexture, fieldTexture, frame, 0); + } + + GlFramebuffer atlasFramebuffer() { + if (atlasFramebuffer == null) { + atlasTexture = GLStateManager.glGenTextures(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, atlasTexture); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, ATLAS_SIZE, ATLAS_SIZE, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); + 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); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); + atlasFramebuffer = new GlFramebuffer(); + atlasFramebuffer.addColorAttachment(0, atlasTexture); + atlasFramebuffer.drawBuffers(new int[]{0}); + atlasFramebuffer.readBuffer(0); + if (!atlasFramebuffer.isComplete()) { + atlasFramebuffer.destroy(); + GLStateManager.glDeleteTextures(atlasTexture); + atlasFramebuffer = null; + atlasTexture = 0; + throw new IllegalStateException("Incomplete Thaumcraft portal atlas framebuffer"); + } + } + return atlasFramebuffer; + } + + int atlasTexture() { + return atlasTexture; + } + + void destroy() { + if (direct != null) direct.delete(); + if (directFogged != null) directFogged.delete(); + if (capture != null) capture.delete(); + direct = directFogged = capture = null; + if (vao != 0) GLStateManager.glDeleteVertexArrays(vao); + if (vbo != 0) GLStateManager.glDeleteBuffers(vbo); + if (ebo != 0) GLStateManager.glDeleteBuffers(ebo); + vao = vbo = ebo = 0; + if (atlasFramebuffer != null) atlasFramebuffer.destroy(); + if (atlasTexture != 0) GLStateManager.glDeleteTextures(atlasTexture); + atlasFramebuffer = null; + atlasTexture = 0; + } + + private void draw(GlProgram program, float[] faces, int first, int count, int tunnelTexture, int fieldTexture, Frame frame, int fogMode) { + final int previousProgram = GLStateManager.getActiveProgram(); + final int previousVao = GLStateManager.getBoundVAO(); + final int depth = GLStateManager.pushState(StateSet.forMask(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_TEXTURE_BIT)); + try { + GLStateManager.disableBlend(); + GLStateManager.glUseProgram(program.handle()); + final Uniforms uniforms = program.getInterface(); + if (uniforms.modelViewProjection != null) uniforms.modelViewProjection.set(frame.modelViewProjection); + if (uniforms.uploadedFrame != frame || uniforms.uploadedVersion != frame.version) { + uniforms.modelView.set(frame.modelView); + uniforms.eyePlane.set(frame.eyePlane); + uniforms.rowS.set(frame.rowS); + uniforms.rowT.set(frame.rowT); + uniforms.uploadedFrame = frame; + uniforms.uploadedVersion = frame.version; + uniforms.uploadedPlanes = 0; + } + if (uniforms.uploadedPlanes != frame.planeCount) { + final int floats = frame.planeCount * FLOATS_PER_PLANE; + if (planeUpload == null || planeUpload.capacity() < floats) planeUpload = BufferUtils.createFloatBuffer(maxPlanes() * FLOATS_PER_PLANE); + planeUpload.clear(); + planeUpload.put(frame.planeData, 0, floats).flip(); + uniforms.planes.set(planeUpload); + uniforms.uploadedPlanes = frame.planeCount; + } + uniforms.lightmapUv.set(frame.lightmapU, frame.lightmapV); + uniforms.lightmapEnabled.setFloat(frame.lightmapEnabled ? 1.0F : 0.0F); + if (uniforms.atlasSize != null) uniforms.atlasSize.setFloat(ATLAS_SIZE); + if (fogMode != 0) uploadFog(uniforms, fogMode); + + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + FIELD_UNIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, fieldTexture); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + TUNNEL_UNIT); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, tunnelTexture); + + uploadFaces(faces, first, count); + GLStateManager.glDrawElementsInstanced(GL11.GL_TRIANGLES, 6, GL11.GL_UNSIGNED_INT, 0L, count); + } finally { + GLStateManager.glBindVertexArray(previousVao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glUseProgram(previousProgram); + GLStateManager.popStateTo(depth); + } + } + + private void uploadFaces(float[] faces, int first, int count) { + if (upload == null || upload.capacity() < count * FLOATS_PER_FACE) { + upload = BufferUtils.createFloatBuffer(Math.max(count, 64) * FLOATS_PER_FACE); + } + upload.clear(); + upload.put(faces, first * FLOATS_PER_FACE, count * FLOATS_PER_FACE).flip(); + + if (vao == 0) createBuffers(); + GLStateManager.glBindVertexArray(vao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, upload, GL15.GL_STREAM_DRAW); + } + + private void createBuffers() { + vao = GLStateManager.glGenVertexArrays(); + vbo = GLStateManager.glGenBuffers(); + ebo = GLStateManager.glGenBuffers(); + GLStateManager.glBindVertexArray(vao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + for (int corner = 0; corner < 4; corner++) { + instanced(corner, 4, corner * 4); + } + final IntBuffer indices = BufferUtils.createIntBuffer(6); + indices.put(0).put(1).put(2).put(0).put(2).put(3).flip(); + GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ebo); + GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indices, GL15.GL_STATIC_DRAW); + } + + static final class Frame { + final Matrix4f modelViewProjection = new Matrix4f(); + final Matrix4f modelView = new Matrix4f(); + private final Matrix4f[] layerBase = new Matrix4f[3 * LAYERS]; + private final FloatBuffer rowS = BufferUtils.createFloatBuffer(3 * LAYERS * 3); + private final FloatBuffer rowT = BufferUtils.createFloatBuffer(3 * LAYERS * 3); + private final FloatBuffer eyePlane = BufferUtils.createFloatBuffer(3 * 3); + private final Matrix4f translated = new Matrix4f(); + private final Matrix4f texGenModelView = new Matrix4f(); + private final Matrix4f inverse = new Matrix4f(); + private final Vector4f lightmapCoord = new Vector4f(); + private final Matrix4f preparedModelView = new Matrix4f(); + float cameraX, cameraY, cameraZ; + float viewX, viewY, viewZ; + float time; + float lightmapU, lightmapV; + boolean lightmapEnabled; + private int[] planeAxis = new int[16]; + private boolean[] planeNegative = new boolean[16]; + private double[] planeValue = new double[16]; + private float[] planeData = new float[16 * FLOATS_PER_PLANE]; + private int planeCount; + private int version; + private float preparedCameraX, preparedCameraY, preparedCameraZ, preparedViewX, preparedViewY, preparedViewZ, preparedTime; + + Frame() { + for (int i = 0; i < layerBase.length; i++) layerBase[i] = new Matrix4f(); + } + + void prepareLayers() { + if (version != 0 && preparedCameraX == cameraX && preparedCameraY == cameraY && preparedCameraZ == cameraZ && preparedViewX == viewX && preparedViewY == viewY && preparedViewZ == viewZ && preparedTime == time && preparedModelView.equals(modelView)) + return; + preparedCameraX = cameraX; + preparedCameraY = cameraY; + preparedCameraZ = cameraZ; + preparedViewX = viewX; + preparedViewY = viewY; + preparedViewZ = viewZ; + preparedTime = time; + preparedModelView.set(modelView); + version++; + planeCount = 0; + for (int axis = 0; axis < 3; axis++) { + final float cameraS = axis == AXIS_X ? cameraZ : cameraX; + final float cameraT = axis == AXIS_Y ? cameraZ : cameraY; + final float cameraAxis = axis == AXIS_X ? cameraX : axis == AXIS_Y ? cameraY : cameraZ; + for (int i = 0; i < LAYERS; i++) { + final float scale = LAYER_SCALE[i]; + final Matrix4f base = layerBase[axis * LAYERS + i].identity().translate(0.0F, time, 0.0F).scale(scale, scale, scale).translate(0.5F, 0.5F, 0.0F).rotate(LAYER_ANGLE[i], 0.0F, 0.0F, 1.0F).translate(-0.5F, -0.5F, 0.0F).translate(-cameraS, -cameraT, -cameraAxis); + final int row = (axis * LAYERS + i) * 3; + rowS.put(row, base.m00()).put(row + 1, base.m10()).put(row + 2, base.m20()); + rowT.put(row, base.m01()).put(row + 1, base.m11()).put(row + 2, base.m21()); + } + } + texGenModelView.set(modelView).translate(cameraX, cameraY, cameraZ).invert(inverse); + eyePlane.put(0, inverse.m00()).put(1, inverse.m10()).put(2, inverse.m20()); + eyePlane.put(3, inverse.m01()).put(4, inverse.m11()).put(5, inverse.m21()); + eyePlane.put(6, inverse.m02()).put(7, inverse.m12()).put(8, inverse.m22()); + } + + void readLightmap(int blockLight) { + final TextureUnitArray textures = GLStateManager.getTextures(); + lightmapEnabled = textures.getTextureUnitStates(LIGHTMAP_UNIT).isEnabled() && textures.getTextureUnitBindings(LIGHTMAP_UNIT).getBinding() != 0; + textures.getTextureUnitMatrix(LIGHTMAP_UNIT).transform(lightmapCoord.set(blockLight, 0.0F, 0.0F, 1.0F)); + lightmapU = lightmapCoord.x / lightmapCoord.w; + lightmapV = lightmapCoord.y / lightmapCoord.w; + } + + int plane(int axis, boolean negative, double plane) { + for (int p = 0; p < planeCount; p++) { + if (planeAxis[p] == axis && planeNegative[p] == negative && planeValue[p] == plane) return p; + } + if (planeCount == maxPlanes()) return -1; + if (planeCount == planeAxis.length) { + planeAxis = Arrays.copyOf(planeAxis, planeCount * 2); + planeNegative = Arrays.copyOf(planeNegative, planeCount * 2); + planeValue = Arrays.copyOf(planeValue, planeCount * 2); + planeData = Arrays.copyOf(planeData, planeCount * 2 * FLOATS_PER_PLANE); + } + final int p = planeCount++; + planeAxis[p] = axis; + planeNegative[p] = negative; + planeValue[p] = plane; + + final float viewS = axis == AXIS_X ? viewZ : viewX; + final float viewT = axis == AXIS_Y ? viewZ : viewY; + final float viewAxis = axis == AXIS_X ? viewX : axis == AXIS_Y ? viewY : viewZ; + final float cameraAxis = axis == AXIS_X ? cameraX : axis == AXIS_Y ? cameraY : cameraZ; + // TC's drawPlane* arithmetic, in its float order + final float f8 = (float) (negative ? -plane : plane); + final float f9 = negative ? f8 + viewAxis : f8 - viewAxis; + final int base = p * FLOATS_PER_PLANE; + for (int layer = 0; layer < LAYERS; layer++) { + final float f5 = LAYER_DEPTH[layer]; + layerBase[axis * LAYERS + layer].translate(viewS * f5 / f9, viewT * f5 / f9, -cameraAxis, translated); + planeData[base + layer * 2] = translated.m30(); + planeData[base + layer * 2 + 1] = translated.m31(); + + final float f10 = negative ? f8 + f5 + viewAxis : f8 + f5 - viewAxis; + float f11 = f9 / f10; + f11 += (float) plane; + // glTexGen stores the Q plane through the inverse of the modelview TC translated just before + texGenModelView.set(modelView).translate(axis == AXIS_X ? f11 : cameraX, axis == AXIS_Y ? f11 : cameraY, axis == AXIS_X || axis == AXIS_Y ? cameraZ : f11).invert(inverse); + planeData[base + LAYERS * 2 + layer] = axis == AXIS_X ? inverse.m30() : axis == AXIS_Y ? inverse.m31() : inverse.m32(); + } + return p; + } + + void clearPlanes() { + planeCount = 0; + version++; + } + } + + private static final class Uniforms { + final GlUniformMatrix4f modelViewProjection; + final GlUniformMatrix4f modelView; + final GlUniformFloat3Array eyePlane; + final GlUniformFloat3Array rowS; + final GlUniformFloat3Array rowT; + final GlUniformFloat4Array planes; + final GlUniformFloat2v lightmapUv; + final GlUniformFloat lightmapEnabled; + final GlUniformFloat atlasSize; + final GlUniformFloat4v fogParams; + final GlUniformFloat3v fogColor; + final GlUniformInt fogMode; + final GlUniformInt fogDistanceMode; + Frame uploadedFrame; + int uploadedVersion; + int uploadedPlanes; + + Uniforms(ShaderBindingContext context) { + modelViewProjection = context.bindUniformIfPresent("u_ModelViewProjection", GlUniformMatrix4f::new); + modelView = context.bindUniform("u_ModelView", GlUniformMatrix4f::new); + eyePlane = context.bindUniform("u_EyePlane", GlUniformFloat3Array::new); + rowS = context.bindUniform("u_RowS", GlUniformFloat3Array::new); + rowT = context.bindUniform("u_RowT", GlUniformFloat3Array::new); + planes = context.bindUniform("u_Planes", GlUniformFloat4Array::new); + lightmapUv = context.bindUniform("u_LightmapUv", GlUniformFloat2v::new); + lightmapEnabled = context.bindUniform("u_LightmapEnabled", GlUniformFloat::new); + atlasSize = context.bindUniformIfPresent("u_AtlasSize", GlUniformFloat::new); + fogParams = context.bindUniformIfPresent("u_FogParams", GlUniformFloat4v::new); + fogColor = context.bindUniformIfPresent("u_FogColor", GlUniformFloat3v::new); + fogMode = context.bindUniformIfPresent("u_FogMode", GlUniformInt::new); + fogDistanceMode = context.bindUniformIfPresent("u_FogDistanceMode", GlUniformInt::new); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalFaces.java b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalFaces.java new file mode 100644 index 000000000..e6ab6907d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalFaces.java @@ -0,0 +1,113 @@ +package com.gtnewhorizons.angelica.compat.thaumcraft; + +import net.minecraft.block.Block; +import net.minecraft.world.IBlockAccess; +import thaumcraft.common.config.ConfigBlocks; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Y; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Z; + +/** + * Which of a portable hole's or eldritch nothing's six planes TC draws, and where. + */ +public final class PortalFaces { + public static final int NOT_BUILT = -1; + + private static final int UP = 1; + private static final int DOWN = 2; + private static final int NORTH = 4; + private static final int SOUTH = 8; + private static final int WEST = 16; + private static final int EAST = 32; + + private static final float HOLE_NEAR = 0.001F; + private static final float HOLE_FAR = 0.999F; + private static final float HOLE_FAR_GRAY = 0.5F; + private static final float NOTHING_FAR_GRAY = 1.0F; + + private PortalFaces() { + } + + public static int holeMask(IBlockAccess world, int x, int y, int z) { + int mask = 0; + if (isHoleWall(world.getBlock(x, y + 1, z))) mask |= UP; + if (isHoleWall(world.getBlock(x, y - 1, z))) mask |= DOWN; + if (isHoleWall(world.getBlock(x, y, z - 1))) mask |= NORTH; + if (isHoleWall(world.getBlock(x, y, z + 1))) mask |= SOUTH; + if (isHoleWall(world.getBlock(x - 1, y, z))) mask |= WEST; + if (isHoleWall(world.getBlock(x + 1, y, z))) mask |= EAST; + return mask; + } + + public static int nothingMask(IBlockAccess world, int x, int y, int z) { + int mask = 0; + if (!world.getBlock(x, y + 1, z).isOpaqueCube()) mask |= UP; + if (!world.getBlock(x, y - 1, z).isOpaqueCube()) mask |= DOWN; + if (!world.getBlock(x, y, z - 1).isOpaqueCube()) mask |= NORTH; + if (!world.getBlock(x, y, z + 1).isOpaqueCube()) mask |= SOUTH; + if (!world.getBlock(x - 1, y, z).isOpaqueCube()) mask |= WEST; + if (!world.getBlock(x + 1, y, z).isOpaqueCube()) mask |= EAST; + return mask; + } + + private static boolean isHoleWall(Block block) { + return block.isOpaqueCube() && block != ConfigBlocks.blockHole; + } + + public static void addHoleFaces(int mask, boolean layered, double x, double y, double z) { + if ((mask & UP) != 0) { + final double plane = y + HOLE_FAR; + face(layered, HOLE_FAR_GRAY, AXIS_Y, false, plane, x, plane, z + 1.0, x, plane, z, x + 1.0, plane, z + 1.0); + } + if ((mask & DOWN) != 0) { + final double plane = y + HOLE_NEAR; + face(layered, HOLE_FAR_GRAY, AXIS_Y, true, plane, x, plane, z, x, plane, z + 1.0, x + 1.0, plane, z); + } + if ((mask & NORTH) != 0) { + final double plane = z + HOLE_NEAR; + face(layered, HOLE_FAR_GRAY, AXIS_Z, true, plane, x, y + 1.0, plane, x, y, plane, x + 1.0, y + 1.0, plane); + } + if ((mask & SOUTH) != 0) { + final double plane = z + HOLE_FAR; + face(layered, HOLE_FAR_GRAY, AXIS_Z, false, plane, x, y, plane, x, y + 1.0, plane, x + 1.0, y, plane); + } + if ((mask & WEST) != 0) { + final double plane = x + HOLE_NEAR; + face(layered, HOLE_FAR_GRAY, AXIS_X, true, plane, plane, y + 1.0, z, plane, y + 1.0, z + 1.0, plane, y, z); + } + if ((mask & EAST) != 0) { + final double plane = x + HOLE_FAR; + face(layered, HOLE_FAR_GRAY, AXIS_X, false, plane, plane, y, z, plane, y, z + 1.0, plane, y + 1.0, z); + } + } + + public static void addNothingFaces(int mask, boolean layered, double x, double y, double z) { + if ((mask & UP) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_Y, true, y + 1.0, x, y + 1.0, z, x, y + 1.0, z + 1.0, x + 1.0, y + 1.0, z); + } + if ((mask & DOWN) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_Y, false, y, x, y, z + 1.0, x, y, z, x + 1.0, y, z + 1.0); + } + if ((mask & NORTH) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_Z, false, z, x, y, z, x, y + 1.0, z, x + 1.0, y, z); + } + if ((mask & SOUTH) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_Z, true, z + 1.0, x, y + 1.0, z + 1.0, x, y, z + 1.0, x + 1.0, y + 1.0, z + 1.0); + } + if ((mask & WEST) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_X, false, x, x, y, z, x, y, z + 1.0, x, y + 1.0, z); + } + if ((mask & EAST) != 0) { + face(layered, NOTHING_FAR_GRAY, AXIS_X, true, x + 1.0, x + 1.0, y + 1.0, z, x + 1.0, y + 1.0, z + 1.0, x + 1.0, y, z); + } + } + + private static void face(boolean layered, float farGray, int axis, boolean negative, double plane, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + if (layered) { + PortalRenderer.addFace(false, axis, negative, plane, x0, y0, z0, x1, y1, z1, x3, y3, z3); + } else { + PortalRenderer.addFarFace(axis, farGray, x0, y0, z0, x1, y1, z1, x3, y3, z3); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalRenderer.java b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalRenderer.java new file mode 100644 index 000000000..213cedd82 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalRenderer.java @@ -0,0 +1,467 @@ +package com.gtnewhorizons.angelica.compat.thaumcraft; + +import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.StateSet; +import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard; +import com.gtnewhorizons.angelica.glsm.profiling.Tracy; +import com.gtnewhorizons.angelica.glsm.states.ViewportState; +import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws; +import com.gtnewhorizons.angelica.rendering.tesr.TesrProviderDispatch; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; +import net.coderbot.iris.pipeline.ShadowRenderer; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ActiveRenderInfo; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.ITextureObject; +import net.minecraft.client.renderer.texture.SimpleTexture; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector4f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL30; +import thaumcraft.common.tiles.TileEldritchLock; +import thaumcraft.common.tiles.TileEldritchNothing; +import thaumcraft.common.tiles.TileHole; + +import java.util.Arrays; + +/** + * Draws Thaumcraft's end-portal-style planes (eldritch obelisk, nothing, lock, portable hole, mirror) in one pass. + */ +public final class PortalRenderer implements PendingTesrDraws.Pending { + public static final int AXIS_X = 0; + public static final int AXIS_Y = 1; + public static final int AXIS_Z = 2; + + private static final ResourceLocation TUNNEL = new ResourceLocation("thaumcraft", "textures/misc/tunnel.png"); + private static final ResourceLocation FIELD = new ResourceLocation("thaumcraft", "textures/misc/particlefield.png"); + private static final ResourceLocation FAR_FIELD = new ResourceLocation("thaumcraft", "textures/misc/particlefield32.png"); + private static final int FULL_BRIGHT = 240 | (240 << 16); + private static final int TC_BRIGHTNESS = 180; + private static final double LAYERED_RANGE_SQUARED = 512.0D; + private static final Matrix4fc IDENTITY = new Matrix4f(); + private static final Tracy.ZoneId Z_FLUSH = Tracy.zoneId("thaumcraftPortals", Tracy.COLOR_CLIENT); + + private static final int MODE_DIRECT = 0; + private static final int MODE_CAPTURE = 1; + private static final int MODE_SHADOW = 2; + + private static final PortalRenderer INSTANCE = new PortalRenderer(); + private static final PortalDrawer drawer = new PortalDrawer(); + private static final PortalDrawer.Frame frame = new PortalDrawer.Frame(); + private static final Matrix4f modelViewProjection = new Matrix4f(); + private static final Matrix4f savedTextureMatrix = new Matrix4f(); + private static final Vector4f projected = new Vector4f(); + private static final float[] screenX = new float[4]; + private static final float[] screenY = new float[4]; + + private static float[] faces = new float[PortalDrawer.FLOATS_PER_FACE * 64]; + private static int[] faceBlockEntity = new int[64]; + private static int faceCount; + private static float[] farFaces = new float[PortalDrawer.FLOATS_PER_FACE * 64]; + private static float[] farGray = new float[64]; + private static int[] farBlockEntity = new int[64]; + private static int farCount; + private static int batchMode; + private static boolean batchFogged; + private static int batchModelViewGeneration; + private static int batchProjectionGeneration; + private static boolean skippedPlaneState; + private static int lastPlaneTexture; + private static int tunnelTexture; + private static int fieldTexture; + private static int farTexture; + + private PortalRenderer() { + } + + public static boolean replacesLayers() { + return !DisplayListManager.isRecording(); + } + + public static boolean inLayeredRange(TileEntity te) { + return Minecraft.getMinecraft().renderViewEntity.getDistanceSq(te.xCoord + 0.5D, te.yCoord + 0.5D, te.zCoord + 0.5D) < LAYERED_RANGE_SQUARED; + } + + public static void addFace(int axis, boolean negative, double plane, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + addFace(GLStateManager.getFogMode().isEnabled(), axis, negative, plane, x0, y0, z0, x1, y1, z1, x3, y3, z3); + } + + static void addFace(boolean fogged, int axis, boolean negative, double plane, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + prepareBatch(fogged); + int planeIndex = 0; + if (batchMode != MODE_SHADOW) { + planeIndex = frame.plane(axis, negative, plane); + if (planeIndex < 0) { + flushFaces(); + frame.clearPlanes(); + planeIndex = frame.plane(axis, negative, plane); + } + } + putLayeredFace(axis, planeIndex, x0, y0, z0, x1, y1, z1, x3, y3, z3); + lastPlaneTexture = fieldTexture; + } + + static void addFarFace(int axis, float gray, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + prepareBatch(false); + lastPlaneTexture = farTexture; + if (batchMode == MODE_SHADOW) { + putLayeredFace(axis, 0, x0, y0, z0, x1, y1, z1, x3, y3, z3); + return; + } + if (farCount == farBlockEntity.length) { + farFaces = Arrays.copyOf(farFaces, farFaces.length * 2); + farGray = Arrays.copyOf(farGray, farGray.length * 2); + farBlockEntity = Arrays.copyOf(farBlockEntity, farBlockEntity.length * 2); + } + PortalDrawer.putFace(farFaces, farCount, axis, 0, x0, y0, z0, x1, y1, z1, x3, y3, z3); + farGray[farCount] = gray; + farBlockEntity[farCount] = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); + farCount++; + skippedPlaneState = true; + } + + public static void drawBuilt(TileEntity te, boolean hole, int mask, double x, double y, double z) { + PendingTesrDraws.beforeTileEntity(te); + if (mask == 0) return; + final CapturedRenderingState rendering = CapturedRenderingState.INSTANCE; + rendering.pushCurrentBlockEntity(); + try { + rendering.setCurrentBlockEntity(te.getBlockType(), TesrProviderDispatch.blockMetadata(te)); + if (hole) { + PortalFaces.addHoleFaces(mask, inLayeredRange(te), x, y, z); + } else { + PortalFaces.addNothingFaces(mask, inLayeredRange(te), x, y, z); + } + } finally { + rendering.popCurrentBlockEntity(); + } + skippedPlaneState = false; + if (PendingTesrDraws.canDefer()) { + PendingTesrDraws.hold(INSTANCE); + } else { + flushFaces(); + } + } + + public static void endSkippedRender() { + if (!GLStateManager.glIsEnabled(GL11.GL_FOG)) GLStateManager.glEnable(GL11.GL_FOG); + } + + private static void prepareBatch(boolean fogged) { + if ((faceCount > 0 || farCount > 0) && fogged != batchFogged) flushFaces(); + batchFogged = fogged; + final int modelViewGeneration = GLStateManager.getMvGeneration(); + final int projectionGeneration = GLStateManager.getProjGeneration(); + final boolean empty = faceCount == 0 && farCount == 0; + if (empty || modelViewGeneration != batchModelViewGeneration || projectionGeneration != batchProjectionGeneration) { + final int mode = currentMode(); + GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), modelViewProjection); + if (!empty && (mode != batchMode || !modelViewProjection.equals(frame.modelViewProjection))) flushFaces(); + if (faceCount == 0 && farCount == 0) startBatch(mode); + batchModelViewGeneration = modelViewGeneration; + batchProjectionGeneration = projectionGeneration; + } + } + + private static void putLayeredFace(int axis, int planeIndex, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + if (faceCount == faceBlockEntity.length) { + faces = Arrays.copyOf(faces, faces.length * 2); + faceBlockEntity = Arrays.copyOf(faceBlockEntity, faceBlockEntity.length * 2); + } + PortalDrawer.putFace(faces, faceCount, axis, planeIndex, x0, y0, z0, x1, y1, z1, x3, y3, z3); + faceBlockEntity[faceCount] = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); + faceCount++; + skippedPlaneState = true; + } + + private static void restoreSkippedPlaneState() { + if (!skippedPlaneState) return; + skippedPlaneState = false; + if (GLStateManager.glIsEnabled(GL11.GL_BLEND)) GLStateManager.disableBlend(); + if (GLStateManager.glIsEnabled(GL11.GL_TEXTURE_GEN_S)) GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_S); + if (GLStateManager.glIsEnabled(GL11.GL_TEXTURE_GEN_T)) GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_T); + if (GLStateManager.glIsEnabled(GL11.GL_TEXTURE_GEN_R)) GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_R); + if (GLStateManager.glIsEnabled(GL11.GL_TEXTURE_GEN_Q)) GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_Q); + if (!GLStateManager.glIsEnabled(GL11.GL_LIGHTING)) GLStateManager.enableLighting(); + if (GLStateManager.getTextures().getTextureUnitBindings(GLStateManager.getActiveTextureUnit()).getBinding() != lastPlaneTexture) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, lastPlaneTexture); + } + } + + public static void drawBeforeOverlay() { + restoreSkippedPlaneState(); + flushFaces(); + } + + public static void endTileEntity(boolean canWait) { + restoreSkippedPlaneState(); + if (faceCount == 0 && farCount == 0) return; + if (canWait && PendingTesrDraws.canDefer()) { + PendingTesrDraws.hold(INSTANCE); + } else { + flushFaces(); + } + } + + private static void flushFaces() { + if (faceCount == 0 && farCount == 0) return; + if (Tracy.ENABLED) Tracy.beginZone(Z_FLUSH); + try { + if (faceCount > 0) { + switch (batchMode) { + case MODE_CAPTURE -> captureAndComposite(tunnelTexture, fieldTexture); + case MODE_SHADOW -> drawQuads(tunnelTexture, 0, faceCount, false); + default -> drawer.drawDirect(faces, faceCount, tunnelTexture, fieldTexture, frame, batchFogged); + } + } + if (farCount > 0) drawFarFaces(); + } finally { + faceCount = 0; + farCount = 0; + if (Tracy.ENABLED) Tracy.endZone(); + } + } + + private static int currentMode() { + if (ShadowRenderer.ACTIVE) return MODE_SHADOW; + return capturingPipeline() != null ? MODE_CAPTURE : MODE_DIRECT; + } + + private static DeferredWorldRenderingPipeline capturingPipeline() { + if (!Iris.enabled) return null; + return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline pipeline && pipeline.shouldOverrideShaders() ? pipeline : null; + } + + private static void startBatch(int mode) { + batchMode = mode; + tunnelTexture = textureId(TUNNEL); + fieldTexture = textureId(FIELD); + farTexture = textureId(FAR_FIELD); + frame.modelViewProjection.set(modelViewProjection); + if (mode == MODE_SHADOW) return; + frame.modelView.set(GLStateManager.getModelViewMatrix()); + frame.cameraX = (float) TileEntityRendererDispatcher.staticPlayerX; + frame.cameraY = (float) TileEntityRendererDispatcher.staticPlayerY; + frame.cameraZ = (float) TileEntityRendererDispatcher.staticPlayerZ; + frame.viewX = ActiveRenderInfo.objectX; + frame.viewY = ActiveRenderInfo.objectY; + frame.viewZ = ActiveRenderInfo.objectZ; + frame.time = (float) (System.currentTimeMillis() % 700000L) / 250000.0F; + frame.prepareLayers(); + frame.readLightmap(TC_BRIGHTNESS); + } + + private static void captureAndComposite(int tunnel, int field) { + final DeferredWorldRenderingPipeline pipeline = capturingPipeline(); + if (pipeline == null) { + drawer.drawDirect(faces, faceCount, tunnel, field, frame, batchFogged); + return; + } + final ViewportState viewport = GLStateManager.getViewportState(); + int first = 0, x = 0, y = 0, rowHeight = 0; + for (int face = 0; face < faceCount; face++) { + final int size = slotSize(face, viewport.width, viewport.height); + if (x + size > PortalDrawer.ATLAS_SIZE) { + x = 0; + y += rowHeight; + rowHeight = 0; + } + if (y + size > PortalDrawer.ATLAS_SIZE) { + capture(pipeline, first, face - first, tunnel, field); + drawQuads(drawer.atlasTexture(), first, face - first, true); + first = face; + x = y = rowHeight = 0; + } + final int i = face * PortalDrawer.FLOATS_PER_FACE; + faces[i + 7] = x; + faces[i + 11] = y; + faces[i + 15] = size; + x += size; + rowHeight = Math.max(rowHeight, size); + } + capture(pipeline, first, faceCount - first, tunnel, field); + drawQuads(drawer.atlasTexture(), first, faceCount - first, true); + } + + private static int slotSize(int face, int viewportWidth, int viewportHeight) { + final int i = face * PortalDrawer.FLOATS_PER_FACE; + float largest = 0.0F; + for (int corner = 0; corner < 4; corner++) { + final int c = i + corner * 4; + frame.modelViewProjection.transform(projected.set(faces[c], faces[c + 1], faces[c + 2], 1.0F)); + if (projected.w <= 1.0E-4F) return PortalDrawer.MAX_SLOT; + screenX[corner] = projected.x / projected.w * 0.5F * viewportWidth; + screenY[corner] = projected.y / projected.w * 0.5F * viewportHeight; + } + for (int corner = 0; corner < 4; corner++) { + final int next = (corner + 1) & 3; + largest = Math.max(largest, Math.max(Math.abs(screenX[next] - screenX[corner]), Math.abs(screenY[next] - screenY[corner]))); + } + final int pixels = (int) Math.ceil(largest); + final int size = pixels <= 1 ? 1 : Integer.highestOneBit(pixels - 1) << 1; + return Math.clamp(size, PortalDrawer.MIN_SLOT, PortalDrawer.MAX_SLOT); + } + + private static void capture(DeferredWorldRenderingPipeline pipeline, int first, int count, int tunnel, int field) { + BatchStateGuard.beforeChange(); + final int drawFramebuffer = GLStateManager.getDrawFramebuffer(); + final int readFramebuffer = GLStateManager.getReadFramebuffer(); + pipeline.setIsMainBound(false); + final int depth = GLStateManager.pushState(StateSet.forMask(GL11.GL_VIEWPORT_BIT | GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT)); + try { + drawer.atlasFramebuffer().bind(); + GLStateManager.glViewport(0, 0, PortalDrawer.ATLAS_SIZE, PortalDrawer.ATLAS_SIZE); + GLStateManager.disableDepthTest(); + GLStateManager.disableCull(); + GLStateManager.glDisable(GL11.GL_SCISSOR_TEST); + GLStateManager.glDisable(GL11.GL_STENCIL_TEST); + GLStateManager.glColorMask(true, true, true, true); + drawer.drawCapture(faces, first, count, tunnel, field, frame); + } finally { + GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, drawFramebuffer); + GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, readFramebuffer); + GLStateManager.popStateTo(depth); + pipeline.setIsMainBound(true); + pipeline.rebindCurrentPass(); + } + } + + private static void drawQuads(int texture, int first, int count, boolean fromAtlas) { + final int depth = GLStateManager.pushState(StateSet.forMask(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_TEXTURE_BIT)); + savedTextureMatrix.set(GLStateManager.getTextures().getTextureUnitMatrix(0)); + CapturedRenderingState.INSTANCE.pushCurrentBlockEntity(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.enableTexture(); + GLStateManager.disableLighting(); + GLStateManager.disableBlend(); + if (!batchFogged) disableFogUntilPop(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); + GLStateManager.setTextureMatrix(0, IDENTITY); + final Tessellator tess = Tessellator.instance; + final float texel = 1.0F / PortalDrawer.ATLAS_SIZE; + int runStart = first; + while (runStart < first + count) { + final int blockEntity = faceBlockEntity[runStart]; + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntity); + tess.startDrawingQuads(); + tess.setColorOpaque_F(1, 1, 1); + tess.setBrightness(FULL_BRIGHT); + int face = runStart; + for (; face < first + count && faceBlockEntity[face] == blockEntity; face++) { + if (fromAtlas) { + final int i = face * PortalDrawer.FLOATS_PER_FACE; + final float x = faces[i + 7], y = faces[i + 11], size = faces[i + 15]; + addQuad(tess, face, (x + 0.5F) * texel, (y + 0.5F) * texel, (x + size - 0.5F) * texel, (y + size - 0.5F) * texel); + } else { + addQuad(tess, face, 0.0F, 0.0F, 1.0F, 1.0F); + } + } + tess.draw(); + runStart = face; + } + if (fromAtlas) BatchStateGuard.beforeChange(); + } finally { + CapturedRenderingState.INSTANCE.popCurrentBlockEntity(); + GLStateManager.setTextureMatrix(0, savedTextureMatrix); + popStateTo(depth); + } + } + + private static void drawFarFaces() { + final int depth = GLStateManager.pushState(StateSet.forMask(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_TEXTURE_BIT)); + CapturedRenderingState.INSTANCE.pushCurrentBlockEntity(); + try { + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.enableTexture(); + GLStateManager.disableLighting(); + GLStateManager.disableBlend(); + disableFogUntilPop(); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, farTexture); + final Tessellator tess = Tessellator.instance; + final float[] f = farFaces; + int runStart = 0; + while (runStart < farCount) { + final int blockEntity = farBlockEntity[runStart]; + CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntity); + tess.startDrawingQuads(); + tess.setBrightness(TC_BRIGHTNESS); + int face = runStart; + for (; face < farCount && farBlockEntity[face] == blockEntity; face++) { + final int i = face * PortalDrawer.FLOATS_PER_FACE; + tess.setColorRGBA_F(farGray[face], farGray[face], farGray[face], 1.0F); + tess.addVertexWithUV(f[i], f[i + 1], f[i + 2], 1.0D, 1.0D); + tess.addVertexWithUV(f[i + 4], f[i + 5], f[i + 6], 1.0D, 0.0D); + tess.addVertexWithUV(f[i + 8], f[i + 9], f[i + 10], 0.0D, 0.0D); + tess.addVertexWithUV(f[i + 12], f[i + 13], f[i + 14], 0.0D, 1.0D); + } + tess.draw(); + runStart = face; + } + } finally { + CapturedRenderingState.INSTANCE.popCurrentBlockEntity(); + popStateTo(depth); + } + } + + private static void disableFogUntilPop() { + BatchStateGuard.suspend(); + try { + GLStateManager.glDisable(GL11.GL_FOG); + } finally { + BatchStateGuard.resume(); + } + } + + private static void popStateTo(int depth) { + BatchStateGuard.suspend(); + try { + GLStateManager.popStateTo(depth); + } finally { + BatchStateGuard.resume(); + } + } + + private static void addQuad(Tessellator tess, int face, float u0, float v0, float u1, float v1) { + final float[] f = faces; + final int i = face * PortalDrawer.FLOATS_PER_FACE; + final float ax = f[i + 4] - f[i], ay = f[i + 5] - f[i + 1], az = f[i + 6] - f[i + 2]; + final float bx = f[i + 12] - f[i], by = f[i + 13] - f[i + 1], bz = f[i + 14] - f[i + 2]; + final float nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx; + final float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); + tess.setNormal(nx / length, ny / length, nz / length); + tess.addVertexWithUV(f[i], f[i + 1], f[i + 2], u0, v0); + tess.addVertexWithUV(f[i + 4], f[i + 5], f[i + 6], u1, v0); + tess.addVertexWithUV(f[i + 8], f[i + 9], f[i + 10], u1, v1); + tess.addVertexWithUV(f[i + 12], f[i + 13], f[i + 14], u0, v1); + } + + private static int textureId(ResourceLocation location) { + final TextureManager textures = Minecraft.getMinecraft().getTextureManager(); + ITextureObject texture = textures.getTexture(location); + if (texture == null) { + texture = new SimpleTexture(location); + textures.loadTexture(location, texture); + } + return texture.getGlTextureId(); + } + + @Override + public boolean canWaitFor(TileEntity next) { + return next instanceof TileEldritchNothing || next instanceof TileHole || next instanceof TileEldritchLock; + } + + @Override + public void flush() { + flushFaces(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/dynamiclights/ChunkRebuildManager.java b/src/main/java/com/gtnewhorizons/angelica/dynamiclights/ChunkRebuildManager.java index e5273a44b..e7b5b0544 100644 --- a/src/main/java/com/gtnewhorizons/angelica/dynamiclights/ChunkRebuildManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/dynamiclights/ChunkRebuildManager.java @@ -35,8 +35,8 @@ public class ChunkRebuildManager { final long packed = CoordinatePacker.pack(x, y, z); lock.writeLock().lock(); try { - // Reset wait counter if already pending, otherwise add new entry - pendingRebuilds.put(packed, 0); + // An already pending section keeps its wait count + pendingRebuilds.putIfAbsent(packed, 0); } finally { lock.writeLock().unlock(); } @@ -125,11 +125,8 @@ public class ChunkRebuildManager { int blockY = chunkY << 4; int blockZ = chunkZ << 4; - // Check if the 16x16x16 chunk section box is visible - return viewport.isBoxVisible( - blockX, blockY, blockZ, - blockX + 16, blockY + 16, blockZ + 16 - ); + // The integer-origin overload takes a center and half-size, not min/max corners. + return viewport.isBoxVisible(blockX + 8, blockY + 8, blockZ + 8, 8.0f); } public void clear() { diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisDisplayListState.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisDisplayListState.java index 17f534966..1d39d8631 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisDisplayListState.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisDisplayListState.java @@ -20,6 +20,9 @@ import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + /** * Records Java-side rendering scopes alongside cached geometry. */ @@ -28,24 +31,36 @@ public final class IrisDisplayListState { private IrisDisplayListState() {} public static void runProgramTransition(Runnable transition) { + runProgramTransition((run, unused) -> run.run(), transition, null); + } + + public static void runProgramTransition(Consumer transition, T argument) { + runProgramTransition(Consumer::accept, transition, argument); + } + + public static void runProgramTransition(BiConsumer transition, A first, B second) { BatchStateGuard.suspend(); try { - runUnrecorded(transition); + runUnrecorded(transition, first, second); } finally { BatchStateGuard.resume(); } } public static void runUnrecorded(Runnable transition) { + runUnrecorded((run, unused) -> run.run(), transition, null); + } + + private static void runUnrecorded(BiConsumer transition, A first, B second) { final DisplayListManager.RecordMode mode = DisplayListManager.getRecordMode(); if (mode == DisplayListManager.RecordMode.COMPILE) return; if (mode == DisplayListManager.RecordMode.NONE) { - transition.run(); + transition.accept(first, second); return; } final CommandRecorder recorder = DisplayListManager.pauseRecording(); try { - transition.run(); + transition.accept(first, second); } finally { DisplayListManager.resumeRecording(recorder); } diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java index 1f81c2684..17edc50d3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java @@ -7,6 +7,7 @@ import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler; import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler; import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig; import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks; +import com.gtnewhorizons.angelica.glsm.hooks.LineDrawHandler; import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor; import com.gtnewhorizons.angelica.glsm.shader.ShaderType; import org.taumc.glsl.grammar.GLSLParser; @@ -103,6 +104,24 @@ public class IrisGLSMBridge { GLSMConfig.expandVertexFormats = Iris.enabled; IrisSamplers.initRenderer(); installPostTransformHook(); + GLSMHooks.lineDrawHandler = new LineDrawHandler() { + private DeferredWorldRenderingPipeline linePipeline; + + @Override + public boolean bindLineProgram() { + if (!Iris.enabled || !(Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) || !drp.bindLineProgram()) { + return false; + } + linePipeline = drp; + return true; + } + + @Override + public void restoreProgram() { + linePipeline.restoreAfterLines(); + linePipeline = null; + } + }; GLSMHooks.blendHandler = new DeferredBlendHandler() { @Override public boolean isBlendLocked() { diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 76892647e..1a43d4a71 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -229,6 +229,20 @@ public enum Mixins implements IMixins { .addClientMixins("client.thaumcraft.MixinItemThaumometerRenderer") ), + THAUMCRAFT_PORTALS(new MixinBuilder("Draw Thaumcraft's end portal styled planes in a more optimized way, and make it work with shaderpacks") + .setPhase(Phase.LATE) + .addRequiredMod(TargetedMod.THAUMCRAFT) + .addClientMixins( + "client.thaumcraft.MixinTileEldritchObeliskRenderer", + "client.thaumcraft.MixinTileEldritchNothingRenderer", + "client.thaumcraft.MixinTileEldritchLockRenderer", + "client.thaumcraft.MixinTileHoleRenderer", + "client.thaumcraft.MixinTileMirrorRenderer", + "client.thaumcraft.MixinTileHole", + "client.thaumcraft.MixinTileEldritchNothing", + "client.thaumcraft.MixinBlockHole") + ), + THAUMCRAFT_TESR_JAR_CACHE(new MixinBuilder("Batch TC4 jar liquid via the retained TESR mesh cache") .setPhase(Phase.LATE) .setApplyIf(() -> AngelicaConfig.enableTESRJarCache) diff --git a/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java index 86d781872..a801c0c03 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/SelectionBoxRenderer.java @@ -6,14 +6,13 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.Color4; -import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat2v; +import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer; import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.util.AxisAlignedBB; import org.embeddedt.embeddium.impl.gl.shader.GlProgram; import org.embeddedt.embeddium.impl.gl.shader.GlShader; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; import org.embeddedt.embeddium.impl.gl.shader.ShaderType; -import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; @@ -27,6 +26,7 @@ public final class SelectionBoxRenderer { private static GlProgram program; private static IVertexArrayObject vao; + private static ByteBuffer edges; private static final Matrix4f mvpMatrix = new Matrix4f(); private static final float[] colorBuf = new float[4]; @@ -43,31 +43,17 @@ public final class SelectionBoxRenderer { private SelectionBoxRenderer() {} public static void init() { - final boolean needsGS = GLStateManager.wideLineEmulationEnabled && GLStateManager.supportsGeometryShaders(); - final GlShader vs = ShaderLoader.loadShader(ShaderType.VERTEX, "angelica:selection_box.vert.glsl", ShaderConstants.EMPTY); final GlShader fs = ShaderLoader.loadShader(ShaderType.FRAGMENT, "angelica:selection_box.frag.glsl", ShaderConstants.EMPTY); - final GlProgram.Builder builder = GlProgram.builder("SelectionBox").attachShader(vs).attachShader(fs); - - GlShader gs = null; - if (needsGS) { - gs = ShaderLoader.loadShader(ShaderType.GEOM, "angelica:selection_box.geom.glsl", ShaderConstants.EMPTY); - builder.attachShader(gs); - } - - program = builder.link(ctx -> new SelectionBoxUniforms( + program = GlProgram.builder("SelectionBox").attachShader(vs).attachShader(fs).link(ctx -> new SelectionBoxUniforms( ctx.bindUniform("u_MVP", GlUniformMatrix4f::new), - ctx.bindUniform("u_Color", GlUniformFloat4v::new), - needsGS ? ctx.bindUniform("u_ViewportSize", GlUniformFloat2v::new) : null, - needsGS ? ctx.bindUniform("u_LineWidth", GlUniformFloat::new) : null)); - + ctx.bindUniform("u_Color", GlUniformFloat4v::new))); vs.destroy(); fs.destroy(); - if (gs != null) gs.destroy(); - final ByteBuffer buf = BufferUtils.createByteBuffer(UNIT_EDGES.length * Float.BYTES); - buf.asFloatBuffer().put(UNIT_EDGES); - vao = VertexBufferType.IMMUTABLE.allocate(DefaultVertexFormat.POSITION, GL11.GL_LINES, buf, VERT_COUNT); + edges = BufferUtils.createByteBuffer(UNIT_EDGES.length * Float.BYTES); + edges.asFloatBuffer().put(UNIT_EDGES); + vao = VertexBufferType.IMMUTABLE.allocate(DefaultVertexFormat.POSITION, GL11.GL_LINES, edges, VERT_COUNT); } public static void draw(AxisAlignedBB aabb, int color) { @@ -78,8 +64,8 @@ public final class SelectionBoxRenderer { final float extY = (float) (aabb.maxY - aabb.minY); final float extZ = (float) (aabb.maxZ - aabb.minZ); - if (AngelicaConfig.enableIris && IrisApi.getInstance().isShaderPackInUse()) { - drawThroughShader(minX, minY, minZ, extX, extY, extZ, color); + if (GLStateManager.wideLineEmulationEnabled || (AngelicaConfig.enableIris && IrisApi.getInstance().isShaderPackInUse())) { + drawAsLines(minX, minY, minZ, extX, extY, extZ, color); } else { drawFast(minX, minY, minZ, extX, extY, extZ, color); } @@ -108,31 +94,29 @@ public final class SelectionBoxRenderer { } uniforms.color.set(colorBuf); - if (uniforms.viewportSize != null) { - uniforms.viewportSize.set(GLStateManager.getViewportState().width, GLStateManager.getViewportState().height); - uniforms.lineWidth.setFloat(GLStateManager.getLineState().getWidth()); - } - vao.render(); program.unbind(); } - private static void drawThroughShader(float minX, float minY, float minZ, float extX, float extY, float extZ, int color) { + // The streaming drawer's line path widens the edges in the FFP vertex shader or sends them to a pack's gbuffers_line + private static void drawAsLines(float minX, float minY, float minZ, float extX, float extY, float extZ, int color) { GLStateManager.glPushMatrix(); GLStateManager.glTranslatef(minX, minY, minZ); GLStateManager.glScalef(extX, extY, extZ); final Color4 prev = GLStateManager.getColor(); + final float prevRed = prev.getRed(), prevGreen = prev.getGreen(), prevBlue = prev.getBlue(), prevAlpha = prev.getAlpha(); final boolean overrideColor = color != -1; if (overrideColor) { GLStateManager.glColor4f(((color >> 16) & 0xFF) / 255.0f, ((color >> 8) & 0xFF) / 255.0f, (color & 0xFF) / 255.0f, 1.0f); } - vao.render(); + edges.clear(); + TessellatorStreamingDrawer.drawPacked(edges, GL11.GL_LINES, DefaultVertexFormat.POSITION.getVertexFlags(), VERT_COUNT); if (overrideColor) { - GLStateManager.glColor4f(prev.getRed(), prev.getGreen(), prev.getBlue(), prev.getAlpha()); + GLStateManager.glColor4f(prevRed, prevGreen, prevBlue, prevAlpha); } GLStateManager.glPopMatrix(); } @@ -148,7 +132,7 @@ public final class SelectionBoxRenderer { } } - private record SelectionBoxUniforms(GlUniformMatrix4f mvp, GlUniformFloat4v color, GlUniformFloat2v viewportSize, GlUniformFloat lineWidth) { + private record SelectionBoxUniforms(GlUniformMatrix4f mvp, GlUniformFloat4v color) { } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java index 4e92af010..46f000030 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaBuiltRenderSectionData.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.rendering.celeritas; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; @@ -10,14 +11,24 @@ import java.util.Arrays; public class AngelicaBuiltRenderSectionData extends MinecraftBuiltRenderSectionData { public static final float[] EMPTY_BOUNDS = new float[0]; + private static final SectionBuiltBlockEntity[] NO_SECTION_BUILT = new SectionBuiltBlockEntity[0]; public float[] culledBlockEntityBounds = EMPTY_BOUNDS; + public SectionBuiltBlockEntity[] sectionBuilt = NO_SECTION_BUILT; + public int[] sectionBuiltResults; + public double maxTeRenderDistSq = Double.POSITIVE_INFINITY; public int cullEpoch = -1; public int cullVerdict; + public void applySectionBuilt() { + for (int i = 0; i < sectionBuilt.length; i++) { + sectionBuilt[i].angelica$applySectionResult(sectionBuiltResults[i]); + } + } + public static void packSectionLocalBounds(FloatArrayList out, AxisAlignedBB aabb, int originX, int originY, int originZ) { out.add((float) (aabb.minX - originX)); out.add((float) (aabb.minY - originY)); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java index 73acf3f8a..9cdca2b67 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java @@ -11,10 +11,12 @@ import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext; import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVertexEncoder; import com.gtnewhorizons.angelica.rendering.celeritas.threading.RenderPassHelper; import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.utils.NaturalTextureUtils; import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; @@ -173,6 +175,8 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask sectionBuilt = null; + IntArrayList sectionBuiltResults = null; double maxTeRenderDistSq = 0; final RenderBlocks renderBlocks = new RenderBlocks(region); @@ -199,6 +203,14 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask(); + sectionBuiltResults = new IntArrayList(); + } + sectionBuilt.add(built); + sectionBuiltResults.add(built.angelica$prepareFromSection(region)); + } final boolean isGlobal; AxisAlignedBB aabb = null; final byte boundsClass = TileEntityRenderBoundsRegistry.classify(tileEntity); @@ -279,6 +291,10 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask createRebuildTask(RenderSection render, int frame) { if (isSectionVisuallyEmpty(render.getChunkX(), render.getChunkY(), render.getChunkZ())) { 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 8164afe5d..5cc453f3d 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java @@ -57,6 +57,8 @@ import com.gtnewhorizons.angelica.render.WeatherRenderer; import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller; import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; @@ -415,6 +417,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer 0) { - return dynamicLightsInstance.getLightmapWithDynamicLight(dynamicLevel, lightmap); - } - return lightmap; - } - return skyBrightness << 20 | blockBrightness << 4; } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PendingTesrDraws.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PendingTesrDraws.java new file mode 100644 index 000000000..dc2e9d556 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/PendingTesrDraws.java @@ -0,0 +1,51 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import net.minecraft.tileentity.TileEntity; + +/** + * Lets a block entity renderer keep geometry pending across consecutive block entities of its own kind during the + * block entity pass. + */ +public final class PendingTesrDraws { + + private static Pending pending; + private static boolean inPass; + + private PendingTesrDraws() { + } + + public static boolean canDefer() { + return inPass; + } + + public static void hold(Pending owner) { + if (pending != owner) flush(); + pending = owner; + } + + public static void beforeTileEntity(TileEntity next) { + if (pending != null && !pending.canWaitFor(next)) flush(); + } + + public static void beginPass() { + inPass = true; + } + + public static void endPass() { + inPass = false; + flush(); + } + + public static void flush() { + final Pending owner = pending; + if (owner == null) return; + pending = null; + owner.flush(); + } + + public interface Pending { + boolean canWaitFor(TileEntity next); + + void flush(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/SectionBuiltBlockEntity.java b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/SectionBuiltBlockEntity.java new file mode 100644 index 000000000..50e316bea --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/tesr/SectionBuiltBlockEntity.java @@ -0,0 +1,12 @@ +package com.gtnewhorizons.angelica.rendering.tesr; + +import net.minecraft.world.IBlockAccess; + +public interface SectionBuiltBlockEntity { + + int angelica$prepareFromSection(IBlockAccess world); + + void angelica$applySectionResult(int prepared); + + boolean angelica$drawBuilt(double x, double y, double z); +} diff --git a/src/main/java/net/coderbot/iris/Iris.java b/src/main/java/net/coderbot/iris/Iris.java index c23195713..fddc3d0c6 100644 --- a/src/main/java/net/coderbot/iris/Iris.java +++ b/src/main/java/net/coderbot/iris/Iris.java @@ -898,8 +898,9 @@ public class Iris { PerFrameUniformBlockHarvester.harvest(programs); final DeferredWorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs); try { - // Both are otherwise built lazily on first draw, after this pipeline is gone + // These are otherwise built lazily on first draw, after this pipeline is gone pipeline.compileInstancedVariants(); + pipeline.compileWideLinePrograms(); if (IrisShaderProviderHolder.getProvider() instanceof IrisCeleritasShaderProvider terrain) { terrain.compileTerrainPrograms(pipeline.getCeleritasTerrainPipeline()); } diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java index bec8342fe..7ab3cfeb0 100644 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java +++ b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java @@ -21,6 +21,7 @@ public enum RenderCondition { RAIN_SNOW, WORLD_BORDER, LIGHTNING, + LINES, SHADOW_TRANSLUCENT, // NB: Must be last due to implementation details of DeferredWorldRenderingPipeline SHADOW diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 00eaae5a8..37299f8f9 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -189,6 +189,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private final Map, Map> attributeTransforms; private final EnumMap, Map>> instancedAttributeTransforms = new EnumMap<>(Instancing.class); private final boolean[] supportsInstancing = initialInstancingSupport(); + private final Map, Map> wideLineTransforms = new HashMap<>(); + private final Map wideLinePrograms = new HashMap<>(); + private final boolean packWidensLines; private final ParityFlipState parityState = new ParityFlipState(AngelicaConfig.shaderParityFlip); private final Supplier> flippedGbuffers; private final Supplier> flippedShadowGbuffers; @@ -266,6 +269,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R resolver = new ProgramFallbackResolver(programs); final Map mvBuiltinsMemo = new ConcurrentHashMap<>(); final Map, CompletableFuture>> attributeTransformFutures = submitAttributeTransforms(resolver, attributeProgramIds(Instancing.NONE), Instancing.NONE, mvBuiltinsMemo); + packWidensLines = programs.get(ProgramId.Line).isPresent(); + final Map, CompletableFuture>> wideLineTransformFutures = submitWideLineTransforms(resolver, packWidensLines); final EnumMap, CompletableFuture>>> instancedTransformFutures = new EnumMap<>(Instancing.class); for (Instancing kind : Instancing.VALUES) { if (kind != Instancing.NONE) { @@ -502,6 +507,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // world border uses textured_lit even though it has no lightmap :/ null, ProgramId.TexturedLit, ProgramId.TexturedLit, ProgramId.Lightning, ProgramId.Lightning, ProgramId.Lightning, + ProgramId.Line, ProgramId.Line, ProgramId.Line, ProgramId.ShadowWater, ProgramId.ShadowWater, ProgramId.ShadowWater, ProgramId.Shadow, ProgramId.Shadow, ProgramId.Shadow }; @@ -522,6 +528,14 @@ 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(); + for (Map.Entry, CompletableFuture>> entry : wideLineTransformFutures.entrySet()) { + try { + this.wideLineTransforms.put(entry.getKey(), entry.getValue().join()); + } catch (Exception e) { + Iris.logger.warn("Wide line transform failed for {}; lines there stay 1 px wide!", entry.getKey().getLeft(), e); + } + } + for (Map.Entry, CompletableFuture>>> kindEntry : instancedTransformFutures.entrySet()) { final Instancing kind = kindEntry.getKey(); final Map, Map> joined = new HashMap<>(); @@ -546,7 +560,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R final Map builtPrograms = new HashMap<>(); - this.table = new ProgramTable<>((condition, availability) -> { + this.table = new ProgramTable<>((condition, requested) -> { + final InputAvailability availability = condition == RenderCondition.LINES ? LINE_INPUTS : requested; final ProgramId finalId = gbufferProgramId(ids, condition, availability); return cachedPasses.computeIfAbsent(Pair.of(finalId, availability), p -> { @@ -1046,6 +1061,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R /** Availability used for every shadow pass draw and for the shadow program lookups at load time. */ private static final InputAvailability SHADOW_INPUTS = InputAvailability.of(true, true); + private static final InputAvailability LINE_INPUTS = InputAvailability.NONE; + @Override public void onEntityRenderBoundary() { GLSMHooks.resolvePendingProgram(); @@ -1061,7 +1078,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } public void beginPass(Pass pass) { - IrisDisplayListState.runProgramTransition(() -> beginPassNow(pass)); + IrisDisplayListState.runProgramTransition(DeferredWorldRenderingPipeline::beginPassNow, this, pass); } private void beginPassNow(Pass pass) { @@ -1399,6 +1416,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private boolean instancingShadow; private final Program[] instancedVariants = new Program[Instancing.VALUES.length]; private final boolean[] instancedVariantAttempted = new boolean[Instancing.VALUES.length]; + @Nullable + private WideLineProgram wideLineProgram; + private boolean wideLineProgramAttempted; private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents, @Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List bufferBlendOverrides, boolean shadowViewport) { @@ -1412,7 +1432,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } public void use() { - IrisDisplayListState.runProgramTransition(this::useNow); + IrisDisplayListState.runProgramTransition(Pass::useNow, this); + } + + void rebindProgram() { + if (program != null) program.use(); + DeferredWorldRenderingPipeline.this.customUniforms.push(this); } private void useNow() { @@ -1494,6 +1519,17 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return instancedVariants[i]; } + @Nullable + WideLineProgram wideLineProgram() { + if (!wideLineProgramAttempted) { + wideLineProgramAttempted = true; + if (instancingSourceName != null) { + wideLineProgram = sharedWideLineProgram(instancingSourceName, instancingAvailability, instancingShadow); + } + } + return wideLineProgram; + } + public void destroy() { if (this.program != null) { this.program.destroy(); @@ -1568,6 +1604,98 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R this.customUniforms.push(variant); } + private record WideLineProgram(Program program, int lineWidthLocation, int screenSizeLocation) {} + + @Nullable + private WideLineProgram sharedWideLineProgram(String sourceName, InputAvailability availability, boolean shadow) { + final SharedProgramKey key = new SharedProgramKey(sourceName, availability, shadow); + if (wideLinePrograms.containsKey(key)) return wideLinePrograms.get(key); + final WideLineProgram built = buildWideLineProgram(sourceName, availability, shadow); + wideLinePrograms.put(key, built); + return built; + } + + @Nullable + private WideLineProgram buildWideLineProgram(String sourceName, InputAvailability availability, boolean shadow) { + final Map transformed = wideLineTransforms.get(Pair.of(sourceName, availability)); + if (transformed == null) { + return null; + } + final String name = sourceName + "_widelines"; + try { + final ProgramBuilder builder = beginBuilder(name, transformed); + wireGbufferProgram(builder, availability, shadow); + final Program program = builder.build(); + vertexWriteReplays.attach(name, program, transformed, (samplers, images) -> wireGbufferResources(samplers, images, availability, shadow)); + this.customUniforms.mapholderToPass(builder, program); + final int id = program.getProgramId(); + return new WideLineProgram(program, GLStateManager.glGetUniformLocation(id, "iris_LineWidth"), GLStateManager.glGetUniformLocation(id, "iris_ScreenSize")); + } catch (Exception e) { + Iris.logger.warn("Wide line program link failed for {}; lines there stay 1 px wide", sourceName, e); + return null; + } + } + + @Nullable + private Pass passBeforeLines; + + public boolean bindLineProgram() { + if (!shouldOverrideShaders() || DisplayListManager.isRecording()) { + return false; + } + GLSMHooks.resolvePendingProgram(); + final Pass pass = current; + if (pass == null || pass.getProgram() == null || activeInstancing != Instancing.NONE + || GLStateManager.getActiveProgram() != pass.getProgram().getProgramId()) { + return false; + } + + final boolean shadow = currentCondition == RenderCondition.SHADOW || currentCondition == RenderCondition.SHADOW_TRANSLUCENT; + final Pass linePass = shadow ? pass : table.match(RenderCondition.LINES, LINE_INPUTS); + if (linePass.getProgram() == null) { + return false; + } + final boolean needsWidening = shadow || !packWidensLines; + final WideLineProgram wide = needsWidening ? linePass.wideLineProgram() : null; + if (needsWidening && wide == null) { + return false; + } + + passBeforeLines = pass; + if (linePass != pass) { + beginPass(linePass); + } + if (wide != null) { + wide.program().use(); + this.customUniforms.push(wide.program()); + final var viewport = GLStateManager.getViewportState(); + RenderSystem.uniform1f(wide.lineWidthLocation(), GLStateManager.getLineState().getWidth()); + RenderSystem.uniform2f(wide.screenSizeLocation(), viewport.width, viewport.height); + } + return true; + } + + public void restoreAfterLines() { + final Pass previous = passBeforeLines; + passBeforeLines = null; + if (previous == null) { + return; + } + if (current != previous) { + beginPass(previous); + } else { + previous.rebindProgram(); + } + } + + public void compileWideLinePrograms() { + table.match(RenderCondition.LINES, LINE_INPUTS).wideLineProgram(); + final Pass shadowPass = table.match(RenderCondition.SHADOW, SHADOW_INPUTS); + if (shadowPass != null) shadowPass.wideLineProgram(); + final Pass shadowWaterPass = table.match(RenderCondition.SHADOW_TRANSLUCENT, SHADOW_INPUTS); + if (shadowWaterPass != null) shadowWaterPass.wideLineProgram(); + } + @Override public void destroy() { clearPendingSelection(); @@ -1612,6 +1740,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } } } + for (WideLineProgram wide : wideLinePrograms.values()) { + if (wide != null) wide.program().destroy(); + } vertexWriteReplays.destroy(); if (shadowVoxelizationCompute != null) { shadowVoxelizationCompute.destroy(); @@ -2444,6 +2575,31 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return futures; } + private static Map, CompletableFuture>> + submitWideLineTransforms(ProgramFallbackResolver resolver, boolean packWidensLines) { + final Map, CompletableFuture>> futures = new HashMap<>(); + if (!packWidensLines) { + submitWideLineTransform(futures, resolver.resolveNullable(ProgramId.Line), LINE_INPUTS); + } + submitWideLineTransform(futures, resolver.resolveNullable(ProgramId.Shadow), SHADOW_INPUTS); + submitWideLineTransform(futures, resolver.resolveNullable(ProgramId.ShadowWater), SHADOW_INPUTS); + return futures; + } + + private static void submitWideLineTransform(Map, CompletableFuture>> futures, + @Nullable ProgramSource source, InputAvailability inputs) { + if (source == null || futures.containsKey(Pair.of(source.getName(), inputs))) { + return; + } + futures.put(Pair.of(source.getName(), inputs), Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributesWideLines( + source.getVertexSource().orElse(null), + source.getGeometrySource().orElse(null), + source.getTessControlSource().orElse(null), + source.getTessEvalSource().orElse(null), + source.getFragmentSource().orElse(null), + inputs))); + } + private static final ProgramId[] INSTANCED_PROGRAM_IDS = { ProgramId.Block, ProgramId.BlockTrans, ProgramId.Entities, ProgramId.EntitiesTrans, ProgramId.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint @@ -2469,7 +2625,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R private static final String[] MV_BUILTINS = { "gl_ModelViewMatrix", "gl_ModelViewMatrixInverse", "gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixInverse", - "gl_NormalMatrix", "ftransform" + "gl_NormalMatrix", "ftransform", + "modelViewMatrix", "modelViewMatrixInverse", "normalMatrix" }; static boolean referencesMvBuiltins(String source) { diff --git a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java index abd7d0433..f5fe5a616 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java @@ -10,6 +10,8 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.profiling.RenderClassTimings; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; +import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import com.gtnewhorizons.angelica.rendering.tesr.TileEntityLight; import com.gtnewhorizons.angelica.glsm.RenderSystem; @@ -771,8 +773,13 @@ public class ShadowRenderer { } } } + if (tile instanceof SectionBuiltBlockEntity built && built.angelica$drawBuilt( + (double) tile.xCoord - cameraX, (double) tile.yCoord - cameraY, (double) tile.zCoord - cameraZ)) { + return; + } final World world = tile.getWorldObj(); int brightness = TileEntityLight.packedLight(world, tile.xCoord, tile.yCoord, tile.zCoord, world.getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0)); + PendingTesrDraws.beforeTileEntity(tile); GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, (float) brightness % 65536, (float) brightness / 65536); GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); TileEntityRendererDispatcher.instance.renderTileEntityAt(tile, @@ -808,6 +815,7 @@ public class ShadowRenderer { GbufferPrograms.beginBlockEntities(); GbufferPrograms.setBlockEntityDefaults(); ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES, true); + PendingTesrDraws.beginPass(); for (int b = 0, bn = visibleTileEntities.size(); b < bn; b++) { final List bucket = visibleTileEntities.get(b); @@ -840,6 +848,7 @@ public class ShadowRenderer { } } + PendingTesrDraws.endPass(); flushShadowModelParts(); TesrBatchRenderer.INSTANCE.flush(); 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 42fbce45a..11da23b66 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -11,7 +11,9 @@ import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLParser; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; /** * Implements AttributeShaderTransformer using glsl-transformer AST @@ -39,17 +41,28 @@ class AttributeTransformer { final boolean cubeVertex = vertex && parameters.instancing == Instancing.CUBE; final boolean particleVertex = vertex && parameters.instancing == Instancing.PARTICLE; final boolean weatherVertex = vertex && parameters.instancing == Instancing.WEATHER; + final boolean lineVertex = vertex && parameters.wideLines; final boolean matrixVertex = vertex && parameters.instancing.hasInstanceHead(); - final boolean wantsMvInverse = matrixVertex && transformer.containsCall("gl_ModelViewMatrixInverse"); + final Set declaredInterface = declaredInterface(transformer); CoreTransformHelper.injectMatrixUniforms(transformer, vertex ? parameters.instancing : Instancing.NONE); - aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix"); - aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix"); - aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix"); + CORE_PROFILE_MATRICES.forEach((name, irisName) -> { + if (claimCoreProfileName(transformer, declaredInterface, name)) { + transformer.rename(name, irisName); + } + }); + final boolean wantsMvInverse = matrixVertex && transformer.containsCall("iris_ModelViewMatrixInverse"); if (parameters.type == ShaderType.VERTEX) { + mapCoreProfileInputs(transformer, declaredInterface); + if (!particleVertex && !weatherVertex) { - transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); + if (lineVertex) { + transformer.injectVariable("layout(location = 0) in vec4 iris_LineVertex;"); + transformer.injectVariable("vec4 iris_Vertex = vec4(0.0, 0.0, 0.0, 1.0);"); + } else { + 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;"); @@ -62,15 +75,16 @@ class AttributeTransformer { transformer.injectVariable("layout(location = " + SECONDARY_UV + ") in vec4 iris_MultiTexCoord1;"); } } - transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); + if (lineVertex) { + transformer.injectVariable("layout(location = 4) in vec3 iris_LineDirection;"); + transformer.injectVariable("const vec3 iris_Normal = vec3(0.0, 0.0, 1.0);"); + } else { + transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); + } transformer.rename("gl_Vertex", "iris_Vertex"); 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")) { - transformer.replaceExpression("vaPosition", "iris_Vertex.xyz"); - } // ftransform() = gl_ModelViewProjectionMatrix * gl_Vertex transformer.renameFunctionCall("ftransform", "iris_ftransform"); @@ -129,6 +143,42 @@ class AttributeTransformer { transformer.prependMain(init.toString()); } } + + if (parameters.wideLines) { + widenLines(transformer, vertex); + } + } + + private static void widenLines(Transformer transformer, boolean vertex) { + transformer.injectVariable("const mat4 iris_VIEW_SCALE = mat4(mat3(1.0 - (1.0 / 256.0)));"); + transformer.replaceExpression("iris_ModelViewMatrix", "(iris_VIEW_SCALE * iris_ModelViewMatrix)", GLSLParser::postfix_expression); + if (!vertex) { + return; + } + + transformer.injectVariable("uniform float iris_LineWidth;"); + transformer.injectVariable("uniform vec2 iris_ScreenSize;"); + transformer.rename("main", "irisMain"); + transformer.injectAtEnd("void iris_widen_lines(vec4 linePosStart, vec4 linePosEnd) {" + + " vec3 ndc1 = linePosStart.xyz / linePosStart.w;" + + " vec3 ndc2 = linePosEnd.xyz / linePosEnd.w;" + + " vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * iris_ScreenSize);" + + " vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * iris_LineWidth / iris_ScreenSize;" + + " if (lineOffset.x < 0.0) { lineOffset *= -1.0; }" + + " if (gl_VertexID % 2 == 0) {" + + " gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + + " } else {" + + " gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + + " } }"); + transformer.injectAtEnd("void main() {" + + " iris_Vertex = iris_LineVertex + vec4(iris_LineDirection, 0.0);" + + " irisMain();" + + " vec4 linePosEnd = gl_Position;" + + " gl_Position = vec4(0.0);" + + " iris_Vertex = iris_LineVertex;" + + " irisMain();" + + " vec4 linePosStart = gl_Position;" + + " iris_widen_lines(linePosStart, linePosEnd); }"); } private static final int PRIMARY_UV = VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(); @@ -200,9 +250,47 @@ class AttributeTransformer { transformer.replaceExpression(name, replacement); } - private static void aliasIfUsed(Transformer transformer, String modernName, String irisName) { - if (transformer.containsCall(modernName) && !transformer.hasVariable(modernName)) { - transformer.rename(modernName, irisName); + private static final Map CORE_PROFILE_MATRICES = Map.of( + "projectionMatrix", "iris_ProjectionMatrix", + "projectionMatrixInverse", "iris_ProjectionMatrixInverse", + "modelViewMatrix", "iris_ModelViewMatrix", + "modelViewMatrixInverse", "iris_ModelViewMatrixInverse", + "normalMatrix", "iris_NormalMatrix", + "textureMatrix", "iris_TextureMatrix"); + + private static Set declaredInterface(Transformer transformer) { + final Set names = new HashSet<>(transformer.findQualifiers(GLSLLexer.UNIFORM).keySet()); + names.addAll(transformer.findQualifiers(GLSLLexer.IN).keySet()); + names.addAll(transformer.findQualifiers(GLSLLexer.ATTRIBUTE).keySet()); + return names; + } + + private static boolean claimCoreProfileName(Transformer transformer, Set declaredInterface, String name) { + if (!transformer.containsCall(name)) { + return false; + } + if (declaredInterface.contains(name)) { + transformer.removeVariable(name); + return true; + } + return !transformer.hasVariable(name); + } + + private static void mapCoreProfileInputs(Transformer transformer, Set declaredInterface) { + final boolean overlayIsInt = transformer.findType("vaUV1") == GLSLLexer.IVEC2; + final boolean lightIsInt = transformer.findType("vaUV2") == GLSLLexer.IVEC2; + mapCoreProfileInput(transformer, declaredInterface, "vaPosition", "gl_Vertex.xyz"); + mapCoreProfileInput(transformer, declaredInterface, "vaColor", "gl_Color"); + mapCoreProfileInput(transformer, declaredInterface, "vaNormal", "gl_Normal"); + mapCoreProfileInput(transformer, declaredInterface, "vaUV0", "gl_MultiTexCoord0.xy"); + // There is no overlay attribute (entityColor carries the hurt tint), so every vertex reads "no overlay" + mapCoreProfileInput(transformer, declaredInterface, "vaUV1", overlayIsInt ? "ivec2(0, 10)" : "vec2(0.0, 10.0)"); + mapCoreProfileInput(transformer, declaredInterface, "vaUV2", lightIsInt ? "ivec2(gl_MultiTexCoord1.xy)" : "gl_MultiTexCoord1.xy"); + } + + private static void mapCoreProfileInput(Transformer transformer, Set declaredInterface, String name, String replacement) { + if (claimCoreProfileName(transformer, declaredInterface, name)) { + transformer.replaceExpression(name, replacement, GLSLParser::postfix_expression); } } } 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 c77da2ae0..f0114afe0 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -146,6 +146,10 @@ public class TransformPatcher { return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, instancing)); } + public static Map patchAttributesWideLines(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) { + return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, false, Instancing.NONE, true)); + } + public static Map patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) { return patchAttributes(vertex, geometry, tessControl, tessEval, fragment, inputs, false); } 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 8c729589e..be359161d 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 @@ -12,15 +12,21 @@ public class AttributeParameters extends Parameters { public final InputAvailability inputs; public final boolean scrollGlint; public final Instancing instancing; + public final boolean wideLines; // WARNING: adding new fields requires updating hashCode and equals methods! public AttributeParameters(Patch patch, boolean hasGeometry, boolean hasTesselation, InputAvailability inputs, boolean scrollGlint, Instancing instancing) { + this(patch, hasGeometry, hasTesselation, inputs, scrollGlint, instancing, false); + } + + public AttributeParameters(Patch patch, boolean hasGeometry, boolean hasTesselation, InputAvailability inputs, boolean scrollGlint, Instancing instancing, boolean wideLines) { super(patch, null); this.hasGeometry = hasGeometry; this.hasTesselation = hasTesselation; this.inputs = inputs; this.scrollGlint = scrollGlint; this.instancing = instancing; + this.wideLines = wideLines; } @Override @@ -31,7 +37,7 @@ public class AttributeParameters extends Parameters { @Override public void appendDiskKey(ShaderDiskCache.Key k) { super.appendDiskKey(k); - k.b(hasGeometry).b(hasTesselation).str(inputs == null ? null : inputs.name()).b(scrollGlint).str(instancing.name()); + k.b(hasGeometry).b(hasTesselation).str(inputs == null ? null : inputs.name()).b(scrollGlint).str(instancing.name()).b(wideLines); } @Override @@ -42,6 +48,7 @@ public class AttributeParameters extends Parameters { result = prime * result + (hasTesselation ? 1231 : 1237); result = prime * result + (scrollGlint ? 1231 : 1237); result = prime * result + instancing.ordinal(); + result = prime * result + (wideLines ? 1231 : 1237); result = prime * result + ((inputs == null) ? 0 : inputs.hashCode()); return result; } @@ -63,11 +70,10 @@ public class AttributeParameters extends Parameters { return false; if (instancing != other.instancing) return false; - if (inputs == null) { - if (other.inputs != null) - return false; - } else if (!inputs.equals(other.inputs)) + if (wideLines != other.wideLines) return false; - return true; - } + if (inputs == null) { + return other.inputs == null; + } else return inputs.equals(other.inputs); + } } diff --git a/src/main/resources/assets/angelica/shaders/selection_box.geom.glsl b/src/main/resources/assets/angelica/shaders/selection_box.geom.glsl deleted file mode 100644 index d052031f0..000000000 --- a/src/main/resources/assets/angelica/shaders/selection_box.geom.glsl +++ /dev/null @@ -1,34 +0,0 @@ -#version 330 core - -layout(lines) in; -layout(triangle_strip, max_vertices = 4) out; - -uniform vec2 u_ViewportSize; -uniform float u_LineWidth; - -void main() { - vec4 c0 = gl_in[0].gl_Position; - vec4 c1 = gl_in[1].gl_Position; - - float d0 = c0.z + c0.w; - float d1 = c1.z + c1.w; - if (d0 < 0.0 && d1 < 0.0) return; - vec4 p0 = d0 < 0.0 ? mix(c0, c1, d0 / (d0 - d1)) : c0; - vec4 p1 = d1 < 0.0 ? mix(c0, c1, d0 / (d0 - d1)) : c1; - - vec2 n0 = p0.xy / p0.w; - vec2 n1 = p1.xy / p1.w; - - vec2 dir = normalize((n1 - n0) * u_ViewportSize); - vec2 offset = vec2(-dir.y, dir.x) * u_LineWidth / u_ViewportSize; - - gl_Position = vec4((n0 + offset) * p0.w, p0.z, p0.w); - EmitVertex(); - gl_Position = vec4((n0 - offset) * p0.w, p0.z, p0.w); - EmitVertex(); - gl_Position = vec4((n1 + offset) * p1.w, p1.z, p1.w); - EmitVertex(); - gl_Position = vec4((n1 - offset) * p1.w, p1.z, p1.w); - EmitVertex(); - EndPrimitive(); -} diff --git a/src/main/resources/assets/angelica/shaders/thaumcraft_portal.frag b/src/main/resources/assets/angelica/shaders/thaumcraft_portal.frag new file mode 100644 index 000000000..24ddec681 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/thaumcraft_portal.frag @@ -0,0 +1,47 @@ +#version 330 core + +in vec3 v_Tex[16]; +flat in vec4 v_Light; + +uniform sampler2D u_Tunnel; +uniform sampler2D u_Field; +uniform vec3 u_LayerColor[16]; + +#ifdef FOG +in float v_FogCoord; +uniform vec4 u_FogParams; +uniform vec3 u_FogColor; +uniform int u_FogMode; +#endif + +out vec4 fragColor; + +// TC blends each layer into an 8-bit framebuffer, which rounds after every blend; rounding the same way keeps the sum +// on the same steps. +vec3 store8(vec3 color) { + return floor(clamp(color, 0.0, 1.0) * 255.0 + 0.5) / 255.0; +} + +void main() { +#ifdef FOG + float f; + if (u_FogMode == 1) { + f = v_FogCoord * u_FogParams.x + u_FogParams.y; + } else if (u_FogMode == 2) { + f = exp2(-(v_FogCoord * u_FogParams.z)); + } else { + float fogTmp = v_FogCoord * u_FogParams.w; + f = exp2(-(fogTmp * fogTmp)); + } + f = clamp(f, 0.0, 1.0); + // Fixed function fogs each layer's draw before it blends, so every additive layer adds its own share of fog color + #define LAYER(rgb) mix(u_FogColor, (rgb), f) +#else + #define LAYER(rgb) (rgb) +#endif + vec3 color = store8(LAYER((vec4(u_LayerColor[0], 1.0) * textureProj(u_Tunnel, v_Tex[0]) * v_Light).rgb)); + for (int i = 1; i < 16; i++) { + color = store8(color + LAYER((vec4(u_LayerColor[i], 1.0) * textureProj(u_Field, v_Tex[i]) * v_Light).rgb)); + } + fragColor = vec4(color, 1.0); +} diff --git a/src/main/resources/assets/angelica/shaders/thaumcraft_portal.vert b/src/main/resources/assets/angelica/shaders/thaumcraft_portal.vert new file mode 100644 index 000000000..bb34319e6 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/thaumcraft_portal.vert @@ -0,0 +1,76 @@ +#version 330 core + +// One instance per face, TC's four vertices in TC's order. a_Corner0.w is axis + 4 * plane index (axis 0 X, 1 Y, 2 Z); +// when capturing, the w of corners 1 to 3 is the face's atlas slot: x, y and size in atlas pixels. +layout(location = 0) in vec4 a_Corner0; +layout(location = 1) in vec4 a_Corner1; +layout(location = 2) in vec4 a_Corner2; +layout(location = 3) in vec4 a_Corner3; + +// 12 vec4s per plane, built on the CPU with GLStateManager's float operations so they match bit for bit: 8 of texture +// matrix translations (m30, m31), two layers each, then 4 of the w glTexGen stores in the Q eye plane, four layers each. +uniform vec4 u_Planes[MAX_PLANES * 12]; + +uniform mat4 u_ModelViewProjection; +uniform mat4 u_ModelView; +// TC's R texgen plane, (0, 0, 0, 1). A uniform rather than a constant, so the compiler cannot fold the texture matrix +// product into a different rounding order than fixed function's. +uniform vec4 u_ObjectPlaneR; +uniform vec3 u_EyePlane[3]; +uniform vec3 u_RowS[48]; +uniform vec3 u_RowT[48]; +uniform sampler2D u_Lightmap; +uniform vec2 u_LightmapUv; +uniform float u_LightmapEnabled; +#ifdef CAPTURE +uniform float u_AtlasSize; +#endif +#ifdef FOG +uniform int u_FogDistanceMode; +out float v_FogCoord; +#endif + +out vec3 v_Tex[16]; +flat out vec4 v_Light; + +const vec2 SLOT_CORNERS[4] = vec2[](vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(1.0, 1.0), vec2(0.0, 1.0)); + +vec2 objectLinearST(vec3 v, int axis) { + return axis == 0 ? v.zy : (axis == 1 ? v.xz : v.xy); +} + +void main() { + vec3 corners[4] = vec3[](a_Corner0.xyz, a_Corner1.xyz, a_Corner2.xyz, a_Corner3.xyz); + vec4 pos4 = vec4(corners[gl_VertexID], 1.0); + vec4 eyePos = u_ModelView * pos4; + + int axisAndPlane = int(a_Corner0.w); + int axis = axisAndPlane & 3; + int plane = (axisAndPlane >> 2) * 12; + vec2 st = objectLinearST(pos4.xyz, axis); + float r = dot(pos4, u_ObjectPlaneR); + vec3 eyePlane = u_EyePlane[axis]; + + for (int i = 0; i < 16; i++) { + float q = dot(eyePos, vec4(eyePlane, u_Planes[plane + 8 + (i >> 2)][i & 3])); + vec3 rowS = u_RowS[axis * 16 + i]; + vec3 rowT = u_RowT[axis * 16 + i]; + vec4 pair = u_Planes[plane + (i >> 1)]; + vec2 translation = (i & 1) == 0 ? pair.xy : pair.zw; + mat4 textureMatrix = mat4(vec4(rowS.x, rowT.x, 0.0, 0.0), vec4(rowS.y, rowT.y, 0.0, 0.0), + vec4(rowS.z, rowT.z, 1.0, 0.0), vec4(translation, 0.0, 1.0)); + v_Tex[i] = (textureMatrix * vec4(st, r, q)).xyw; + } + + v_Light = u_LightmapEnabled > 0.5 ? texture(u_Lightmap, u_LightmapUv) : vec4(1.0); +#ifdef FOG + v_FogCoord = u_FogDistanceMode == 0 ? length(eyePos.xyz) : (u_FogDistanceMode == 1 ? eyePos.z : abs(eyePos.z)); +#endif + +#ifdef CAPTURE + vec2 slot = vec2(a_Corner1.w, a_Corner2.w) + SLOT_CORNERS[gl_VertexID] * a_Corner3.w; + gl_Position = vec4(slot / u_AtlasSize * 2.0 - 1.0, 0.0, 1.0); +#else + gl_Position = u_ModelViewProjection * pos4; +#endif +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java index 44f683231..ebb2c3e54 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/dynamiclights/MixinEntity.java @@ -170,9 +170,10 @@ public abstract class MixinEntity implements IDynamicLightSource { DynamicLights.updateTrackedChunks(chunkPos, this.angelica$trackedLitChunkPos, newPos); } } - // Schedules the rebuild of removed chunks. - this.angelica$scheduleTrackedChunksRebuild(renderer); + if (!this.angelica$trackedLitChunkPos.isEmpty()) { + this.angelica$scheduleTrackedChunksRebuild(renderer); + } // Swap tracked sets this.angelica$prevTrackedLitChunkPos = this.angelica$trackedLitChunkPos; this.angelica$trackedLitChunkPos = newPos; diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinRenderBlocks.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinRenderBlocks.java index f571b250d..8ca405a32 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinRenderBlocks.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/rendering/MixinRenderBlocks.java @@ -58,6 +58,28 @@ public abstract class MixinRenderBlocks implements ExtCeleritasRenderBlocks { private boolean applyingCeleritasAO = false; + @Unique + private int lastBrightnessX, lastBrightnessY, lastBrightnessZ; + + @Unique + private boolean discardedBrightness; + + @Unique + private boolean renderingPlainCube; + + @Surround(method = "renderBlockByRenderType", id = "plainCube", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBlocks;renderStandardBlock(Lnet/minecraft/block/Block;III)Z"), + require = 1) + private void angelica$enterPlainCube() { + @Surround.Carry final boolean wasPlainCube = this.renderingPlainCube; + this.renderingPlainCube = true; + } + + @Surround.Finally("plainCube") + private void angelica$exitPlainCube(@Surround.Carry boolean wasPlainCube) { + this.renderingPlainCube = wasPlainCube; + } + @Surround(method = "renderBlockByRenderType", id = "byType") private void angelica$enterByType() { @Surround.Carry final boolean wasByType = this.isRenderingByType; @@ -123,11 +145,19 @@ public abstract class MixinRenderBlocks implements ExtCeleritasRenderBlocks { @Surround.Skipped("celeritasAo") private boolean angelica$celeritasAoSkipped(Block block, int x, int y, int z, float r, float g, float b) { this.applyingCeleritasAO = true; + this.discardedBrightness = false; + final boolean rendered; try { - return this.renderStandardBlockWithColorMultiplier(block, x, y, z, r, g, b); + rendered = this.renderStandardBlockWithColorMultiplier(block, x, y, z, r, g, b); } finally { this.applyingCeleritasAO = false; } + // Multi-part render types that emit their own vertices after renderStandardBlock inherit its Tessellator + // brightness. Only a discarded lookup left it wrong; lastBrightness* is stale otherwise. + if (rendered && this.discardedBrightness && !this.renderingPlainCube) { + TessellatorManager.get().setBrightness(block.getMixedBrightnessForBlock(this.blockAccess, this.lastBrightnessX, this.lastBrightnessY, this.lastBrightnessZ)); + } + return rendered; } @Redirect(method = "renderStandardBlockWithColorMultiplier", @@ -138,7 +168,12 @@ public abstract class MixinRenderBlocks implements ExtCeleritasRenderBlocks { && ((Object) this).getClass() == RenderBlocks.class && !IsbrhDispatch.isRenderingWorldBlock() && ((StateAwareTessellator) tessellator).angelica$isCeleritasMeshing(); - return discard ? 0 : block.getMixedBrightnessForBlock(world, x, y, z); + if (!discard) return block.getMixedBrightnessForBlock(world, x, y, z); + this.discardedBrightness = true; + this.lastBrightnessX = x; + this.lastBrightnessY = y; + this.lastBrightnessZ = z; + return 0; } @Override diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinBlockHole.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinBlockHole.java new file mode 100644 index 000000000..4a86fde5f --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinBlockHole.java @@ -0,0 +1,23 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.world.IBlockAccess; +import org.spongepowered.asm.mixin.Mixin; +import thaumcraft.common.blocks.BlockHole; + +/** + * A placed hole renders as a cube textured with blank.png, which is fully transparent...why mesh?? + */ +@Mixin(BlockHole.class) +public abstract class MixinBlockHole extends BlockContainer { + + private MixinBlockHole(Material material) { + super(material); + } + + @Override + public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { + return false; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchLockRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchLockRenderer.java new file mode 100644 index 000000000..216c04c4f --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchLockRenderer.java @@ -0,0 +1,74 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import net.minecraft.tileentity.TileEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import thaumcraft.client.renderers.tile.TileEldritchLockRenderer; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Z; + +@Mixin(value = TileEldritchLockRenderer.class, remap = false) +public abstract class MixinTileEldritchLockRenderer { + @Unique + private static final float angelica$OFFSET = 0.5F; + + @Shadow + private boolean inrange; + + @Surround(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "render", remap = true, require = 1) + private void angelica$beginRender(TileEntity te, double x, double y, double z, float partialTicks) { + } + + @Surround.Finally("render") + private void angelica$endRender() { + PortalRenderer.endTileEntity(true); + } + + @Surround(method = "drawPlaneZPos(DDDFI)V", id = "zPos", require = 1) + private void angelica$zPos(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zPos") + private void angelica$zPosFace(double x, double y, double z, float f, int height) { + final double plane = z + angelica$OFFSET; + PortalRenderer.addFace(AXIS_Z, true, plane, x - 2.0, y + 3.0, plane, x - 2.0, y - 2.0, plane, x + 3.0, y + 3.0, plane); + } + + @Surround(method = "drawPlaneZNeg(DDDFI)V", id = "zNeg", require = 1) + private void angelica$zNeg(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zNeg") + private void angelica$zNegFace(double x, double y, double z, float f, int height) { + final double plane = z + angelica$OFFSET; + PortalRenderer.addFace(AXIS_Z, false, plane, x - 2.0, y - 2.0, plane, x - 2.0, y + 3.0, plane, x + 3.0, y - 2.0, plane); + } + + @Surround(method = "drawPlaneXPos(DDDFI)V", id = "xPos", require = 1) + private void angelica$xPos(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("xPos") + private void angelica$xPosFace(double x, double y, double z, float f, int height) { + final double plane = x + angelica$OFFSET; + PortalRenderer.addFace(AXIS_X, true, plane, plane, y + 3.0, z - 2.0, plane, y + 3.0, z + 3.0, plane, y - 2.0, z - 2.0); + } + + @Surround(method = "drawPlaneXNeg(DDDFI)V", id = "xNeg", require = 1) + private void angelica$xNeg(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("xNeg") + private void angelica$xNegFace(double x, double y, double z, float f, int height) { + final double plane = x + angelica$OFFSET; + PortalRenderer.addFace(AXIS_X, false, plane, plane, y - 2.0, z - 2.0, plane, y - 2.0, z + 3.0, plane, y + 3.0, z - 2.0); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothing.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothing.java new file mode 100644 index 000000000..f2e178b73 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothing.java @@ -0,0 +1,35 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalFaces; +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import thaumcraft.common.tiles.TileEldritchNothing; + +@Mixin(value = TileEldritchNothing.class, remap = false) +public abstract class MixinTileEldritchNothing implements SectionBuiltBlockEntity { + @Unique + private int angelica$faces = PortalFaces.NOT_BUILT; + + @Override + public int angelica$prepareFromSection(IBlockAccess world) { + final TileEntity te = (TileEntity) (Object) this; + return PortalFaces.nothingMask(world, te.xCoord, te.yCoord, te.zCoord); + } + + @Override + public void angelica$applySectionResult(int prepared) { + angelica$faces = prepared; + } + + @Override + public boolean angelica$drawBuilt(double x, double y, double z) { + final int faces = angelica$faces; + if (faces == PortalFaces.NOT_BUILT || !PortalRenderer.replacesLayers()) return false; + PortalRenderer.drawBuilt((TileEntity) (Object) this, false, faces, x, y, z); + return true; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothingRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothingRenderer.java new file mode 100644 index 000000000..1170cc63a --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchNothingRenderer.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalFaces; +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import net.minecraft.tileentity.TileEntity; +import org.spongepowered.asm.mixin.Mixin; +import thaumcraft.client.renderers.tile.TileEldritchNothingRenderer; + +/** + * Replaced whole for the same reasons as {@link MixinTileHoleRenderer}. + */ +@Mixin(value = TileEldritchNothingRenderer.class, remap = false) +public abstract class MixinTileEldritchNothingRenderer { + + @Surround(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "render", remap = true, require = 1) + private void angelica$beginRender(TileEntity te, double x, double y, double z, float partialTicks) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("render") + private void angelica$render(TileEntity te, double x, double y, double z, float partialTicks) { + final int mask = PortalFaces.nothingMask(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + PortalFaces.addNothingFaces(mask, PortalRenderer.inLayeredRange(te), x, y, z); + PortalRenderer.endSkippedRender(); + } + + @Surround.Finally("render") + private void angelica$endRender() { + PortalRenderer.endTileEntity(true); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchObeliskRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchObeliskRenderer.java new file mode 100644 index 000000000..1a3985533 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileEldritchObeliskRenderer.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; +import net.minecraft.tileentity.TileEntity; +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 thaumcraft.client.renderers.tile.TileEldritchObeliskRenderer; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Z; + +@Mixin(value = TileEldritchObeliskRenderer.class, remap = false) +public abstract class MixinTileEldritchObeliskRenderer { + @Unique + private static final float angelica$NEAR = 0.01F; + @Unique + private static final float angelica$FAR = 0.99F; + + @Shadow + private boolean inrange; + + @Unique + private double angelica$maxRenderDistanceSq; + + @Surround(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "render", remap = true, require = 1) + private void angelica$beginRender(TileEntity te, double x, double y, double z, float partialTicks) { + this.angelica$maxRenderDistanceSq = te.getMaxRenderDistanceSquared(); + } + + @Surround.Finally("render") + private void angelica$endRender() { + PortalRenderer.endTileEntity(false); + } + + @ModifyExpressionValue(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", + at = @At(value = "CONSTANT", args = "doubleValue=512.0"), remap = true, require = 1) + private double angelica$layeredPortalDistance(double original) { + return this.angelica$maxRenderDistanceSq; + } + + @Surround(method = "drawPlaneZNeg(DDDFI)V", id = "zNeg", require = 1) + private void angelica$zNeg(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zNeg") + private void angelica$zNegFace(double x, double y, double z, float f, int height) { + final double plane = z + angelica$NEAR; + PortalRenderer.addFace(AXIS_Z, false, plane, x, y, plane, x, y + height, plane, x + 1.0, y, plane); + } + + @Surround(method = "drawPlaneZPos(DDDFI)V", id = "zPos", require = 1) + private void angelica$zPos(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zPos") + private void angelica$zPosFace(double x, double y, double z, float f, int height) { + final double plane = z + angelica$FAR; + PortalRenderer.addFace(AXIS_Z, true, plane, x, y + height, plane, x, y, plane, x + 1.0, y + height, plane); + } + + @Surround(method = "drawPlaneXNeg(DDDFI)V", id = "xNeg", require = 1) + private void angelica$xNeg(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("xNeg") + private void angelica$xNegFace(double x, double y, double z, float f, int height) { + final double plane = x + angelica$NEAR; + PortalRenderer.addFace(AXIS_X, false, plane, plane, y, z, plane, y, z + 1.0, plane, y + height, z); + } + + @Surround(method = "drawPlaneXPos(DDDFI)V", id = "xPos", require = 1) + private void angelica$xPos(double x, double y, double z, float f, int height) { + @Surround.Skip final boolean skip = this.inrange && PortalRenderer.replacesLayers(); + } + + // TC draws this face last and the obelisk sides right after, which must land on top of the portal. + @Surround.Skipped("xPos") + private void angelica$xPosFace(double x, double y, double z, float f, int height) { + final double plane = x + angelica$FAR; + PortalRenderer.addFace(AXIS_X, true, plane, plane, y + height, z, plane, y + height, z + 1.0, plane, y, z); + PortalRenderer.drawBeforeOverlay(); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHole.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHole.java new file mode 100644 index 000000000..7d8fdfd07 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHole.java @@ -0,0 +1,35 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalFaces; +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import thaumcraft.common.tiles.TileHole; + +@Mixin(value = TileHole.class, remap = false) +public abstract class MixinTileHole implements SectionBuiltBlockEntity { + @Unique + private int angelica$faces = PortalFaces.NOT_BUILT; + + @Override + public int angelica$prepareFromSection(IBlockAccess world) { + final TileEntity te = (TileEntity) (Object) this; + return PortalFaces.holeMask(world, te.xCoord, te.yCoord, te.zCoord); + } + + @Override + public void angelica$applySectionResult(int prepared) { + angelica$faces = prepared; + } + + @Override + public boolean angelica$drawBuilt(double x, double y, double z) { + final int faces = angelica$faces; + if (faces == PortalFaces.NOT_BUILT || !PortalRenderer.replacesLayers()) return false; + PortalRenderer.drawBuilt((TileEntity) (Object) this, true, faces, x, y, z); + return true; + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHoleRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHoleRenderer.java new file mode 100644 index 000000000..6f13ced86 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileHoleRenderer.java @@ -0,0 +1,32 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalFaces; +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import net.minecraft.tileentity.TileEntity; +import org.spongepowered.asm.mixin.Mixin; +import thaumcraft.client.renderers.tile.TileHoleRenderer; + +/** + * TC's renderTileEntityAt only draws planes on the faces that border another opaque block, so it is replaced. + */ +@Mixin(value = TileHoleRenderer.class, remap = false) +public abstract class MixinTileHoleRenderer { + + @Surround(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "render", remap = true, require = 1) + private void angelica$beginRender(TileEntity te, double x, double y, double z, float partialTicks) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("render") + private void angelica$render(TileEntity te, double x, double y, double z, float partialTicks) { + final int mask = PortalFaces.holeMask(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + PortalFaces.addHoleFaces(mask, PortalRenderer.inLayeredRange(te), x, y, z); + PortalRenderer.endSkippedRender(); + } + + @Surround.Finally("render") + private void angelica$endRender() { + PortalRenderer.endTileEntity(true); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileMirrorRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileMirrorRenderer.java new file mode 100644 index 000000000..b69ad1b1a --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/thaumcraft/MixinTileMirrorRenderer.java @@ -0,0 +1,97 @@ +package com.gtnewhorizons.angelica.mixins.late.client.thaumcraft; + +import com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer; +import com.gtnewhorizons.angelica.experimental.surround.Surround; +import net.minecraft.tileentity.TileEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import thaumcraft.client.renderers.tile.TileMirrorRenderer; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Y; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Z; + +/** + * The mirror draws its glass pane over the portal right after, so each plane is flushed on its own. + */ +@Mixin(value = TileMirrorRenderer.class, remap = false) +public abstract class MixinTileMirrorRenderer { + @Unique + private static final float angelica$NEAR = 0.01F; + @Unique + private static final float angelica$FAR = 0.99F; + @Unique + private static final float angelica$INSET = 0.1875F; + + @Surround(method = "drawPlaneYPos(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "yPos", require = 1) + private void angelica$yPos(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("yPos") + private void angelica$yPosFace(TileEntity te, double x, double y, double z, float f) { + final double plane = y + angelica$FAR; + PortalRenderer.addFace(AXIS_Y, false, plane, x + angelica$INSET, plane, z + 1.0 - angelica$INSET, x + angelica$INSET, plane, z + angelica$INSET, x + 1.0 - angelica$INSET, plane, z + 1.0 - angelica$INSET); + PortalRenderer.drawBeforeOverlay(); + } + + @Surround(method = "drawPlaneYNeg(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "yNeg", require = 1) + private void angelica$yNeg(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("yNeg") + private void angelica$yNegFace(TileEntity te, double x, double y, double z, float f) { + final double plane = y + angelica$NEAR; + PortalRenderer.addFace(AXIS_Y, true, plane, x + angelica$INSET, plane, z + angelica$INSET, x + angelica$INSET, plane, z + 1.0 - angelica$INSET, x + 1.0 - angelica$INSET, plane, z + angelica$INSET); + PortalRenderer.drawBeforeOverlay(); + } + + @Surround(method = "drawPlaneZNeg(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "zNeg", require = 1) + private void angelica$zNeg(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zNeg") + private void angelica$zNegFace(TileEntity te, double x, double y, double z, float f) { + final double plane = z + angelica$NEAR; + PortalRenderer.addFace(AXIS_Z, true, plane, x + angelica$INSET, y + 1.0 - angelica$INSET, plane, x + angelica$INSET, y + angelica$INSET, plane, x + 1.0 - angelica$INSET, y + 1.0 - angelica$INSET, plane); + PortalRenderer.drawBeforeOverlay(); + } + + @Surround(method = "drawPlaneZPos(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "zPos", require = 1) + private void angelica$zPos(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("zPos") + private void angelica$zPosFace(TileEntity te, double x, double y, double z, float f) { + final double plane = z + angelica$FAR; + PortalRenderer.addFace(AXIS_Z, false, plane, x + angelica$INSET, y + angelica$INSET, plane, x + angelica$INSET, y + 1.0 - angelica$INSET, plane, x + 1.0 - angelica$INSET, y + angelica$INSET, plane); + PortalRenderer.drawBeforeOverlay(); + } + + @Surround(method = "drawPlaneXNeg(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "xNeg", require = 1) + private void angelica$xNeg(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("xNeg") + private void angelica$xNegFace(TileEntity te, double x, double y, double z, float f) { + final double plane = x + angelica$NEAR; + PortalRenderer.addFace(AXIS_X, true, plane, plane, y + 1.0 - angelica$INSET, z + angelica$INSET, plane, y + 1.0 - angelica$INSET, z + 1.0 - angelica$INSET, plane, y + angelica$INSET, z + angelica$INSET); + PortalRenderer.drawBeforeOverlay(); + } + + @Surround(method = "drawPlaneXPos(Lnet/minecraft/tileentity/TileEntity;DDDF)V", id = "xPos", require = 1) + private void angelica$xPos(TileEntity te, double x, double y, double z, float f) { + @Surround.Skip final boolean skip = PortalRenderer.replacesLayers(); + } + + @Surround.Skipped("xPos") + private void angelica$xPosFace(TileEntity te, double x, double y, double z, float f) { + final double plane = x + angelica$FAR; + PortalRenderer.addFace(AXIS_X, false, plane, plane, y + angelica$INSET, z + angelica$INSET, plane, y + angelica$INSET, z + 1.0 - angelica$INSET, plane, y + 1.0 - angelica$INSET, z + angelica$INSET); + PortalRenderer.drawBeforeOverlay(); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawerTest.java b/src/test/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawerTest.java new file mode 100644 index 000000000..f69d0ca21 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/compat/thaumcraft/PortalDrawerTest.java @@ -0,0 +1,432 @@ +package com.gtnewhorizons.angelica.compat.thaumcraft; + +import com.gtnewhorizons.angelica.glsm.GLCoreTest; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.FfpFixture; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import net.coderbot.iris.gl.framebuffer.GlFramebuffer; +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.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_X; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Y; +import static com.gtnewhorizons.angelica.compat.thaumcraft.PortalRenderer.AXIS_Z; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Checks that the single-pass portal shader looks like Thaumcraft's 16-layer draw. + */ +@GLCoreTest +class PortalDrawerTest { + private static final int SIZE = 512; + private static final int BACKGROUND = 0xFF1E140A; + private static final float TIME = 0.4567F; + // A camera far from the origin, where TC's fixed-function texture coordinates lose the most precision + private static final float CAMERA_X = -814.3F, CAMERA_Y = 86.75F, CAMERA_Z = -246.2F; + private static final float VIEW_X = 0.05F, VIEW_Y = -0.12F, VIEW_Z = 0.2F; + + private final List faces = new ArrayList<>(); + private final PortalDrawer drawer = new PortalDrawer(); + private GlFramebuffer framebuffer; + private int color, depth, tunnel, field, lightmap; + + private static void quad(double[] f, int red, int green, int blue) { + final ByteBuffer vertices = BufferUtils.createByteBuffer(4 * 20); + final double[][] corners = {{f[3], f[4], f[5]}, {f[6], f[7], f[8]}, {f[6] + f[9] - f[3], f[7] + f[10] - f[4], f[8] + f[11] - f[5]}, {f[9], f[10], f[11]}}; + for (double[] corner : corners) { + vertices.putFloat((float) corner[0]).putFloat((float) corner[1]).putFloat((float) corner[2]); + vertices.put((byte) red).put((byte) green).put((byte) blue).put((byte) 255); + vertices.putShort((short) 180).putShort((short) 0); + } + vertices.flip(); + final int vao = GLStateManager.glGenVertexArrays(); + final int vbo = GLStateManager.glGenBuffers(); + try { + GLStateManager.glBindVertexArray(vao); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); + GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); + GLStateManager.glVertexPointer(3, GL11.GL_FLOAT, 20, 0L); + GLStateManager.glColorPointer(4, GL11.GL_UNSIGNED_BYTE, 20, 12L); + GLStateManager.glClientActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glTexCoordPointer(2, GL11.GL_SHORT, 20, 16L); + GLStateManager.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); + GLStateManager.glClientActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glEnableClientState(GL11.GL_VERTEX_ARRAY); + GLStateManager.glEnableClientState(GL11.GL_COLOR_ARRAY); + GLStateManager.glDrawArrays(GL11.GL_QUADS, 0, 4); + } finally { + GLStateManager.glDisableClientState(GL11.GL_COLOR_ARRAY); + GLStateManager.glClientActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); + GLStateManager.glClientActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindVertexArray(0); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glDeleteBuffers(vbo); + GLStateManager.glDeleteVertexArrays(vao); + } + } + + private static void clear() { + GLStateManager.glClearColor(10 / 255.0F, 20 / 255.0F, 30 / 255.0F, 1.0F); + GLStateManager.glClearDepth(1.0); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + } + + private static int channelDifference(int a, int b) { + int worst = 0; + for (int shift = 0; shift <= 16; shift += 8) { + worst = Math.max(worst, Math.abs(((a >> shift) & 0xFF) - ((b >> shift) & 0xFF))); + } + return worst; + } + + private static int thaumcraftTexture(String name) { + try (InputStream in = PortalDrawerTest.class.getResourceAsStream("/assets/thaumcraft/textures/misc/" + name + ".png")) { + if (in == null) return 0; + final BufferedImage image = ImageIO.read(in); + final int width = image.getWidth(), height = image.getHeight(); + final ByteBuffer texels = BufferUtils.createByteBuffer(width * height * 4); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + final int argb = image.getRGB(x, y); + texels.put((byte) (argb >> 16)).put((byte) (argb >> 8)).put((byte) argb).put((byte) (argb >>> 24)); + } + } + texels.flip(); + final int id = texture(width, height, GL11.GL_RGBA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + 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); + return id; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static int noiseTexture(int size, long seed, int filter) { + final ByteBuffer texels = BufferUtils.createByteBuffer(size * size * 4); + final Random random = new Random(seed); + for (int i = 0; i < size * size; i++) { + texels.put((byte) random.nextInt(256)).put((byte) random.nextInt(256)).put((byte) random.nextInt(256)).put((byte) 255); + } + texels.flip(); + final int id = texture(size, size, GL11.GL_RGBA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, filter); + final int wrap = filter == GL11.GL_LINEAR ? GL12.GL_CLAMP_TO_EDGE : GL11.GL_REPEAT; + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, wrap); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, wrap); + return id; + } + + private static int texture(int width, int height, int internalFormat, int format, int type, ByteBuffer data) { + final int id = GLStateManager.glGenTextures(); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, data); + 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); + return id; + } + + private static FloatBuffer floats(float... values) { + final FloatBuffer buffer = BufferUtils.createFloatBuffer(values.length); + buffer.put(values).flip(); + return buffer; + } + + @BeforeEach + void setup() { + FfpFixture.resetFfpState(); + GLStateManager.glUseProgram(0); + ShaderManager.enable(); + GLStateManager.disableFog(); + GLStateManager.disableLighting(); + GLStateManager.disableCull(); + GLStateManager.disableBlend(); + GLStateManager.enableDepthTest(); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + + color = texture(SIZE, SIZE, GL11.GL_RGBA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null); + depth = texture(SIZE, SIZE, GL14.GL_DEPTH_COMPONENT24, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, null); + framebuffer = new GlFramebuffer(); + framebuffer.addColorAttachment(0, color); + framebuffer.addDepthAttachment(depth); + framebuffer.drawBuffers(new int[]{0}); + framebuffer.readBuffer(0); + framebuffer.bind(); + GLStateManager.glViewport(0, 0, SIZE, SIZE); + + lightmap = noiseTexture(16, 3, GL11.GL_LINEAR); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE1); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, lightmap); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + // EntityRenderer.enableLightmap's texture matrix + 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.enableTexture(); + + GLStateManager.setProjectionMatrix(new Matrix4f().perspective((float) Math.toRadians(70), 1.0F, 0.05F, 256.0F)); + GLStateManager.setModelViewMatrix(new Matrix4f().rotateX(0.2F).rotateY(0.25F)); + addFaces(); + } + + @AfterEach + void cleanup() { + drawer.destroy(); + framebuffer.destroy(); + GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + GLStateManager.glDeleteTextures(color); + GLStateManager.glDeleteTextures(depth); + if (tunnel != 0) GLStateManager.glDeleteTextures(tunnel); + if (field != 0) GLStateManager.glDeleteTextures(field); + GLStateManager.glDeleteTextures(lightmap); + FfpFixture.resetFfpState(); + } + + @Test + void matchesThaumcraftsLayersWithItsTextures() { + tunnel = thaumcraftTexture("tunnel"); + field = thaumcraftTexture("particlefield"); + assumeTrue(tunnel != 0 && field != 0, "Thaumcraft's textures are not on the test classpath"); + final Parity parity = compare(); + assertTrue(parity.exact >= parity.covered * 0.99, "single pass differs from TC's layers: " + parity); + } + + @Test + void staysWithinOneStepOnNoiseTextures() { + tunnel = noiseTexture(64, 1, GL11.GL_NEAREST); + field = noiseTexture(256, 2, GL11.GL_NEAREST); + final Parity parity = compare(); + assertTrue(parity.withinOne >= parity.covered * 0.97, "single pass drifts from TC's layers: " + parity); + } + + @Test + void fogsEachLayerLikeTheMirror() { + tunnel = noiseTexture(64, 1, GL11.GL_NEAREST); + field = noiseTexture(256, 2, GL11.GL_NEAREST); + GLStateManager.enableFog(); + GLStateManager.glFog(GL11.GL_FOG_COLOR, floats(0.05F, 0.08F, 0.15F, 1.0F)); + // Minecraft's distance fog, then its underwater fog + GLStateManager.glFogi(GL11.GL_FOG_MODE, GL11.GL_LINEAR); + GLStateManager.glFogf(GL11.GL_FOG_START, 2.0F); + GLStateManager.glFogf(GL11.GL_FOG_END, 40.0F); + final Parity linear = compare(true); + assertTrue(linear.withinOne >= linear.covered * 0.97, "linear fog drifts from TC's layers: " + linear); + GLStateManager.glFogi(GL11.GL_FOG_MODE, GL11.GL_EXP); + GLStateManager.glFogf(GL11.GL_FOG_DENSITY, 0.02F); + final Parity exp = compare(true); + assertTrue(exp.withinOne >= exp.covered * 0.97, "exp fog drifts from TC's layers: " + exp); + } + + private Parity compare() { + return compare(false); + } + + private Parity compare(boolean fogged) { + clear(); + for (double[] face : faces) referenceFace(face); + final int[] reference = FfpFixture.readRegion(SIZE); + + clear(); + final PortalDrawer.Frame frame = new PortalDrawer.Frame(); + GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), frame.modelViewProjection); + frame.modelView.set(GLStateManager.getModelViewMatrix()); + frame.cameraX = CAMERA_X; + frame.cameraY = CAMERA_Y; + frame.cameraZ = CAMERA_Z; + frame.viewX = VIEW_X; + frame.viewY = VIEW_Y; + frame.viewZ = VIEW_Z; + frame.time = TIME; + frame.prepareLayers(); + frame.readLightmap(180); + final float[] packed = new float[faces.size() * PortalDrawer.FLOATS_PER_FACE]; + for (int i = 0; i < faces.size(); i++) { + final double[] f = faces.get(i); + final int plane = frame.plane((int) f[0], f[1] != 0, f[2]); + PortalDrawer.putFace(packed, i, (int) f[0], plane, f[3], f[4], f[5], f[6], f[7], f[8], f[9], f[10], f[11]); + } + drawer.drawDirect(packed, faces.size(), tunnel, field, frame, fogged); + final int[] candidate = FfpFixture.readRegion(SIZE); + + int covered = 0, exact = 0, withinOne = 0, worst = 0; + for (int i = 0; i < reference.length; i++) { + if (reference[i] == BACKGROUND && candidate[i] == BACKGROUND) continue; + covered++; + final int difference = channelDifference(reference[i], candidate[i]); + if (difference == 0) exact++; + if (difference <= 1) withinOne++; + worst = Math.max(worst, difference); + } + final Parity parity = new Parity(covered, exact, withinOne, worst); + System.out.println("PortalDrawerTest: " + parity); + assertTrue(covered > reference.length / 10, "faces covered too little of the frame: " + parity); + return parity; + } + + private void addFaces() { + for (int x = -2; x <= 1; x++) { + for (int y = -1; y <= 0; y++) { + face(AXIS_Z, false, -6.0, x, y, -6.0, x, y + 1.0, -6.0, x + 1.0, y, -6.0); + } + } + for (int y = -1; y <= 0; y++) { + face(AXIS_Z, true, -7.0, 2.0, y + 1.0, -7.0, 2.0, y, -7.0, 3.0, y + 1.0, -7.0); + } + for (int z = -7; z <= -6; z++) { + face(AXIS_X, false, -4.0, -4.0, -1.0, z, -4.0, -1.0, z + 1.0, -4.0, 0.0, z); + final double plane = 3.0 + 0.001F; + face(AXIS_X, true, plane, plane, 1.0, z, plane, 1.0, z + 1.0, plane, 0.0, z); + } + for (int x = -1; x <= 0; x++) { + for (int z = -5; z <= -4; z++) { + face(AXIS_Y, false, -2.0, x, -2.0, z + 1.0, x, -2.0, z, x + 1.0, -2.0, z + 1.0); + final double plane = 2.0 + 0.001F; + face(AXIS_Y, true, plane, x, plane, z, x, plane, z + 1.0, x + 1.0, plane, z); + } + } + final double obelisk = -9.0 + 0.01F; + face(AXIS_Z, false, obelisk, -3.0, -1.0, obelisk, -3.0, 2.0, obelisk, -2.0, -1.0, obelisk); + final double lock = -12.0 + 0.5F; + face(AXIS_Z, true, lock, 1.0, 4.0, lock, 1.0, -1.0, lock, 6.0, 4.0, lock); + } + + private void face(int axis, boolean negative, double plane, double x0, double y0, double z0, double x1, double y1, double z1, double x3, double y3, double z3) { + faces.add(new double[]{axis, negative ? 1 : 0, plane, x0, y0, z0, x1, y1, z1, x3, y3, z3}); + } + + private void referenceFace(double[] f) { + final int axis = (int) f[0]; + final boolean negative = f[1] != 0; + final double plane = f[2]; + final float px = CAMERA_X, py = CAMERA_Y, pz = CAMERA_Z; + final float view = axis == AXIS_X ? VIEW_X : axis == AXIS_Y ? VIEW_Y : VIEW_Z; + final Random random = new Random(31100L); + for (int i = 0; i < 16; ++i) { + GLStateManager.glPushMatrix(); + float f5 = (float) (16 - i); + float f6 = 0.0625F; + float f7 = 1.0F / (f5 + 1.0F); + if (i == 0) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, tunnel); + f7 = 0.1F; + f5 = 65.0F; + f6 = 0.125F; + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(770, 771); + } + if (i == 1) { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, field); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(1, 1); + f6 = 0.5F; + } + final float f8 = (float) (negative ? -plane : plane); + final float f9 = negative ? f8 + view : f8 - view; + final float f10 = negative ? f8 + f5 + view : f8 + f5 - view; + float f11 = f9 / f10; + f11 += (float) plane; + switch (axis) { + case AXIS_X -> GLStateManager.glTranslatef(f11, py, pz); + case AXIS_Y -> GLStateManager.glTranslatef(px, f11, pz); + default -> GLStateManager.glTranslatef(px, py, f11); + } + GLStateManager.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); + GLStateManager.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); + GLStateManager.glTexGeni(GL11.GL_R, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_OBJECT_LINEAR); + GLStateManager.glTexGeni(GL11.GL_Q, GL11.GL_TEXTURE_GEN_MODE, GL11.GL_EYE_LINEAR); + switch (axis) { + case AXIS_X -> { + GLStateManager.glTexGen(GL11.GL_T, GL11.GL_OBJECT_PLANE, floats(0, 1, 0, 0)); + GLStateManager.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, floats(0, 0, 1, 0)); + GLStateManager.glTexGen(GL11.GL_R, GL11.GL_OBJECT_PLANE, floats(0, 0, 0, 1)); + GLStateManager.glTexGen(GL11.GL_Q, GL11.GL_EYE_PLANE, floats(1, 0, 0, 0)); + } + case AXIS_Y -> { + GLStateManager.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, floats(1, 0, 0, 0)); + GLStateManager.glTexGen(GL11.GL_T, GL11.GL_OBJECT_PLANE, floats(0, 0, 1, 0)); + GLStateManager.glTexGen(GL11.GL_R, GL11.GL_OBJECT_PLANE, floats(0, 0, 0, 1)); + GLStateManager.glTexGen(GL11.GL_Q, GL11.GL_EYE_PLANE, floats(0, 1, 0, 0)); + } + default -> { + GLStateManager.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, floats(1, 0, 0, 0)); + GLStateManager.glTexGen(GL11.GL_T, GL11.GL_OBJECT_PLANE, floats(0, 1, 0, 0)); + GLStateManager.glTexGen(GL11.GL_R, GL11.GL_OBJECT_PLANE, floats(0, 0, 0, 1)); + GLStateManager.glTexGen(GL11.GL_Q, GL11.GL_EYE_PLANE, floats(0, 0, 1, 0)); + } + } + GLStateManager.glEnable(GL11.GL_TEXTURE_GEN_S); + GLStateManager.glEnable(GL11.GL_TEXTURE_GEN_T); + GLStateManager.glEnable(GL11.GL_TEXTURE_GEN_R); + GLStateManager.glEnable(GL11.GL_TEXTURE_GEN_Q); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_TEXTURE); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glTranslatef(0.0F, TIME, 0.0F); + GLStateManager.glScalef(f6, f6, f6); + GLStateManager.glTranslatef(0.5F, 0.5F, 0.0F); + GLStateManager.glRotatef((float) (i * i * 4321 + i * 9) * 2.0F, 0.0F, 0.0F, 1.0F); + GLStateManager.glTranslatef(-0.5F, -0.5F, 0.0F); + switch (axis) { + case AXIS_X -> { + GLStateManager.glTranslatef(-pz, -py, -px); + GLStateManager.glTranslatef(VIEW_Z * f5 / f9, VIEW_Y * f5 / f9, -px); + } + case AXIS_Y -> { + GLStateManager.glTranslatef(-px, -pz, -py); + GLStateManager.glTranslatef(VIEW_X * f5 / f9, VIEW_Z * f5 / f9, -py); + } + default -> { + GLStateManager.glTranslatef(-px, -py, -pz); + GLStateManager.glTranslatef(VIEW_X * f5 / f9, VIEW_Y * f5 / f9, -pz); + } + } + float red = random.nextFloat() * 0.5F + 0.1F; + float green = random.nextFloat() * 0.5F + 0.4F; + float blue = random.nextFloat() * 0.5F + 0.5F; + if (i == 0) red = green = blue = 1.0F; + // Tessellator.setColorRGBA_F stores bytes, and its brightness 180 becomes the lightmap coordinate + quad(f, (int) (red * f7 * 255.0F), (int) (green * f7 * 255.0F), (int) (blue * f7 * 255.0F)); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + } + GLStateManager.disableBlend(); + GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_S); + GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_T); + GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_R); + GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_Q); + } + + private record Parity(int covered, int exact, int withinOne, int worst) { + @Override + public String toString() { + return String.format("covered=%d exact=%.3f%% withinOne=%.3f%% worstChannel=%d", covered, 100.0 * exact / covered, 100.0 * withinOne / covered, worst); + } + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/AttributeTransformerLinkGLTest.java b/src/test/java/net/coderbot/iris/pipeline/AttributeTransformerLinkGLTest.java new file mode 100644 index 000000000..5d6abb072 --- /dev/null +++ b/src/test/java/net/coderbot/iris/pipeline/AttributeTransformerLinkGLTest.java @@ -0,0 +1,137 @@ +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.shader.ShaderType; +import com.gtnewhorizons.angelica.glsm.testutil.Reflect; +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.gl.shader.GlShader; +import net.coderbot.iris.gl.shader.ProgramCreator; +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.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@GLCoreTest +class AttributeTransformerLinkGLTest { + + private static final String COMPAT_VERTEX = """ + #version 120 + varying vec4 color; + varying vec3 normal; + void main() { + color = gl_Color; + normal = normalize(gl_NormalMatrix * gl_Normal); + gl_Position = ftransform(); + } + """; + + private static final String COMPAT_FRAGMENT = """ + #version 120 + varying vec4 color; + varying vec3 normal; + void main() { + gl_FragData[0] = color * vec4(normal * 0.5 + 0.5, 1.0); + } + """; + + private static final String CORE_PROFILE_VERTEX = """ + #version 150 + in vec3 vaPosition; + in vec3 vaNormal; + in vec4 vaColor; + in ivec2 vaUV2; + uniform mat4 modelViewMatrix; + uniform mat4 projectionMatrix; + out vec4 color; + void main() { + vec4 start = projectionMatrix * modelViewMatrix * vec4(vaPosition, 1.0); + vec4 end = projectionMatrix * modelViewMatrix * vec4(vaPosition + vaNormal, 1.0); + color = vaColor * vec4(vec2(vaUV2) / 240.0, 1.0, 1.0); + gl_Position = mix(start, end, float(gl_VertexID % 2)); + } + """; + + private static final String CORE_PROFILE_FRAGMENT = """ + #version 150 + in vec4 color; + void main() { + gl_FragData[0] = color; + } + """; + + 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 clearCaches() { + TransformPatcher.clearCache(); + ShaderTransformer.clearCache(); + } + + private static int link(String name, Map result) { + assertNotNull(result); + final GlShader vertex = new GlShader(ShaderType.VERTEX, name + "Vertex", result.get(PatchShaderType.VERTEX)); + final GlShader fragment = new GlShader(ShaderType.FRAGMENT, name + "Fragment", result.get(PatchShaderType.FRAGMENT)); + try { + return ProgramCreator.create(name, vertex, fragment); + } finally { + vertex.destroy(); + fragment.destroy(); + } + } + + @Test + void wideLineVariantLinksWithLineUniformsLive() { + final Map result = TransformPatcher.patchAttributesWideLines(COMPAT_VERTEX, null, null, null, COMPAT_FRAGMENT, InputAvailability.NONE); + final int program = link("wideLines", result); + try { + assertNotEquals(-1, GLStateManager.glGetUniformLocation(program, "iris_LineWidth"), () -> result.get(PatchShaderType.VERTEX)); + assertNotEquals(-1, GLStateManager.glGetUniformLocation(program, "iris_ScreenSize"), () -> result.get(PatchShaderType.VERTEX)); + } finally { + GLStateManager.glDeleteProgram(program); + } + } + + @Test + void declaredCoreProfileInputsReadTheBoundAttributes() { + final Map result = TransformPatcher.patchAttributes(CORE_PROFILE_VERTEX, null, null, null, CORE_PROFILE_FRAGMENT, InputAvailability.BOTH); + final int program = link("coreProfileInputs", result); + try { + for (String input : new String[] {"vaPosition", "vaNormal", "vaColor", "vaUV2"}) { + assertEquals(-1, GLStateManager.glGetAttribLocation(program, input), () -> input + " left unmapped:\n" + result.get(PatchShaderType.VERTEX)); + } + assertEquals(0, GLStateManager.glGetAttribLocation(program, "iris_Vertex")); + assertEquals(1, GLStateManager.glGetAttribLocation(program, "iris_Color")); + assertEquals(4, GLStateManager.glGetAttribLocation(program, "iris_Normal")); + assertEquals(-1, GLStateManager.glGetUniformLocation(program, "modelViewMatrix")); + assertEquals(-1, GLStateManager.glGetUniformLocation(program, "projectionMatrix")); + assertNotEquals(-1, GLStateManager.glGetUniformLocation(program, "iris_ModelViewMatrix")); + assertNotEquals(-1, GLStateManager.glGetUniformLocation(program, "iris_ProjectionMatrix")); + } finally { + GLStateManager.glDeleteProgram(program); + } + } +} diff --git a/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java b/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java index b15fcbdf2..3a647efa1 100644 --- a/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java +++ b/src/test/java/net/coderbot/iris/pipeline/MvBuiltinScanTest.java @@ -13,6 +13,12 @@ class MvBuiltinScanTest { assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag)); } + @Test + void detectsCoreProfileMatrixNames() { + String frag = "#version 150\nuniform mat4 modelViewMatrixInverse;\nvoid main() { gl_FragData[0] = modelViewMatrixInverse * vec4(1.0); }"; + assertTrue(DeferredWorldRenderingPipeline.referencesMvBuiltins(frag)); + } + @Test void detectsFtransformCall() { String vert = "#version 120\nvoid main() { gl_Position = ftransform(); }"; 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 eaf7397cc..1303fea83 100644 --- a/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java +++ b/src/test/java/net/coderbot/iris/pipeline/transform/AttributeTransformerInstancedTest.java @@ -100,6 +100,19 @@ class AttributeTransformerInstancedTest { } """; + private static final String VERTEX_CORE_PROFILE_MV_INVERSE = """ + #version 150 + in vec3 vaPosition; + uniform mat4 modelViewMatrix; + uniform mat4 modelViewMatrixInverse; + uniform mat4 projectionMatrix; + out vec3 wpos; + void main() { + wpos = (modelViewMatrixInverse * (modelViewMatrix * vec4(vaPosition, 1.0))).xyz; + gl_Position = projectionMatrix * modelViewMatrix * vec4(vaPosition, 1.0); + } + """; + private static final String FRAGMENT = """ #version 120 varying vec4 color; @@ -310,6 +323,13 @@ class AttributeTransformerInstancedTest { assertLacks(with, "uniform mat4 iris_ModelViewMatrixInverse;"); } + @Test + void coreProfileMvInverseIsComputedPerInstance() { + final String v = instancedVertex(VERTEX_CORE_PROFILE_MV_INVERSE); + assertHas(v, "iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix)"); + assertLacks(v, "modelViewMatrixInverse"); + } + @Test void assignmentBlockRunsFirstInMain() { final String v = instancedVertex(VERTEX);