From 542a1b051c14f2d113548e4f15e8a3637ea83cfd Mon Sep 17 00:00:00 2001 From: Jason Mitchell Date: Fri, 5 Dec 2025 15:50:06 -0800 Subject: [PATCH] Support lines and triangles in tessellator & cleanup allocs (#222) --- .../gtnhlib/client/renderer/CapturedDraw.java | 28 - .../client/renderer/CapturingTessellator.java | 71 +- .../gtnhlib/client/renderer/DrawCallback.java | 20 +- .../client/renderer/PrimitiveExtractor.java | 409 +++++++++ .../client/renderer/QuadExtractor.java | 52 +- .../client/renderer/TessellatorManager.java | 429 ++++++++-- .../renderer/cel/model/line/ModelLine.java | 160 ++++ .../model/primitive/ModelPrimitiveView.java | 53 ++ .../renderer/cel/model/quad/ModelQuad.java | 6 +- .../cel/model/quad/ModelQuadView.java | 10 +- .../renderer/cel/model/tri/ModelTriangle.java | 226 +++++ .../renderer/PrimitiveExtractorTest.java | 776 ++++++++++++++++++ .../renderer/TessellatorManagerTest.java | 221 +++-- 13 files changed, 2223 insertions(+), 238 deletions(-) delete mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractor.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/line/ModelLine.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/primitive/ModelPrimitiveView.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/tri/ModelTriangle.java create mode 100644 src/test/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractorTest.java diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java deleted file mode 100644 index 323f4879..00000000 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.gtnewhorizon.gtnhlib.client.renderer; - -import java.util.List; - -import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; - -/** - * Represents a single draw call captured during CAPTURING mode. Contains the quads and flags from that specific draw() - * call. - */ -public class CapturedDraw { - - private final List quads; - private final CapturingTessellator.Flags flags; - - public CapturedDraw(List quads, CapturingTessellator.Flags flags) { - this.quads = quads; - this.flags = flags; - } - - public List quads() { - return quads; - } - - public CapturingTessellator.Flags flags() { - return flags; - } -} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java index c59e8775..e699a088 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java @@ -9,6 +9,7 @@ import static net.minecraft.util.MathHelper.clamp_int; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -18,10 +19,14 @@ import net.minecraft.client.renderer.Tessellator; import org.joml.Matrix3f; import org.joml.Vector3f; import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.Vector3dStack; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizon.gtnhlib.util.ObjectPooler; @@ -35,8 +40,32 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; @SuppressWarnings("unused") public class CapturingTessellator extends Tessellator implements ITessellatorInstance { - final ObjectPooler quadBuf = new ObjectPooler<>(ModelQuad::new); + // Object pools reduce allocations over time by reusing primitive instances across multiple + // capture sessions. Not meant to avoid allocations within a single call, but to amortize + // allocation costs across the lifetime of the CapturingTessellator. + final ObjectPooler quadPool = new ObjectPooler<>(ModelQuad::new); + final ObjectPooler triPool = new ObjectPooler<>(ModelTriangle::new); + final ObjectPooler linePool = new ObjectPooler<>(ModelLine::new); + + /** + * Stores ModelQuad objects for GL_QUADS and GL_TRIANGLES draw modes. Triangles are stored as "degenerate quads" via + * quadrangulation (v2 duplicated to v3) for backward compatibility with code expecting all geometry in this list. + * Populated by QuadExtractor. + */ final List collectedQuads = new ObjectArrayList<>(); + + /** + * Stores primitives from other draw modes: GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP (as ModelLine), GL_TRIANGLE_STRIP, + * GL_TRIANGLE_FAN (as ModelTriangle). These are converted to their base primitive types. Populated by + * PrimitiveExtractor. + */ + final List collectedPrimitives = new ObjectArrayList<>(); + + // Reusable lists for stopCapturingToGeometry to avoid allocations + final List lineListCache = new ArrayList<>(); + final List triangleListCache = new ArrayList<>(); + final List quadListCache = new ArrayList<>(); + int shaderBlockId = -1; // Any offset we need to the Tesselator's offset! @@ -82,15 +111,34 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns return collectedQuads; } + public List getPrimitives() { + return collectedPrimitives; + } + public void clearQuads() { // noinspection ForLoopReplaceableByForEach for (int i = 0; i < collectedQuads.size(); i++) { final var quad = collectedQuads.get(i); - if (quad instanceof ModelQuad mq) quadBuf.releaseInstance(mq); + if (quad instanceof ModelQuad mq) quadPool.releaseInstance(mq); } collectedQuads.clear(); } + public void clearPrimitives() { + // noinspection ForLoopReplaceableByForEach + for (int i = 0; i < collectedPrimitives.size(); i++) { + final var prim = collectedPrimitives.get(i); + if (prim instanceof ModelQuad mq) { + quadPool.releaseInstance(mq); + } else if (prim instanceof ModelTriangle mt) { + triPool.releaseInstance(mt); + } else if (prim instanceof ModelLine ml) { + linePool.releaseInstance(ml); + } + } + collectedPrimitives.clear(); + } + public static ByteBuffer quadsToBuffer(List quads, VertexFormat format) { if (!format.canWriteQuads()) { throw new IllegalStateException("Vertex format has no quad writer: " + format); @@ -242,6 +290,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns public boolean hasBrightness; public boolean hasColor; public boolean hasNormals; + public int drawMode = GL11.GL_QUADS; public Flags(boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals) { this.hasTexture = hasTexture; @@ -258,6 +307,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns this.hasBrightness = other.hasBrightness; this.hasColor = other.hasColor; this.hasNormals = other.hasNormals; + this.drawMode = other.drawMode; } /** @@ -270,18 +320,31 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns this.hasNormals = hasNormals; } + /** + * Updates this Flags instance with new values including draw mode. + */ + public void copyFrom(boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals, + int drawMode) { + this.hasTexture = hasTexture; + this.hasBrightness = hasBrightness; + this.hasColor = hasColor; + this.hasNormals = hasNormals; + this.drawMode = drawMode; + } + @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Flags flags)) return false; return hasTexture == flags.hasTexture && hasBrightness == flags.hasBrightness && hasColor == flags.hasColor - && hasNormals == flags.hasNormals; + && hasNormals == flags.hasNormals + && drawMode == flags.drawMode; } @Override public int hashCode() { - return Objects.hash(hasTexture, hasBrightness, hasColor, hasNormals); + return Objects.hash(hasTexture, hasBrightness, hasColor, hasNormals, drawMode); } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java index 21f1e1c3..e8689399 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java @@ -2,6 +2,7 @@ package com.gtnewhorizon.gtnhlib.client.renderer; import java.util.List; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; /** @@ -10,11 +11,20 @@ import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMuta public interface DrawCallback { /** - * Called after each Tessellator.draw() during compiling mode. The quads are pooled objects - caller MUST copy them - * if needed beyond this call. After this callback returns, the quads will be released back to the pool. + * Called after each Tessellator.draw() during compiling mode. The quads and primitives are pooled objects - caller + * MUST copy them if needed beyond this call. After this callback returns, they will be released back to the pool. + *

+ * For any single draw call, typically only one list will have content: + *

    + *
  • GL_QUADS → quads list (as ModelQuad)
  • + *
  • GL_TRIANGLES → primitives list (as ModelTriangle)
  • + *
  • GL_LINES, GL_LINE_STRIP, etc. → primitives list (as ModelLine/ModelTriangle)
  • + *
* - * @param quads The quads from this specific draw call (sublist of collected quads) - * @param flags The tessellator flags (hasTexture, hasBrightness, hasColor, hasNormals) from this draw call + * @param quads The quads from GL_QUADS draw calls + * @param primitives The primitives from GL_TRIANGLES, GL_LINES, and other draw modes + * @param flags The tessellator flags (hasTexture, hasBrightness, hasColor, hasNormals, drawMode) */ - void onDraw(List quads, CapturingTessellator.Flags flags); + void onDraw(List quads, List primitives, + CapturingTessellator.Flags flags); } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractor.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractor.java new file mode 100644 index 00000000..ebb1a26f --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractor.java @@ -0,0 +1,409 @@ +package com.gtnewhorizon.gtnhlib.client.renderer; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; + +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; +import com.gtnewhorizon.gtnhlib.util.ObjectPooler; + +/** + * Utility class for extracting primitives (lines, triangles, quads) from Tessellator raw buffers. Supports GL_QUADS, + * GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN. + */ +public final class PrimitiveExtractor { + + private static final Logger LOGGER = LogManager.getLogger("PrimitiveExtractor"); + + private PrimitiveExtractor() {} + + /** + * Builds primitives from a Tessellator's raw buffer based on draw mode. Quads are extracted as ModelQuad objects. + */ + public static void buildPrimitivesFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture, + boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler quadPool, ObjectPooler triPool, + ObjectPooler linePool, List collectedPrimitives, + CapturingTessellator.Flags flags) { + buildPrimitivesFromBuffer( + rawBuffer, + vertexCount, + drawMode, + hasTexture, + hasBrightness, + hasColor, + hasNormals, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + quadPool, + triPool, + linePool, + collectedPrimitives, + flags, + false); + } + + /** + * Builds primitives from a Tessellator's raw buffer based on draw mode. + * + * @param convertQuadsToTriangles If true, GL_QUADS are converted to GL_TRIANGLES (2 triangles per quad). Useful for + * modern OpenGL compatibility since GL_QUADS is deprecated in 3.1+. + */ + public static void buildPrimitivesFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture, + boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler quadPool, ObjectPooler triPool, + ObjectPooler linePool, List collectedPrimitives, + CapturingTessellator.Flags flags, boolean convertQuadsToTriangles) { + + flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals, drawMode); + + switch (drawMode) { + case GL11.GL_QUADS: + if (convertQuadsToTriangles) { + extractQuadsAsTriangles( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + triPool, + collectedPrimitives, + flags); + flags.drawMode = GL11.GL_TRIANGLES; + } else { + extractQuads( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + quadPool, + collectedPrimitives, + flags); + } + break; + case GL11.GL_TRIANGLES: + extractTriangles( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + triPool, + collectedPrimitives, + flags); + break; + case GL11.GL_LINES: + extractLines( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + linePool, + collectedPrimitives); + break; + case GL11.GL_LINE_STRIP: + extractLineStrip( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + linePool, + collectedPrimitives); + flags.drawMode = GL11.GL_LINES; // Converted to individual lines + break; + case GL11.GL_LINE_LOOP: + extractLineLoop( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + linePool, + collectedPrimitives); + flags.drawMode = GL11.GL_LINES; + break; + case GL11.GL_TRIANGLE_STRIP: + extractTriangleStrip( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + triPool, + collectedPrimitives, + flags); + flags.drawMode = GL11.GL_TRIANGLES; + break; + case GL11.GL_TRIANGLE_FAN: + extractTriangleFan( + rawBuffer, + vertexCount, + offsetX, + offsetY, + offsetZ, + shaderBlockId, + triPool, + collectedPrimitives, + flags); + flags.drawMode = GL11.GL_TRIANGLES; + break; + default: + LOGGER.warn( + "Unsupported draw mode: 0x{} ({} vertices) - primitives will not be captured", + Integer.toHexString(drawMode), + vertexCount); + break; + } + } + + // ==================== QUADS ==================== + + private static void extractQuads(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler quadPool, List collected, + CapturingTessellator.Flags flags) { + + final int numQuads = vertexCount / 4; + for (int i = 0; i < numQuads; i++) { + final int srcOffset = i * 4 * VERTEX_SIZE; + if (isEmptyPrimitive(rawBuffer, srcOffset, 4)) continue; + + final ModelQuad quad = quadPool.getInstance(); + quad.setState(rawBuffer, srcOffset, flags, GL11.GL_QUADS, offsetX, offsetY, offsetZ); + quad.setShaderBlockId(shaderBlockId); + collected.add(quad); + } + } + + /** + * Converts quads to triangles. Each quad (v0,v1,v2,v3) becomes 2 triangles: (v0,v1,v2) and (v0,v2,v3). + */ + private static void extractQuadsAsTriangles(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler triPool, List collected, + CapturingTessellator.Flags flags) { + + final int numQuads = vertexCount / 4; + for (int i = 0; i < numQuads; i++) { + final int srcOffset = i * 4 * VERTEX_SIZE; + if (isEmptyPrimitive(rawBuffer, srcOffset, 4)) continue; + + // Triangle 1: v0, v1, v2 + final ModelTriangle tri1 = triPool.getInstance(); + copyVertexToTriangle(rawBuffer, srcOffset + 0 * VERTEX_SIZE, tri1, 0); + copyVertexToTriangle(rawBuffer, srcOffset + 1 * VERTEX_SIZE, tri1, 1); + copyVertexToTriangle(rawBuffer, srcOffset + 2 * VERTEX_SIZE, tri1, 2); + if (!flags.hasColor) setDefaultTriangleColors(tri1); + tri1.setShaderBlockId(shaderBlockId); + tri1.applyOffset(offsetX, offsetY, offsetZ); + collected.add(tri1); + + // Triangle 2: v0, v2, v3 + final ModelTriangle tri2 = triPool.getInstance(); + copyVertexToTriangle(rawBuffer, srcOffset + 0 * VERTEX_SIZE, tri2, 0); + copyVertexToTriangle(rawBuffer, srcOffset + 2 * VERTEX_SIZE, tri2, 1); + copyVertexToTriangle(rawBuffer, srcOffset + 3 * VERTEX_SIZE, tri2, 2); + if (!flags.hasColor) setDefaultTriangleColors(tri2); + tri2.setShaderBlockId(shaderBlockId); + tri2.applyOffset(offsetX, offsetY, offsetZ); + collected.add(tri2); + } + } + + // ==================== TRIANGLES ==================== + + private static void extractTriangles(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler triPool, List collected, + CapturingTessellator.Flags flags) { + + final int numTris = vertexCount / 3; + for (int i = 0; i < numTris; i++) { + final int srcOffset = i * 3 * VERTEX_SIZE; + if (isEmptyPrimitive(rawBuffer, srcOffset, 3)) continue; + + final ModelTriangle tri = triPool.getInstance(); + tri.setState(rawBuffer, srcOffset, flags); + tri.setShaderBlockId(shaderBlockId); + tri.applyOffset(offsetX, offsetY, offsetZ); + collected.add(tri); + } + } + + private static void extractTriangleStrip(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler triPool, List collected, + CapturingTessellator.Flags flags) { + + if (vertexCount < 3) return; + + // Triangle strip: N vertices → N-2 triangles + // Even triangles: [i, i+1, i+2] + // Odd triangles: [i+1, i, i+2] (reversed winding) + for (int i = 0; i < vertexCount - 2; i++) { + final ModelTriangle tri = triPool.getInstance(); + + int v0, v1, v2; + if ((i & 1) == 0) { + v0 = i; + v1 = i + 1; + v2 = i + 2; + } else { + v0 = i + 1; + v1 = i; + v2 = i + 2; + } + + copyVertexToTriangle(rawBuffer, v0 * VERTEX_SIZE, tri, 0); + copyVertexToTriangle(rawBuffer, v1 * VERTEX_SIZE, tri, 1); + copyVertexToTriangle(rawBuffer, v2 * VERTEX_SIZE, tri, 2); + + if (!flags.hasColor) setDefaultTriangleColors(tri); + + tri.setShaderBlockId(shaderBlockId); + tri.applyOffset(offsetX, offsetY, offsetZ); + collected.add(tri); + } + } + + private static void extractTriangleFan(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler triPool, List collected, + CapturingTessellator.Flags flags) { + + if (vertexCount < 3) return; + + // Triangle fan: All triangles share vertex 0 + // Triangle i uses vertices [0, i+1, i+2] + for (int i = 0; i < vertexCount - 2; i++) { + final ModelTriangle tri = triPool.getInstance(); + + copyVertexToTriangle(rawBuffer, 0, tri, 0); // Center vertex + copyVertexToTriangle(rawBuffer, (i + 1) * VERTEX_SIZE, tri, 1); + copyVertexToTriangle(rawBuffer, (i + 2) * VERTEX_SIZE, tri, 2); + + if (!flags.hasColor) setDefaultTriangleColors(tri); + + tri.setShaderBlockId(shaderBlockId); + tri.applyOffset(offsetX, offsetY, offsetZ); + collected.add(tri); + } + } + + // ==================== LINES ==================== + + private static void extractLines(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler linePool, List collected) { + + final int numLines = vertexCount / 2; + for (int i = 0; i < numLines; i++) { + final int srcOffset = i * 2 * VERTEX_SIZE; + if (isEmptyPrimitive(rawBuffer, srcOffset, 2)) continue; + + final ModelLine line = linePool.getInstance(); + line.setState(rawBuffer, srcOffset); + line.setShaderBlockId(shaderBlockId); + line.applyOffset(offsetX, offsetY, offsetZ); + collected.add(line); + } + } + + private static void extractLineStrip(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler linePool, List collected) { + + if (vertexCount < 2) return; + + // Line strip: N vertices → N-1 lines + for (int i = 0; i < vertexCount - 1; i++) { + final ModelLine line = linePool.getInstance(); + + copyVertexToLine(rawBuffer, i * VERTEX_SIZE, line, 0); + copyVertexToLine(rawBuffer, (i + 1) * VERTEX_SIZE, line, 1); + + line.setShaderBlockId(shaderBlockId); + line.applyOffset(offsetX, offsetY, offsetZ); + collected.add(line); + } + } + + private static void extractLineLoop(int[] rawBuffer, int vertexCount, int offsetX, int offsetY, int offsetZ, + int shaderBlockId, ObjectPooler linePool, List collected) { + + if (vertexCount < 2) return; + + // Line loop: Like strip + closing segment (but don't recurse - apply offsets inline) + for (int i = 0; i < vertexCount - 1; i++) { + final ModelLine line = linePool.getInstance(); + copyVertexToLine(rawBuffer, i * VERTEX_SIZE, line, 0); + copyVertexToLine(rawBuffer, (i + 1) * VERTEX_SIZE, line, 1); + line.setShaderBlockId(shaderBlockId); + line.applyOffset(offsetX, offsetY, offsetZ); + collected.add(line); + } + + // Add closing segment (last → first) + final ModelLine closingLine = linePool.getInstance(); + copyVertexToLine(rawBuffer, (vertexCount - 1) * VERTEX_SIZE, closingLine, 0); + copyVertexToLine(rawBuffer, 0, closingLine, 1); + closingLine.setShaderBlockId(shaderBlockId); + closingLine.applyOffset(offsetX, offsetY, offsetZ); + collected.add(closingLine); + } + + // ==================== HELPERS ==================== + + /** + * Copies a vertex from raw buffer to triangle. Delegates to ModelTriangle's optimized copy method. + */ + private static void copyVertexToTriangle(int[] rawBuffer, int srcOffset, ModelTriangle tri, int destIdx) { + tri.copyVertexFromBuffer(rawBuffer, srcOffset, destIdx); + } + + /** + * Copies a vertex from raw buffer to line. Delegates to ModelLine's optimized copy method. + */ + private static void copyVertexToLine(int[] rawBuffer, int srcOffset, ModelLine line, int destIdx) { + line.copyVertexFromBuffer(rawBuffer, srcOffset, destIdx); + } + + private static void setDefaultTriangleColors(ModelTriangle tri) { + tri.setColor(0, DEFAULT_COLOR); + tri.setColor(1, DEFAULT_COLOR); + tri.setColor(2, DEFAULT_COLOR); + } + + /** + * Check if a primitive is degenerate (all vertices at the same position). Also returns true if buffer is malformed + * (insufficient size) to prevent ArrayIndexOutOfBoundsException. + */ + static boolean isEmptyPrimitive(int[] rawBuffer, int srcOffset, int vertexCount) { + // Bounds check: need srcOffset + (vertexCount-1)*VERTEX_SIZE + 2 (for Z axis) + final int requiredSize = srcOffset + (vertexCount - 1) * VERTEX_SIZE + 3; // +3 for X,Y,Z of last vertex + if (requiredSize > rawBuffer.length) return true; // Treat malformed buffer as empty + + for (int axis = 0; axis < 3; axis++) { + final int firstVal = rawBuffer[srcOffset + axis]; + for (int v = 1; v < vertexCount; v++) { + if (firstVal != rawBuffer[srcOffset + v * VERTEX_SIZE + axis]) { + return false; + } + } + } + return true; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java index 0d56d439..17f08c8d 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java @@ -1,7 +1,11 @@ package com.gtnewhorizon.gtnhlib.client.renderer; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; + import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL11; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; @@ -14,7 +18,7 @@ import com.gtnewhorizon.gtnhlib.util.ObjectPooler; */ public final class QuadExtractor { - private static final int VERTEX_STRIDE = 8; // ints per vertex in Tessellator raw buffer + private static final Logger LOGGER = LogManager.getLogger("QuadExtractor"); private QuadExtractor() { // Utility class - no instantiation @@ -35,46 +39,40 @@ public final class QuadExtractor { * @param offsetY Y offset to apply to all vertices * @param offsetZ Z offset to apply to all vertices * @param shaderBlockId Shader block ID to assign to quads - * @param quadBuf Object pooler for ModelQuad instances + * @param quadPool Object pooler for ModelQuad instances * @param collectedQuads List to add extracted quads to * @param flags Flags object to update with vertex format information */ public static void buildQuadsFromBuffer(int[] rawBuffer, int vertexCount, int drawMode, boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals, int offsetX, int offsetY, int offsetZ, - int shaderBlockId, ObjectPooler quadBuf, List collectedQuads, + int shaderBlockId, ObjectPooler quadPool, List collectedQuads, CapturingTessellator.Flags flags) { - flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals); + flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals, drawMode); - final int verticesPerPrimitive = drawMode == GL11.GL_QUADS ? 4 : 3; + // Only handle GL_QUADS and GL_TRIANGLES - skip unsupported draw modes to prevent buffer corruption + final int verticesPerPrimitive; + if (drawMode == GL11.GL_QUADS) { + verticesPerPrimitive = 4; + } else if (drawMode == GL11.GL_TRIANGLES) { + verticesPerPrimitive = 3; + } else { + // Unsupported draw mode (GL_LINES, GL_LINE_STRIP, etc.) - skip to avoid corrupting buffer reads + LOGGER.debug( + "Skipping unsupported draw mode: 0x{} ({} vertices)", + Integer.toHexString(drawMode), + vertexCount); + return; + } for (int quadI = 0; quadI < vertexCount / verticesPerPrimitive; quadI++) { - final int srcOffset = quadI * (verticesPerPrimitive * VERTEX_STRIDE); - if (isEmptyQuad(rawBuffer, srcOffset)) continue; + final int srcOffset = quadI * (verticesPerPrimitive * VERTEX_SIZE); + if (PrimitiveExtractor.isEmptyPrimitive(rawBuffer, srcOffset, verticesPerPrimitive)) continue; - final ModelQuad quad = quadBuf.getInstance(); + final ModelQuad quad = quadPool.getInstance(); quad.setState(rawBuffer, srcOffset, flags, drawMode, offsetX, offsetY, offsetZ); quad.setShaderBlockId(shaderBlockId); collectedQuads.add(quad); } } - - /** - * Check if a quad is degenerate (all vertices at the same position). This filters out empty/collapsed quads that - * would be invisible. Compares raw float bits for exact equality. - * - * @param rawBuffer The tessellator's raw data buffer - * @param srcOffset Offset to the first vertex of the quad - * @return true if all 4 vertices have identical X, Y, and Z coordinates - */ - private static boolean isEmptyQuad(int[] rawBuffer, int srcOffset) { - // Check if all 4 vertices have identical X, Y, Z coordinates - for (int axis = 0; axis < 3; axis++) { - final int firstVal = rawBuffer[srcOffset + axis]; - if (firstVal != rawBuffer[srcOffset + VERTEX_STRIDE + axis]) return false; - if (firstVal != rawBuffer[srcOffset + 2 * VERTEX_STRIDE + axis]) return false; - if (firstVal != rawBuffer[srcOffset + 3 * VERTEX_STRIDE + axis]) return false; - } - return true; - } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java index f6890908..c03e9f95 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java @@ -8,10 +8,15 @@ import net.minecraft.client.renderer.Tessellator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; +import com.github.bsideup.jabel.Desugar; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; -import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; @@ -30,7 +35,7 @@ public class TessellatorManager { final CaptureMode mode; final DrawCallback callback; // null for CAPTURING mode, non-null for COMPILING - final List capturedDraws = new ArrayList<>(); // Stores per-draw quads+flags for nested CAPTURING + List savedQuads; // Quads saved from parent when nesting starts CaptureState(CaptureMode mode, DrawCallback callback) { this.mode = mode; @@ -38,6 +43,29 @@ public class TessellatorManager { } } + /** + * Captured geometry as a list of VBOs. Each VBO contains primitives of a single type (lines, triangles, or quads). + */ + @Desugar + public record CapturedGeometry(List vbos) { + + public boolean isEmpty() { + return vbos.isEmpty(); + } + + public void delete() { + for (int i = 0, size = vbos.size(); i < size; i++) { + vbos.get(i).delete(); + } + } + + public void renderAll() { + for (int i = 0, size = vbos.size(); i < size; i++) { + vbos.get(i).render(); + } + } + } + private static final ThreadLocal capturingTessellator = ThreadLocal .withInitial(CapturingTessellator::new); @@ -125,21 +153,18 @@ public class TessellatorManager { } /** - * If parent state is CAPTURING and there are uncommitted quads, save them as a draw. This handles nesting: child - * captures need to preserve parent's pending work. + * If parent state is CAPTURING, save its quads before child starts. The child will use the same collectedQuads + * list, so we save parent's quads and clear for child use. */ - private static void saveUncommittedQuadsIfNeeded(ArrayList stack, CapturingTessellator tess) { - if (stack.isEmpty() || tess.getQuads().isEmpty()) { + private static void saveParentQuadsIfNeeded(ArrayList stack, CapturingTessellator tess) { + if (stack.isEmpty()) { return; } CaptureState parent = stack.get(stack.size() - 1); if (parent.mode == CaptureMode.CAPTURING) { - // Deep copy quads before clearing (will be reused by child) - parent.capturedDraws.add( - new CapturedDraw( - ModelQuadUtil.deepCopyQuads(tess.getQuads()), - new CapturingTessellator.Flags(tess.flags))); + // Save parent's quads and clear for child + parent.savedQuads = new ArrayList<>(tess.getQuads()); tess.getQuads().clear(); } } @@ -152,8 +177,8 @@ public class TessellatorManager { ArrayList stack = captureStack.get(); final CapturingTessellator tess = capturingTessellator.get(); - // Save any uncommitted quads if parent is CAPTURING - saveUncommittedQuadsIfNeeded(stack, tess); + // Save parent's quads if parent is CAPTURING + saveParentQuadsIfNeeded(stack, tess); // Validate no orphan quads exist if (!tess.getQuads().isEmpty()) { @@ -166,9 +191,9 @@ public class TessellatorManager { return tess; } - /// Stop the CapturingTessellator and return the captured draws with per-draw flags. - /// The quads are pooled objects - caller MUST copy them if needed beyond their pool lifecycle. - public static List stopCapturingToDraws() { + /// Stop the CapturingTessellator and return the pooled quads. The quads are valid until clearQuads() is called on + /// the CapturingTesselator, which must be done before starting capturing again. + public static List stopCapturingToPooledQuads() { CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!"); ArrayList stack = captureStack.get(); @@ -177,38 +202,29 @@ public class TessellatorManager { // Flush any pending draw if (tess.isDrawing) tess.draw(); - // Get the captured draws from the current level (already stored by processDrawForCapturingTessellator) stack.remove(stack.size() - 1); // Pop - final List draws = new ArrayList<>(currentState.capturedDraws); - tess.restoreTranslation(); - // If nested inside another CAPTURING, we're done - parent's draws are already in parent's capturedDraws - // Note: tess.getQuads() should be empty since processDrawForCapturingTessellator clears after each draw - if (!stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING) { - // Child is done, parent continues (no restoration needed - parent draws already in parent.capturedDraws) - tess.getQuads().clear(); // Defensive clear + boolean isNested = !stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING; + + List quads; + + if (currentState.savedQuads != null) { + // Had nested child - combine saved quads with any new quads + quads = currentState.savedQuads; + quads.addAll(tess.getQuads()); + tess.getQuads().clear(); + } else if (isNested) { + // We are a child - return copy of accumulated quads (will clear for parent) + quads = new ArrayList<>(tess.getQuads()); + tess.getQuads().clear(); } else { - tess.discard(); + // Non-nested common case - return accumulated quads directly + quads = tess.getQuads(); } + // Note: don't discard here - caller owns the pooled quads until clearQuads() - return draws; - } - - /// Stop the CapturingTessellator and return the pooled quads. The quads are valid until clearQuads() is called on - /// the CapturingTesselator, which must be done before starting capturing again. - /// Note: This flattens all draws into a single list, losing per-draw flag information. - /// Use stopCapturingToDraws() if you need per-draw flags. - public static List stopCapturingToPooledQuads() { - final List draws = stopCapturingToDraws(); - - // Flatten all draws into a single quad list - final List allQuads = new ArrayList<>(); - for (int i = 0, size = draws.size(); i < size; i++) { - allQuads.addAll(draws.get(i).quads()); - } - - return allQuads; + return quads; } /// Stops the CapturingTessellator, stores the quads in a buffer (based on the VertexFormat provided), and clears @@ -225,6 +241,151 @@ public class TessellatorManager { return new VertexBuffer(format, GL11.GL_QUADS).upload(stopCapturingToBuffer(format)); } + /** + * Stops the CapturingTessellator and returns separate VBOs for each primitive type captured. This is the preferred + * method when capturing mixed geometry (lines, triangles, quads). + * + * @param format The vertex format for all VBOs + * @return CapturedGeometry with separate VBOs (null fields for types not captured) + */ + public static CapturedGeometry stopCapturingToGeometry(VertexFormat format) { + CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!"); + ArrayList stack = captureStack.get(); + final CapturingTessellator tess = capturingTessellator.get(); + + // Flush any pending draw + if (tess.isDrawing) tess.draw(); + + stack.remove(stack.size() - 1); // Pop + + tess.restoreTranslation(); + + // Group primitives by type using reusable lists from the tessellator + List lines = tess.lineListCache; + List triangles = tess.triangleListCache; + List quads = tess.quadListCache; + lines.clear(); + triangles.clear(); + quads.clear(); + + // Use indexed loops to avoid iterator allocation + List prims = tess.getPrimitives(); + for (int i = 0, size = prims.size(); i < size; i++) { + ModelPrimitiveView prim = prims.get(i); + if (prim instanceof ModelLine ml) { + lines.add(ml); + } else if (prim instanceof ModelTriangle mt) { + triangles.add(mt); + } + // Note: Quads have been moved to collectedQuads by processDrawForCapturingTessellator + } + + // Get quads from collectedQuads (where they were moved for backward compat) + List collectedQuads = tess.getQuads(); + for (int i = 0, size = collectedQuads.size(); i < size; i++) { + ModelQuadViewMutable quad = collectedQuads.get(i); + if (quad instanceof ModelQuad mq) { + quads.add(mq); + } + } + + // Create VBOs for each type that has content + List vbos = new ArrayList<>(); + if (!lines.isEmpty()) vbos.add(createLineVBO(lines, format)); + if (!triangles.isEmpty()) vbos.add(createTriangleVBO(triangles, format)); + if (!quads.isEmpty()) vbos.add(createQuadVBO(quads, format)); + + // Clean up + tess.clearPrimitives(); + tess.clearQuads(); + + if (!stack.isEmpty() && stack.get(stack.size() - 1).mode == CaptureMode.CAPTURING) { + // Nested - parent continues + } else { + tess.discard(); + } + + return new CapturedGeometry(vbos); + } + + private static VertexBuffer createLineVBO(List lines, VertexFormat format) { + ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * lines.size() * 2); + for (int i = 0, size = lines.size(); i < size; i++) { + writePrimitiveToBuffer(lines.get(i), buffer, format); + } + buffer.rewind(); + return new VertexBuffer(format, GL11.GL_LINES).upload(buffer); + } + + private static VertexBuffer createTriangleVBO(List triangles, VertexFormat format) { + ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * triangles.size() * 3); + for (int i = 0, size = triangles.size(); i < size; i++) { + writePrimitiveToBuffer(triangles.get(i), buffer, format); + } + buffer.rewind(); + return new VertexBuffer(format, GL11.GL_TRIANGLES).upload(buffer); + } + + private static VertexBuffer createQuadVBO(List quads, VertexFormat format) { + ByteBuffer buffer = BufferUtils.createByteBuffer(format.getVertexSize() * quads.size() * 4); + for (int i = 0, size = quads.size(); i < size; i++) { + format.writeQuad(quads.get(i), buffer); + } + buffer.rewind(); + return new VertexBuffer(format, GL11.GL_QUADS).upload(buffer); + } + + /** + * Expected vertex size for primitive writing: pos(12) + color(4) + tex(8) + light(4) + normal(4) = 32 bytes + */ + private static final int EXPECTED_PRIMITIVE_VERTEX_SIZE = 32; + + /** + * Writes a primitive's vertices to the buffer using the standard vertex layout. + *

+ * IMPORTANT: This method assumes the vertex format matches the layout: + *

    + *
  • Position: 3 floats (12 bytes)
  • + *
  • Color: 1 int ABGR (4 bytes)
  • + *
  • Texture: 2 floats (8 bytes)
  • + *
  • Light: 1 int (4 bytes)
  • + *
  • Normal: 1 int (4 bytes)
  • + *
+ * Total: 32 bytes per vertex. The format's vertexSize must match. + * + * @throws IllegalArgumentException if format.getVertexSize() != 32 + */ + private static void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer, VertexFormat format) { + if (format.getVertexSize() != EXPECTED_PRIMITIVE_VERTEX_SIZE) { + throw new IllegalArgumentException( + "writePrimitiveToBuffer requires vertex size of " + EXPECTED_PRIMITIVE_VERTEX_SIZE + + " bytes, but format has " + + format.getVertexSize() + + ". Use a compatible format or implement a custom primitive writer."); + } + + // Write each vertex of the primitive + for (int i = 0; i < prim.getVertexCount(); i++) { + // Position (always present) + buffer.putFloat(prim.getX(i)); + buffer.putFloat(prim.getY(i)); + buffer.putFloat(prim.getZ(i)); + + // Color (ABGR format for OpenGL) + buffer.putInt(prim.getColor(i)); + + // Texture coordinates + buffer.putFloat(prim.getTexU(i)); + buffer.putFloat(prim.getTexV(i)); + + // Light (packed lightmap) + buffer.putInt(prim.getLight(i)); + + // Normal (packed) + buffer.putInt(prim.getForgeNormal(i)); + } + } + /** * Populates the passed-in VBO with the data from the CapturingTessellator. If the passed-in VBO is null, it will * create & return a new one. @@ -268,9 +429,11 @@ public class TessellatorManager { } /** - * Intercepts Tessellator.draw() during display list compilation. Extracts quads from the vanilla Tessellator's + * Intercepts Tessellator.draw() during display list compilation. Extracts geometry from the vanilla Tessellator's * buffer and invokes the compiling callback. Only called when shouldInterceptDraw returns true. This is main-thread * only (display list compilation happens on the main thread). + *

+ * GL_QUADS go to collectedQuads; GL_TRIANGLES and other modes go to collectedPrimitives as proper primitives. * * @param tess The vanilla Tessellator instance * @return The result that draw() should return @@ -288,32 +451,55 @@ public class TessellatorManager { throw new IllegalStateException("interceptDraw called but callback is null!"); } - // Build quads from vanilla tess's buffer using main thread capturing tessellator's infrastructure + // Build geometry from vanilla tess's buffer using main thread capturing tessellator's infrastructure + // COMPILING mode: Only GL_QUADS go to quads; triangles and other primitives stay as proper primitives final CapturingTessellator helper = capturingTessellator.get(); - QuadExtractor.buildQuadsFromBuffer( - tess.rawBuffer, - tess.vertexCount, - tess.drawMode, - true, // Vanilla always has texture - tess.hasBrightness, - tess.hasColor, - tess.hasNormals, - 0, - 0, - 0, // Vanilla has no offset - -1, // No shaderBlockId - helper.quadBuf, - helper.collectedQuads, - helper.flags); + if (tess.drawMode == GL11.GL_QUADS) { + QuadExtractor.buildQuadsFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + true, // Vanilla always has texture + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, // Vanilla has no offset + -1, // No shaderBlockId + helper.quadPool, + helper.collectedQuads, + helper.flags); + } else { + // GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, etc. → primitives (not quadrangulated) + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + true, // Vanilla always has texture + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, // Vanilla has no offset + -1, // No shaderBlockId + helper.quadPool, + helper.triPool, + helper.linePool, + helper.collectedPrimitives, + helper.flags); + } - // Invoke callback with collected quads (protect against recursion) + // Invoke callback with collected geometry (protect against recursion) isInCompilingCallback = true; try { - current.callback.onDraw(helper.collectedQuads, helper.flags); + current.callback.onDraw(helper.collectedQuads, helper.collectedPrimitives, helper.flags); } finally { isInCompilingCallback = false; } helper.clearQuads(); + helper.clearPrimitives(); int result = tess.rawBufferIndex * 4; ((ITessellatorInstance) tess).discard(); @@ -322,42 +508,102 @@ public class TessellatorManager { /** * Helper for CapturingTessellator to process its draw() call using shared logic. + *

+ * Mode-specific behavior: + *

    + *
  • COMPILING: Only GL_QUADS → quads; GL_TRIANGLES and other modes → primitives (proper triangles)
  • + *
  • CAPTURING: GL_QUADS and GL_TRIANGLES → quads (quadrangulated for backward compat); other modes → + * primitives
  • + *
*/ static int processDrawForCapturingTessellator(CapturingTessellator tess) { - CaptureState current = peekState(); + final CaptureState current = peekState(); + final boolean isCompiling = current != null && current.mode == CaptureMode.COMPILING; - QuadExtractor.buildQuadsFromBuffer( - tess.rawBuffer, - tess.vertexCount, - tess.drawMode, - tess.hasTexture, - tess.hasBrightness, - tess.hasColor, - tess.hasNormals, - -tess.offset.x, - -tess.offset.y, - -tess.offset.z, - tess.shaderBlockId, - tess.quadBuf, - tess.collectedQuads, - tess.flags); - - if (current != null) { - if (current.mode == CaptureMode.COMPILING) { - current.callback.onDraw(tess.collectedQuads, tess.flags); - tess.clearQuads(); - } else if (current.mode == CaptureMode.CAPTURING) { - // Deep copy quads before pooling (tess.clearQuads releases them for reuse) - // Store per-draw quads+flags (deep copy to preserve across pool reuse) - current.capturedDraws.add( - new CapturedDraw( - ModelQuadUtil.deepCopyQuads(tess.collectedQuads), - new CapturingTessellator.Flags(tess.flags))); - tess.clearQuads(); + if (isCompiling) { + // COMPILING: Only GL_QUADS to quads; triangles and other primitives stay as proper primitives + if (tess.drawMode == GL11.GL_QUADS) { + QuadExtractor.buildQuadsFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + -tess.offset.x, + -tess.offset.y, + -tess.offset.z, + tess.shaderBlockId, + tess.quadPool, + tess.collectedQuads, + tess.flags); + } else { + // GL_TRIANGLES, GL_LINES, GL_LINE_STRIP, etc. → primitives (not quadrangulated) + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + -tess.offset.x, + -tess.offset.y, + -tess.offset.z, + tess.shaderBlockId, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); } + // Invoke callback and clear + current.callback.onDraw(tess.collectedQuads, tess.collectedPrimitives, tess.flags); + tess.clearQuads(); + tess.clearPrimitives(); + } else { + // CAPTURING: GL_QUADS and GL_TRIANGLES to quads (backward compat quadrangulation) + if (tess.drawMode == GL11.GL_QUADS || tess.drawMode == GL11.GL_TRIANGLES) { + QuadExtractor.buildQuadsFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + -tess.offset.x, + -tess.offset.y, + -tess.offset.z, + tess.shaderBlockId, + tess.quadPool, + tess.collectedQuads, + tess.flags); + } else { + // GL_LINES, GL_LINE_STRIP, etc. → primitives + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + -tess.offset.x, + -tess.offset.y, + -tess.offset.z, + tess.shaderBlockId, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + } + // No callback - geometry stays until stop is called } - int result = tess.rawBufferIndex * 4; + final int result = tess.rawBufferIndex * 4; tess.discard(); return result; } @@ -381,6 +627,7 @@ public class TessellatorManager { stack.clear(); tessellator.discard(); tessellator.clearQuads(); + tessellator.clearPrimitives(); isInCompilingCallback = false; } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/line/ModelLine.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/line/ModelLine.java new file mode 100644 index 00000000..68122a80 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/line/ModelLine.java @@ -0,0 +1,160 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.POSITION_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEXTURE_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.vertexOffset; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; + +/** + * A line primitive with 2 vertices. Supports full vertex attributes including position, color, texture coordinates, + * lightmap, and normals. + */ +public class ModelLine implements ModelPrimitiveView { + + private final int[] data = new int[VERTEX_SIZE * 2]; + private int shaderBlockId = -1; + + @Override + public int getVertexCount() { + return 2; + } + + @Override + public float getX(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX]); + } + + @Override + public float getY(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 1]); + } + + @Override + public float getZ(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 2]); + } + + @Override + public int getColor(int idx) { + return data[vertexOffset(idx) + COLOR_INDEX]; + } + + @Override + public float getTexU(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX]); + } + + @Override + public float getTexV(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX + 1]); + } + + @Override + public int getLight(int idx) { + return data[vertexOffset(idx) + LIGHT_INDEX]; + } + + @Override + public int getForgeNormal(int idx) { + return data[vertexOffset(idx) + NORMAL_INDEX]; + } + + // Setters for building the line + + public void setX(int idx, float x) { + data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x); + } + + public void setY(int idx, float y) { + data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y); + } + + public void setZ(int idx, float z) { + data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z); + } + + public void setColor(int idx, int color) { + data[vertexOffset(idx) + COLOR_INDEX] = color; + } + + public void setTexU(int idx, float u) { + data[vertexOffset(idx) + TEXTURE_INDEX] = Float.floatToRawIntBits(u); + } + + public void setTexV(int idx, float v) { + data[vertexOffset(idx) + TEXTURE_INDEX + 1] = Float.floatToRawIntBits(v); + } + + public void setLight(int idx, int light) { + data[vertexOffset(idx) + LIGHT_INDEX] = light; + } + + public void setForgeNormal(int idx, int normal) { + data[vertexOffset(idx) + NORMAL_INDEX] = normal; + } + + /** + * Sets vertex data from a raw tessellator buffer. + * + * @param rawBuffer The tessellator's raw int[] buffer + * @param srcOffset Offset to the first vertex in the source buffer + */ + public void setState(int[] rawBuffer, int srcOffset) { + System.arraycopy(rawBuffer, srcOffset, data, 0, VERTEX_SIZE * 2); + } + + /** + * Copies a single vertex from a raw buffer directly to this line's data. Avoids int→float→int conversions by + * copying raw ints directly. + * + * @param rawBuffer The tessellator's raw int[] buffer + * @param srcOffset Offset to the vertex in the source buffer + * @param destIdx Destination vertex index (0 or 1) + */ + public void copyVertexFromBuffer(int[] rawBuffer, int srcOffset, int destIdx) { + System.arraycopy(rawBuffer, srcOffset, data, vertexOffset(destIdx), VERTEX_SIZE); + } + + public int getShaderBlockId() { + return shaderBlockId; + } + + public void setShaderBlockId(int shaderBlockId) { + this.shaderBlockId = shaderBlockId; + } + + /** + * Applies a position offset to all vertices. + * + * @param offsetX X offset to add to all vertices + * @param offsetY Y offset to add to all vertices + * @param offsetZ Z offset to add to all vertices + */ + public void applyOffset(int offsetX, int offsetY, int offsetZ) { + if (offsetX == 0 && offsetY == 0 && offsetZ == 0) return; + + for (int i = 0; i < 2; i++) { + final int offset = vertexOffset(i); + data[offset + POSITION_INDEX] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX]) + offsetX); + data[offset + POSITION_INDEX + 1] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 1]) + offsetY); + data[offset + POSITION_INDEX + 2] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 2]) + offsetZ); + } + } + + /** + * Copy data from another ModelLine. + */ + public ModelLine copyFrom(ModelLine source) { + System.arraycopy(source.data, 0, this.data, 0, VERTEX_SIZE * 2); + this.shaderBlockId = source.shaderBlockId; + return this; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/primitive/ModelPrimitiveView.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/primitive/ModelPrimitiveView.java new file mode 100644 index 00000000..db16a52c --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/primitive/ModelPrimitiveView.java @@ -0,0 +1,53 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive; + +/** + * Base interface for all primitive types (lines, triangles, quads). Provides common vertex accessors with variable + * vertex count. + */ +public interface ModelPrimitiveView { + + /** + * @return The number of vertices in this primitive (2 for lines, 3 for triangles, 4 for quads) + */ + int getVertexCount(); + + /** + * @return The x-position of the vertex at index {@param idx} + */ + float getX(int idx); + + /** + * @return The y-position of the vertex at index {@param idx} + */ + float getY(int idx); + + /** + * @return The z-position of the vertex at index {@param idx} + */ + float getZ(int idx); + + /** + * @return The integer-encoded color of the vertex at index {@param idx} + */ + int getColor(int idx); + + /** + * @return The texture x-coordinate for the vertex at index {@param idx} + */ + float getTexU(int idx); + + /** + * @return The texture y-coordinate for the vertex at index {@param idx} + */ + float getTexV(int idx); + + /** + * @return The packed lightmap coordinates for the vertex at index {@param idx} + */ + int getLight(int idx); + + /** + * @return The packed normal vector for the vertex at index {@param idx} + */ + int getForgeNormal(int idx); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuad.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuad.java index daaab68e..b8bf80d2 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuad.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuad.java @@ -260,9 +260,9 @@ public class ModelQuad implements ModelQuadViewMutable { private void clearLightmap() { setLight(0, DEFAULT_LIGHTMAP); - setLight(0, DEFAULT_LIGHTMAP); - setLight(0, DEFAULT_LIGHTMAP); - setLight(0, DEFAULT_LIGHTMAP); + setLight(1, DEFAULT_LIGHTMAP); + setLight(2, DEFAULT_LIGHTMAP); + setLight(3, DEFAULT_LIGHTMAP); } /** diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuadView.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuadView.java index ffc17894..9fbde75d 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuadView.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/quad/ModelQuadView.java @@ -1,16 +1,24 @@ package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFlags; /** * Provides a read-only view of a model quad. For mutable access to a model quad, see {@link ModelQuadViewMutable}. + * Extends {@link ModelPrimitiveView} for compatibility with the primitive rendering pipeline. */ -public interface ModelQuadView { +public interface ModelQuadView extends ModelPrimitiveView { + + @Override + default int getVertexCount() { + return 4; + } /** * @return The x-position of the vertex at index {@param idx} */ + @Override float getX(int idx); /** diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/tri/ModelTriangle.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/tri/ModelTriangle.java new file mode 100644 index 00000000..6da81eca --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/model/tri/ModelTriangle.java @@ -0,0 +1,226 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri; + +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_LIGHTMAP; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.POSITION_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEXTURE_INDEX; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE; +import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.vertexOffset; + +import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; + +/** + * A triangle primitive with 3 vertices. Supports full vertex attributes including position, color, texture coordinates, + * lightmap, and normals. + */ +public class ModelTriangle implements ModelPrimitiveView { + + private final int[] data = new int[VERTEX_SIZE * 3]; + private int computedNormal; + private int shaderBlockId = -1; + + @Override + public int getVertexCount() { + return 3; + } + + @Override + public float getX(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX]); + } + + @Override + public float getY(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 1]); + } + + @Override + public float getZ(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + POSITION_INDEX + 2]); + } + + @Override + public int getColor(int idx) { + return data[vertexOffset(idx) + COLOR_INDEX]; + } + + @Override + public float getTexU(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX]); + } + + @Override + public float getTexV(int idx) { + return Float.intBitsToFloat(data[vertexOffset(idx) + TEXTURE_INDEX + 1]); + } + + @Override + public int getLight(int idx) { + return data[vertexOffset(idx) + LIGHT_INDEX]; + } + + @Override + public int getForgeNormal(int idx) { + return data[vertexOffset(idx) + NORMAL_INDEX]; + } + + // Setters + + public void setX(int idx, float x) { + data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x); + computedNormal = 0; // Invalidate cached normal + } + + public void setY(int idx, float y) { + data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y); + computedNormal = 0; + } + + public void setZ(int idx, float z) { + data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z); + computedNormal = 0; + } + + public void setColor(int idx, int color) { + data[vertexOffset(idx) + COLOR_INDEX] = color; + } + + public void setTexU(int idx, float u) { + data[vertexOffset(idx) + TEXTURE_INDEX] = Float.floatToRawIntBits(u); + } + + public void setTexV(int idx, float v) { + data[vertexOffset(idx) + TEXTURE_INDEX + 1] = Float.floatToRawIntBits(v); + } + + public void setLight(int idx, int light) { + data[vertexOffset(idx) + LIGHT_INDEX] = light; + } + + public void setForgeNormal(int idx, int normal) { + data[vertexOffset(idx) + NORMAL_INDEX] = normal; + } + + /** + * Sets vertex data from a raw tessellator buffer. + * + * @param rawBuffer The tessellator's raw int[] buffer + * @param srcOffset Offset to the first vertex in the source buffer + * @param flags Vertex format flags + */ + public void setState(int[] rawBuffer, int srcOffset, CapturingTessellator.Flags flags) { + System.arraycopy(rawBuffer, srcOffset, data, 0, VERTEX_SIZE * 3); + + if (!flags.hasColor) clearColors(); + if (!flags.hasNormals) clearNormals(); + if (!flags.hasBrightness) clearLightmap(); + + computedNormal = 0; + } + + /** + * Copies a single vertex from a raw buffer directly to this triangle's data. Avoids int→float→int conversions by + * copying raw ints directly. + * + * @param rawBuffer The tessellator's raw int[] buffer + * @param srcOffset Offset to the vertex in the source buffer + * @param destIdx Destination vertex index (0, 1, or 2) + */ + public void copyVertexFromBuffer(int[] rawBuffer, int srcOffset, int destIdx) { + System.arraycopy(rawBuffer, srcOffset, data, vertexOffset(destIdx), VERTEX_SIZE); + } + + /** + * Calculate the face normal from the triangle's vertices. + */ + public int getComputedFaceNormal() { + if (computedNormal != 0) return computedNormal; + + final float x0 = getX(0), y0 = getY(0), z0 = getZ(0); + final float x1 = getX(1), y1 = getY(1), z1 = getZ(1); + final float x2 = getX(2), y2 = getY(2), z2 = getZ(2); + + // Cross product of (v1-v0) x (v2-v0) + final float dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0; + final float dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0; + + float nx = dy1 * dz2 - dz1 * dy2; + float ny = dz1 * dx2 - dx1 * dz2; + float nz = dx1 * dy2 - dy1 * dx2; + + float len = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); + if (len != 0) { + nx /= len; + ny /= len; + nz /= len; + } + + computedNormal = NormI8.pack(nx, ny, nz); + return computedNormal; + } + + private void clearColors() { + setColor(0, DEFAULT_COLOR); + setColor(1, DEFAULT_COLOR); + setColor(2, DEFAULT_COLOR); + } + + private void clearNormals() { + computedNormal = 0; + data[vertexOffset(0) + NORMAL_INDEX] = 0; + data[vertexOffset(1) + NORMAL_INDEX] = 0; + data[vertexOffset(2) + NORMAL_INDEX] = 0; + } + + private void clearLightmap() { + setLight(0, DEFAULT_LIGHTMAP); + setLight(1, DEFAULT_LIGHTMAP); + setLight(2, DEFAULT_LIGHTMAP); + } + + public int getShaderBlockId() { + return shaderBlockId; + } + + public void setShaderBlockId(int shaderBlockId) { + this.shaderBlockId = shaderBlockId; + } + + /** + * Applies a position offset to all vertices. More efficient than calling setX/setY/setZ individually as it + * invalidates the computed normal only once. + * + * @param offsetX X offset to add to all vertices + * @param offsetY Y offset to add to all vertices + * @param offsetZ Z offset to add to all vertices + */ + public void applyOffset(int offsetX, int offsetY, int offsetZ) { + if (offsetX == 0 && offsetY == 0 && offsetZ == 0) return; + + for (int i = 0; i < 3; i++) { + final int offset = vertexOffset(i); + data[offset + POSITION_INDEX] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX]) + offsetX); + data[offset + POSITION_INDEX + 1] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 1]) + offsetY); + data[offset + POSITION_INDEX + 2] = Float + .floatToRawIntBits(Float.intBitsToFloat(data[offset + POSITION_INDEX + 2]) + offsetZ); + } + computedNormal = 0; // Invalidate once at the end + } + + /** + * Copy data from another ModelTriangle. + */ + public ModelTriangle copyFrom(ModelTriangle source) { + System.arraycopy(source.data, 0, this.data, 0, VERTEX_SIZE * 3); + this.computedNormal = source.computedNormal; + this.shaderBlockId = source.shaderBlockId; + return this; + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractorTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractorTest.java new file mode 100644 index 00000000..74461067 --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/client/renderer/PrimitiveExtractorTest.java @@ -0,0 +1,776 @@ +package com.gtnewhorizon.gtnhlib.client.renderer; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; + +/** + * Unit tests for PrimitiveExtractor - tests extraction of lines, triangles, quads from tessellator buffers. + */ +public class PrimitiveExtractorTest { + + @Test + void testLineExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw lines + tess.startDrawing(GL11.GL_LINES); + tess.pos(0, 0, 0).color(255, 0, 0, 255).endVertex(); + tess.pos(1, 1, 1).color(255, 0, 0, 255).endVertex(); + tess.pos(2, 0, 0).color(0, 255, 0, 255).endVertex(); + tess.pos(3, 1, 1).color(0, 255, 0, 255).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(2, primitives.size(), "Should have extracted 2 lines"); + + // Verify first line + ModelPrimitiveView line1 = primitives.get(0); + assertTrue(line1 instanceof ModelLine, "First primitive should be ModelLine"); + assertEquals(2, line1.getVertexCount(), "Line should have 2 vertices"); + assertEquals(0.0f, line1.getX(0), 0.001f, "Line1 start X"); + assertEquals(1.0f, line1.getX(1), 0.001f, "Line1 end X"); + + // Verify second line + ModelPrimitiveView line2 = primitives.get(1); + assertTrue(line2 instanceof ModelLine, "Second primitive should be ModelLine"); + assertEquals(2.0f, line2.getX(0), 0.001f, "Line2 start X"); + assertEquals(3.0f, line2.getX(1), 0.001f, "Line2 end X"); + + tess.clearPrimitives(); + } + + @Test + void testTriangleExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawing(GL11.GL_TRIANGLES); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0.5f, 1, 0).tex(0.5f, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(1, primitives.size(), "Should have extracted 1 triangle"); + + ModelPrimitiveView tri = primitives.get(0); + assertTrue(tri instanceof ModelTriangle, "Primitive should be ModelTriangle"); + assertEquals(3, tri.getVertexCount(), "Triangle should have 3 vertices"); + assertEquals(0.0f, tri.getX(0), 0.001f, "Triangle v0 X"); + assertEquals(1.0f, tri.getX(1), 0.001f, "Triangle v1 X"); + assertEquals(0.5f, tri.getX(2), 0.001f, "Triangle v2 X"); + + tess.clearPrimitives(); + } + + @Test + void testQuadExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawingQuads(); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(1, primitives.size(), "Should have extracted 1 quad"); + + ModelPrimitiveView quad = primitives.get(0); + assertTrue(quad instanceof ModelQuad, "Primitive should be ModelQuad"); + assertEquals(4, quad.getVertexCount(), "Quad should have 4 vertices"); + + tess.clearPrimitives(); + } + + @Test + void testMixedPrimitiveExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw quads + tess.startDrawingQuads(); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + // End drawing state and draw lines + tess.isDrawing = false; + tess.reset(); + tess.startDrawing(GL11.GL_LINES); + tess.pos(2, 0, 0).color(255, 0, 0, 255).endVertex(); + tess.pos(3, 1, 1).color(255, 0, 0, 255).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(2, primitives.size(), "Should have 2 primitives (1 quad + 1 line)"); + + long quads = primitives.stream().filter(p -> p instanceof ModelQuad).count(); + long lines = primitives.stream().filter(p -> p instanceof ModelLine).count(); + assertEquals(1, quads, "Should have 1 quad"); + assertEquals(1, lines, "Should have 1 line"); + + tess.clearPrimitives(); + } + + @Test + void testLineStripExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw line strip: 4 vertices → 3 line segments + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.pos(0, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 1, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(0, 1, 0).color(255, 255, 255, 255).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(3, primitives.size(), "LINE_STRIP with 4 vertices should produce 3 lines"); + + for (ModelPrimitiveView prim : primitives) { + assertTrue(prim instanceof ModelLine, "All primitives should be ModelLine"); + } + + tess.clearPrimitives(); + } + + @Test + void testLineLoopExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw line loop: 4 vertices → 4 line segments (including closing segment) + tess.startDrawing(GL11.GL_LINE_LOOP); + tess.pos(0, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 1, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(0, 1, 0).color(255, 255, 255, 255).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(4, primitives.size(), "LINE_LOOP with 4 vertices should produce 4 lines"); + + // Verify closing segment connects last to first + ModelLine closingLine = (ModelLine) primitives.get(3); + assertEquals(0.0f, closingLine.getX(0), 0.001f, "Closing line start should be at last vertex X"); + assertEquals(1.0f, closingLine.getY(0), 0.001f, "Closing line start should be at last vertex Y"); + assertEquals(0.0f, closingLine.getX(1), 0.001f, "Closing line end should be at first vertex X"); + assertEquals(0.0f, closingLine.getY(1), 0.001f, "Closing line end should be at first vertex Y"); + + tess.clearPrimitives(); + } + + @Test + void testTriangleStripExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw triangle strip: 4 vertices → 2 triangles + tess.startDrawing(GL11.GL_TRIANGLE_STRIP); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(2, primitives.size(), "TRIANGLE_STRIP with 4 vertices should produce 2 triangles"); + + for (ModelPrimitiveView prim : primitives) { + assertTrue(prim instanceof ModelTriangle, "All primitives should be ModelTriangle"); + assertEquals(3, prim.getVertexCount()); + } + + tess.clearPrimitives(); + } + + @Test + void testTriangleFanExtraction() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw triangle fan: center + 4 outer vertices → 3 triangles + tess.startDrawing(GL11.GL_TRIANGLE_FAN); + tess.pos(0.5f, 0.5f, 0).tex(0.5f, 0.5f).endVertex(); // center + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(3, primitives.size(), "TRIANGLE_FAN with 5 vertices should produce 3 triangles"); + + // All triangles should share vertex 0 (the center) + for (ModelPrimitiveView prim : primitives) { + assertTrue(prim instanceof ModelTriangle, "All primitives should be ModelTriangle"); + ModelTriangle tri = (ModelTriangle) prim; + assertEquals(0.5f, tri.getX(0), 0.001f, "All triangles should share center vertex X"); + assertEquals(0.5f, tri.getY(0), 0.001f, "All triangles should share center vertex Y"); + } + + tess.clearPrimitives(); + } + + @Test + void testFlagsDrawModeTracking() { + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawing(GL11.GL_LINES); + tess.pos(0, 0, 0).endVertex(); + tess.pos(1, 1, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + assertEquals(GL11.GL_LINES, tess.flags.drawMode, "Flags should track GL_LINES drawMode"); + + tess.clearPrimitives(); + } + + @Test + void testModelLineFullAttributes() { + // Test that ModelLine properly stores and retrieves all vertex attributes + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawing(GL11.GL_LINES); + tess.pos(0, 0, 0).tex(0.25f, 0.75f).color(255, 128, 64, 200).brightness(0xF000F0).normal(0, 1, 0).endVertex(); + tess.pos(1, 1, 1).tex(0.5f, 0.5f).color(100, 150, 200, 255).brightness(0xA000A0).normal(1, 0, 0).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + ModelLine line = (ModelLine) tess.getPrimitives().get(0); + + assertEquals(2, line.getVertexCount(), "Line should have 2 vertices"); + + // Verify first vertex + assertEquals(0.0f, line.getX(0), 0.001f); + assertEquals(0.25f, line.getTexU(0), 0.001f, "Line should store texU"); + assertEquals(0.75f, line.getTexV(0), 0.001f, "Line should store texV"); + assertEquals(0xF000F0, line.getLight(0), "Line should store brightness"); + assertNotEquals(0, line.getForgeNormal(0), "Line should store normal"); + + // Verify second vertex + assertEquals(1.0f, line.getX(1), 0.001f); + assertEquals(0.5f, line.getTexU(1), 0.001f); + assertEquals(0.5f, line.getTexV(1), 0.001f); + + tess.clearPrimitives(); + } + + @Test + void testModelTriangleNormalComputation() { + ModelTriangle tri = new ModelTriangle(); + + // Create a triangle in XY plane facing +Z + tri.setX(0, 0); + tri.setY(0, 0); + tri.setZ(0, 0); + tri.setX(1, 1); + tri.setY(1, 0); + tri.setZ(1, 0); + tri.setX(2, 0); + tri.setY(2, 1); + tri.setZ(2, 0); + + int normal = tri.getComputedFaceNormal(); + assertNotEquals(0, normal, "Computed normal should not be zero"); + } + + @Test + void testFlagsEquality() { + CapturingTessellator.Flags flags1 = new CapturingTessellator.Flags(true, true, true, true); + flags1.drawMode = GL11.GL_QUADS; + + CapturingTessellator.Flags flags2 = new CapturingTessellator.Flags(true, true, true, true); + flags2.drawMode = GL11.GL_LINES; + + assertNotEquals(flags1, flags2, "Flags with different drawMode should not be equal"); + + flags2.drawMode = GL11.GL_QUADS; + assertEquals(flags1, flags2, "Flags with same drawMode should be equal"); + } + + @Test + void testQuadsToTrianglesConversion() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw a quad: v0(0,0), v1(1,0), v2(1,1), v3(0,1) + tess.startDrawingQuads(); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + + // Pass convertQuadsToTriangles=true + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags, + true); // convertQuadsToTriangles + + List primitives = tess.getPrimitives(); + + // Should have 2 triangles, not 1 quad + assertEquals(2, primitives.size(), "Quad should be converted to 2 triangles"); + assertTrue(primitives.get(0) instanceof ModelTriangle, "First primitive should be triangle"); + assertTrue(primitives.get(1) instanceof ModelTriangle, "Second primitive should be triangle"); + + // Flags should indicate GL_TRIANGLES + assertEquals(GL11.GL_TRIANGLES, tess.flags.drawMode, "drawMode should be GL_TRIANGLES after conversion"); + + // Triangle 1: v0, v1, v2 -> (0,0), (1,0), (1,1) + ModelTriangle tri1 = (ModelTriangle) primitives.get(0); + assertEquals(0.0f, tri1.getX(0), 0.001f); + assertEquals(0.0f, tri1.getY(0), 0.001f); + assertEquals(1.0f, tri1.getX(1), 0.001f); + assertEquals(0.0f, tri1.getY(1), 0.001f); + assertEquals(1.0f, tri1.getX(2), 0.001f); + assertEquals(1.0f, tri1.getY(2), 0.001f); + + // Triangle 2: v0, v2, v3 -> (0,0), (1,1), (0,1) + ModelTriangle tri2 = (ModelTriangle) primitives.get(1); + assertEquals(0.0f, tri2.getX(0), 0.001f); + assertEquals(0.0f, tri2.getY(0), 0.001f); + assertEquals(1.0f, tri2.getX(1), 0.001f); + assertEquals(1.0f, tri2.getY(1), 0.001f); + assertEquals(0.0f, tri2.getX(2), 0.001f); + assertEquals(1.0f, tri2.getY(2), 0.001f); + + tess.clearPrimitives(); + } + + @Test + void testDegeneratePrimitiveFiltering() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw a degenerate line (both vertices at same position) + tess.startDrawing(GL11.GL_LINES); + tess.pos(5, 5, 5).color(255, 0, 0, 255).endVertex(); + tess.pos(5, 5, 5).color(255, 0, 0, 255).endVertex(); // Same as first vertex + // Draw a valid line + tess.pos(0, 0, 0).color(0, 255, 0, 255).endVertex(); + tess.pos(1, 1, 1).color(0, 255, 0, 255).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + // Degenerate line should be filtered out, only valid line remains + assertEquals(1, primitives.size(), "Degenerate line should be filtered out"); + + ModelLine validLine = (ModelLine) primitives.get(0); + assertEquals(0.0f, validLine.getX(0), 0.001f, "Valid line should start at origin"); + + tess.clearPrimitives(); + } + + @Test + void testDegenerateTriangleFiltering() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw a degenerate triangle (all vertices at same position) + tess.startDrawing(GL11.GL_TRIANGLES); + tess.pos(3, 3, 3).tex(0, 0).endVertex(); + tess.pos(3, 3, 3).tex(0, 0).endVertex(); + tess.pos(3, 3, 3).tex(0, 0).endVertex(); + // Draw a valid triangle + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0.5f, 1, 0).tex(0.5f, 1).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(1, primitives.size(), "Degenerate triangle should be filtered out"); + + tess.clearPrimitives(); + } + + @Test + void testLineOffsetApplication() { + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawing(GL11.GL_LINES); + tess.pos(0, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 1, 1).color(255, 255, 255, 255).endVertex(); + + // Apply offset of (10, 20, 30) + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 10, + 20, + 30, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(1, primitives.size()); + + ModelLine line = (ModelLine) primitives.get(0); + // Vertex 0: (0,0,0) + (10,20,30) = (10,20,30) + assertEquals(10.0f, line.getX(0), 0.001f, "Line start X should have offset applied"); + assertEquals(20.0f, line.getY(0), 0.001f, "Line start Y should have offset applied"); + assertEquals(30.0f, line.getZ(0), 0.001f, "Line start Z should have offset applied"); + // Vertex 1: (1,1,1) + (10,20,30) = (11,21,31) + assertEquals(11.0f, line.getX(1), 0.001f, "Line end X should have offset applied"); + assertEquals(21.0f, line.getY(1), 0.001f, "Line end Y should have offset applied"); + assertEquals(31.0f, line.getZ(1), 0.001f, "Line end Z should have offset applied"); + + tess.clearPrimitives(); + } + + @Test + void testLineStripOffsetApplication() { + CapturingTessellator tess = new CapturingTessellator(); + + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.pos(0, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 0, 0).color(255, 255, 255, 255).endVertex(); + tess.pos(1, 1, 0).color(255, 255, 255, 255).endVertex(); + + // Apply offset of (5, 5, 5) + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 5, + 5, + 5, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + List primitives = tess.getPrimitives(); + assertEquals(2, primitives.size(), "LINE_STRIP with 3 vertices should produce 2 lines"); + + // First line: (0,0,0)-(1,0,0) + offset = (5,5,5)-(6,5,5) + ModelLine line1 = (ModelLine) primitives.get(0); + assertEquals(5.0f, line1.getX(0), 0.001f); + assertEquals(6.0f, line1.getX(1), 0.001f); + + // Second line: (1,0,0)-(1,1,0) + offset = (6,5,5)-(6,6,5) + ModelLine line2 = (ModelLine) primitives.get(1); + assertEquals(6.0f, line2.getX(0), 0.001f); + assertEquals(6.0f, line2.getX(1), 0.001f); + assertEquals(6.0f, line2.getY(1), 0.001f); + + tess.clearPrimitives(); + } + + @Test + void testLineStripPreservesFullAttributes() { + CapturingTessellator tess = new CapturingTessellator(); + + // Draw line strip with full attributes + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.pos(0, 0, 0).tex(0.25f, 0.5f).color(255, 128, 64, 200).brightness(0xF000F0).normal(0, 1, 0).endVertex(); + tess.pos(1, 1, 1).tex(0.75f, 0.25f).color(100, 150, 200, 255).brightness(0xA000A0).normal(1, 0, 0).endVertex(); + + PrimitiveExtractor.buildPrimitivesFromBuffer( + tess.rawBuffer, + tess.vertexCount, + tess.drawMode, + tess.hasTexture, + tess.hasBrightness, + tess.hasColor, + tess.hasNormals, + 0, + 0, + 0, + -1, + tess.quadPool, + tess.triPool, + tess.linePool, + tess.collectedPrimitives, + tess.flags); + + ModelLine line = (ModelLine) tess.getPrimitives().get(0); + + // Verify all attributes were preserved from first vertex + assertEquals(0.25f, line.getTexU(0), 0.001f, "Line strip should preserve texU"); + assertEquals(0.5f, line.getTexV(0), 0.001f, "Line strip should preserve texV"); + assertEquals(0xF000F0, line.getLight(0), "Line strip should preserve brightness"); + assertNotEquals(0, line.getForgeNormal(0), "Line strip should preserve normal"); + + // Verify second vertex attributes + assertEquals(0.75f, line.getTexU(1), 0.001f, "Line strip should preserve texU for vertex 1"); + assertEquals(0.25f, line.getTexV(1), 0.001f, "Line strip should preserve texV for vertex 1"); + + tess.clearPrimitives(); + } + + @Test + void testIsEmptyPrimitiveUtility() { + // Test the shared utility directly + int[] buffer = new int[16]; // 2 vertices * 8 ints + + // All zeros - degenerate + assertTrue(PrimitiveExtractor.isEmptyPrimitive(buffer, 0, 2), "All-zero vertices should be empty"); + + // Different X values - not degenerate + buffer[0] = Float.floatToRawIntBits(0.0f); + buffer[8] = Float.floatToRawIntBits(1.0f); // Second vertex X is different + assertFalse(PrimitiveExtractor.isEmptyPrimitive(buffer, 0, 2), "Different X should not be empty"); + + // Reset and test Y difference + buffer[0] = 0; + buffer[8] = 0; + buffer[1] = Float.floatToRawIntBits(0.0f); + buffer[9] = Float.floatToRawIntBits(1.0f); // Second vertex Y is different + assertFalse(PrimitiveExtractor.isEmptyPrimitive(buffer, 0, 2), "Different Y should not be empty"); + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.java index a493fa9e..41ef232a 100644 --- a/src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.java +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.java @@ -2,14 +2,16 @@ package com.gtnewhorizon.gtnhlib.test.client.renderer; import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.lwjgl.opengl.GL11; -import com.gtnewhorizon.gtnhlib.client.renderer.CapturedDraw; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; /** @@ -34,9 +36,9 @@ public class TessellatorManagerTest { @Test void testNestedCompiling() { // Nested COMPILING is now ALLOWED for nested display list compilation - TessellatorManager.setCompiling((quads, flags) -> {}); + TessellatorManager.setCompiling((quads, primitives, flags) -> {}); assertDoesNotThrow( - () -> TessellatorManager.setCompiling((quads, flags) -> {}), + () -> TessellatorManager.setCompiling((quads, primitives, flags) -> {}), "Nested setCompiling() should be allowed"); TessellatorManager.stopCompiling(); // Stop inner TessellatorManager.stopCompiling(); // Stop outer @@ -48,7 +50,7 @@ public class TessellatorManagerTest { final java.util.List callOrder = new java.util.ArrayList<>(); // Outer compilation - TessellatorManager.setCompiling((quads, flags) -> { callOrder.add("outer"); }); + TessellatorManager.setCompiling((quads, primitives, flags) -> { callOrder.add("outer"); }); CapturingTessellator outerTess = (CapturingTessellator) TessellatorManager.get(); outerTess.startDrawingQuads(); @@ -62,7 +64,7 @@ public class TessellatorManagerTest { assertEquals("outer", callOrder.get(0)); // Nested inner compilation - TessellatorManager.setCompiling((quads, flags) -> { callOrder.add("inner"); }); + TessellatorManager.setCompiling((quads, primitives, flags) -> { callOrder.add("inner"); }); CapturingTessellator innerTess = (CapturingTessellator) TessellatorManager.get(); assertSame(outerTess, innerTess, "Should reuse same tessellator instance"); @@ -119,7 +121,7 @@ public class TessellatorManagerTest { @Test void testNestingCapturingInsideCompiling() { - TessellatorManager.setCompiling((quads, flags) -> {}); + TessellatorManager.setCompiling((quads, primitives, flags) -> {}); assertDoesNotThrow( TessellatorManager::startCapturing, "startCapturing() when compiling should be allowed for nesting"); @@ -130,18 +132,18 @@ public class TessellatorManagerTest { @Test void testSetCompilingAndStop() { // Basic lifecycle test - should not throw - TessellatorManager.setCompiling((quads, flags) -> {}); + TessellatorManager.setCompiling((quads, primitives, flags) -> {}); TessellatorManager.stopCompiling(); } @Test void testCleanupClearsCompilingState() { - TessellatorManager.setCompiling((quads, flags) -> {}); + TessellatorManager.setCompiling((quads, primitives, flags) -> {}); TessellatorManager.cleanup(); // After cleanup, compiling should be cleared // This means we should be able to set compiling again without error - assertDoesNotThrow(() -> TessellatorManager.setCompiling((quads, flags) -> {})); + assertDoesNotThrow(() -> TessellatorManager.setCompiling((quads, primitives, flags) -> {})); TessellatorManager.stopCompiling(); } @@ -171,13 +173,13 @@ public class TessellatorManagerTest { parentTess.pos(0, 1, 0).tex(0, 1).endVertex(); parentTess.draw(); - // After draw(), quads are moved to capturedDraws, so tess.getQuads() is empty - assertEquals(0, parentTess.getQuads().size(), "After draw(), quads moved to capturedDraws"); + // In index-based mode, quads accumulate in collectedQuads until nesting or stop + assertEquals(1, parentTess.getQuads().size(), "After draw(), quads accumulate in collectedQuads"); - // Start nested child capture + // Start nested child capture - parent's quads are preserved, list cleared for child CapturingTessellator childTess = TessellatorManager.startCapturingAndGet(); assertSame(parentTess, childTess, "Should reuse same tessellator instance"); - assertEquals(0, childTess.getQuads().size(), "Child should start with 0 quads"); + assertEquals(0, childTess.getQuads().size(), "Child should start with 0 quads (parent's were saved)"); childTess.startDrawingQuads(); childTess.pos(2, 0, 0).tex(0, 0).endVertex(); @@ -190,8 +192,8 @@ public class TessellatorManagerTest { assertEquals(1, childQuads.size(), "Child should have captured 1 quad"); assertEquals(2.0f, childQuads.get(0).getX(0), 0.001f, "Child quad should have correct position"); - // After popping child, parent continues with empty tess.getQuads() (draws in capturedDraws) - assertEquals(0, parentTess.getQuads().size(), "tess.getQuads() empty, draws in capturedDraws"); + // After popping child, parent continues with cleared list (its quads already saved) + assertEquals(0, parentTess.getQuads().size(), "tess.getQuads() cleared for parent to continue"); // Parent can continue capturing parentTess.startDrawingQuads(); @@ -268,75 +270,12 @@ public class TessellatorManagerTest { CapturingTessellator.Flags flags4 = new CapturingTessellator.Flags(flags1); assertEquals(flags1, flags4, "Copy constructor should produce equal flags"); assertEquals(flags1.hashCode(), flags4.hashCode(), "Copied flags should have same hashCode"); - - // Verify batching use case: flags from different CapturedDraws can be compared - TessellatorManager.startCapturing(); - CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); - - // Draw 1 - tess.startDrawingQuads(); - tess.pos(0, 0, 0).tex(0, 0).endVertex(); - tess.pos(1, 0, 0).tex(1, 0).endVertex(); - tess.pos(1, 1, 0).tex(1, 1).endVertex(); - tess.pos(0, 1, 0).tex(0, 1).endVertex(); - tess.draw(); - - // Draw 2 with same settings - tess.startDrawingQuads(); - tess.pos(2, 0, 0).tex(0, 0).endVertex(); - tess.pos(3, 0, 0).tex(1, 0).endVertex(); - tess.pos(3, 1, 0).tex(1, 1).endVertex(); - tess.pos(2, 1, 0).tex(0, 1).endVertex(); - tess.draw(); - - List draws = TessellatorManager.stopCapturingToDraws(); - assertEquals(2, draws.size()); - - // Flags from different draws should be equal if settings were identical - assertEquals( - draws.get(0).flags(), - draws.get(1).flags(), - "Flags from draws with identical settings should be equal"); - assertEquals( - draws.get(0).flags().hashCode(), - draws.get(1).flags().hashCode(), - "Equal flags should have same hashCode for batching"); - } - - @Test - void testPerDrawFlagTracking() { - // Test that per-draw flags are tracked correctly - TessellatorManager.startCapturing(); - CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); - - // First draw with texture - tess.startDrawingQuads(); - tess.pos(0, 0, 0).tex(0, 0).endVertex(); - tess.pos(1, 0, 0).tex(1, 0).endVertex(); - tess.pos(1, 1, 0).tex(1, 1).endVertex(); - tess.pos(0, 1, 0).tex(0, 1).endVertex(); - tess.draw(); - - // Second draw with different setup - tess.startDrawingQuads(); - tess.pos(2, 0, 0).tex(0, 0).endVertex(); - tess.pos(3, 0, 0).tex(1, 0).endVertex(); - tess.pos(3, 1, 0).tex(1, 1).endVertex(); - tess.pos(2, 1, 0).tex(0, 1).endVertex(); - tess.draw(); - - List draws = TessellatorManager.stopCapturingToDraws(); - assertEquals(2, draws.size(), "Should have 2 separate draws"); - assertEquals(1, draws.get(0).quads().size(), "First draw should have 1 quad"); - assertEquals(1, draws.get(1).quads().size(), "Second draw should have 1 quad"); - assertEquals(0.0f, draws.get(0).quads().get(0).getX(0), 0.001f, "First draw quad at x=0"); - assertEquals(2.0f, draws.get(1).quads().get(0).getX(0), 0.001f, "Second draw quad at x=2"); } @Test void testNestedCapturingWithCompilingParent() { // Test COMPILING → CAPTURING → CAPTURING (Angelica use case) - TessellatorManager.setCompiling((quads, flags) -> { + TessellatorManager.setCompiling((quads, primitives, flags) -> { // Compiling callback - start capturing inside CapturingTessellator parentTess = TessellatorManager.startCapturingAndGet(); parentTess.startDrawingQuads(); @@ -364,4 +303,128 @@ public class TessellatorManagerTest { TessellatorManager.stopCompiling(); } + + @Test + void testCompilingModeQuadsGoToQuadsList() { + // In COMPILING mode, GL_QUADS should go to quads list, primitives should be empty + final List receivedQuads = new ArrayList<>(); + final List receivedPrimitives = new ArrayList<>(); + + TessellatorManager.setCompiling((quads, primitives, flags) -> { + receivedQuads.addAll(quads); + receivedPrimitives.addAll(primitives); + }); + + CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); + tess.startDrawingQuads(); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + tess.draw(); + + TessellatorManager.stopCompiling(); + + assertEquals(1, receivedQuads.size(), "COMPILING mode: GL_QUADS should produce 1 quad"); + assertTrue(receivedPrimitives.isEmpty(), "COMPILING mode: GL_QUADS should not produce primitives"); + } + + @Test + void testCompilingModeTrianglesGoToPrimitivesList() { + // In COMPILING mode, GL_TRIANGLES should go to primitives list (NOT quadrangulated) + final List receivedQuads = new ArrayList<>(); + final List receivedPrimitives = new ArrayList<>(); + + TessellatorManager.setCompiling((quads, primitives, flags) -> { + receivedQuads.addAll(quads); + receivedPrimitives.addAll(primitives); + }); + + CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); + tess.startDrawing(GL11.GL_TRIANGLES); + // Triangle 1 + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0.5, 1, 0).tex(0.5, 1).endVertex(); + tess.draw(); + + TessellatorManager.stopCompiling(); + + assertTrue(receivedQuads.isEmpty(), "COMPILING mode: GL_TRIANGLES should not produce quads"); + assertEquals(1, receivedPrimitives.size(), "COMPILING mode: GL_TRIANGLES should produce 1 triangle primitive"); + assertEquals(3, receivedPrimitives.get(0).getVertexCount(), "Triangle should have 3 vertices"); + } + + @Test + void testCompilingModeLinesGoToPrimitivesList() { + // In COMPILING mode, GL_LINES should go to primitives list + final List receivedQuads = new ArrayList<>(); + final List receivedPrimitives = new ArrayList<>(); + + TessellatorManager.setCompiling((quads, primitives, flags) -> { + receivedQuads.addAll(quads); + receivedPrimitives.addAll(primitives); + }); + + CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); + tess.startDrawing(GL11.GL_LINES); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 1, 1).tex(1, 1).endVertex(); + tess.draw(); + + TessellatorManager.stopCompiling(); + + assertTrue(receivedQuads.isEmpty(), "COMPILING mode: GL_LINES should not produce quads"); + assertEquals(1, receivedPrimitives.size(), "COMPILING mode: GL_LINES should produce 1 line primitive"); + assertEquals(2, receivedPrimitives.get(0).getVertexCount(), "Line should have 2 vertices"); + } + + @Test + void testCapturingModeTrianglesAreQuadrangulated() { + // In CAPTURING mode, GL_TRIANGLES should be quadrangulated into quads list for backward compat + CapturingTessellator tess = TessellatorManager.startCapturingAndGet(); + tess.startDrawing(GL11.GL_TRIANGLES); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0.5, 1, 0).tex(0.5, 1).endVertex(); + tess.draw(); + + List quads = TessellatorManager.stopCapturingToPooledQuads(); + + assertEquals(1, quads.size(), "CAPTURING mode: GL_TRIANGLES should be quadrangulated into 1 quad"); + // Quadrangulated triangle has v2 duplicated to v3 + assertEquals(quads.get(0).getX(2), quads.get(0).getX(3), 0.001f, "Quadrangulated: v2.x should equal v3.x"); + assertEquals(quads.get(0).getY(2), quads.get(0).getY(3), 0.001f, "Quadrangulated: v2.y should equal v3.y"); + } + + @Test + void testCompilingModeDrawModeInFlags() { + // Verify that the draw mode is correctly passed in flags + final int[] capturedDrawMode = new int[1]; + + TessellatorManager.setCompiling((quads, primitives, flags) -> { capturedDrawMode[0] = flags.drawMode; }); + + CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get(); + + // Test with GL_TRIANGLES + tess.startDrawing(GL11.GL_TRIANGLES); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(0.5, 1, 0).tex(0.5, 1).endVertex(); + tess.draw(); + + assertEquals(GL11.GL_TRIANGLES, capturedDrawMode[0], "Flags should contain GL_TRIANGLES draw mode"); + + // Test with GL_QUADS + tess.startDrawingQuads(); + tess.pos(0, 0, 0).tex(0, 0).endVertex(); + tess.pos(1, 0, 0).tex(1, 0).endVertex(); + tess.pos(1, 1, 0).tex(1, 1).endVertex(); + tess.pos(0, 1, 0).tex(0, 1).endVertex(); + tess.draw(); + + assertEquals(GL11.GL_QUADS, capturedDrawMode[0], "Flags should contain GL_QUADS draw mode"); + + TessellatorManager.stopCompiling(); + } }