From 1ba88f027e9cc3c407b85a5b65d6cd11974acfae Mon Sep 17 00:00:00 2001 From: Jason Mitchell Date: Tue, 2 Dec 2025 09:48:18 -0800 Subject: [PATCH] Add compiling (callback) tessellator mode (#193) --- .../gtnhlib/client/renderer/CapturedDraw.java | 28 ++ .../client/renderer/CapturingTessellator.java | 145 +++---- .../gtnhlib/client/renderer/DrawCallback.java | 20 + .../client/renderer/ITessellatorInstance.java | 21 + .../client/renderer/QuadExtractor.java | 80 ++++ .../client/renderer/TessellatorManager.java | 367 ++++++++++++++++-- .../renderer/cel/model/quad/ModelQuad.java | 48 +++ .../renderer/cel/util/ModelQuadUtil.java | 22 ++ .../quad/writers/PositionColorQuadWriter.java | 43 ++ ...PositionColorTextureLightNormalWriter.java | 53 +++ .../PositionColorTextureLightmapWriter.java | 50 +++ .../PositionTextureLightNormalWriter.java | 50 +++ .../client/renderer/stacks/IStateStack.java | 71 +++- .../client/renderer/vbo/VertexBuffer.java | 10 + .../renderer/vertex/DefaultVertexFormat.java | 17 +- .../transformers/TessellatorTransformer.java | 115 ++++++ .../gtnhlib/core/rfb/GTNHLibRfbPlugin.java | 3 +- .../mixins/early/MixinTessellator.java | 14 + .../rfb/TessellatorTransformerWrapper.java | 72 ++++ src/main/resources/META-INF/gtnhlib_at.cfg | 4 +- .../renderer/TessellatorManagerTest.java | 367 ++++++++++++++++++ 21 files changed, 1479 insertions(+), 121 deletions(-) create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorQuadWriter.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightNormalWriter.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightmapWriter.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionTextureLightNormalWriter.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/core/fml/transformers/TessellatorTransformer.java create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/rfb/TessellatorTransformerWrapper.java create mode 100644 src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.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 new file mode 100644 index 00000000..323f4879 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturedDraw.java @@ -0,0 +1,28 @@ +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 eb8015f8..c59e8775 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/CapturingTessellator.java @@ -5,23 +5,19 @@ import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LI 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.vertexOffset; import static net.minecraft.util.MathHelper.clamp_int; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.List; +import java.util.Objects; 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.quad.ModelQuad; @@ -30,7 +26,6 @@ import com.gtnewhorizon.gtnhlib.client.renderer.stacks.Vector3dStack; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizon.gtnhlib.util.ObjectPooler; -import cpw.mods.fml.relauncher.ReflectionHelper; import it.unimi.dsi.fastutil.objects.ObjectArrayList; /// To be used in conjunction with the {@link TessellatorManager}. Used to capture the quads generated by the @@ -40,16 +35,15 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; @SuppressWarnings("unused") public class CapturingTessellator extends Tessellator implements ITessellatorInstance { - // Access Transformers don't work on Forge Fields :rage: - private static final MethodHandle sRawBufferSize; - private static final MethodHandle gRawBufferSize; - private final Flags FLAGS = new Flags(true, true, true, true); - private final ObjectPooler quadBuf = new ObjectPooler<>(ModelQuad::new); - private final List collectedQuads = new ObjectArrayList<>(); - private int shaderBlockId = -1; + final ObjectPooler quadBuf = new ObjectPooler<>(ModelQuad::new); + final List collectedQuads = new ObjectArrayList<>(); + int shaderBlockId = -1; // Any offset we need to the Tesselator's offset! - private final BlockPos offset = new BlockPos(); + final BlockPos offset = new BlockPos(); + + // Reusable FLAGS instance to avoid allocations + final Flags flags = new Flags(true, true, true, true); private final Vector3dStack storedTranslation = new Vector3dStack(); @@ -61,77 +55,10 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns this.offset.zero(); } - static { - // Optifine breaks the remapping of this, so look for the obf name as well - final Field rbs = ReflectionHelper.findField(Tessellator.class, "rawBufferSize", "field_78388_E"); - rbs.setAccessible(true); - try { - sRawBufferSize = MethodHandles.lookup().unreflectSetter(rbs); - gRawBufferSize = MethodHandles.lookup().unreflectGetter(rbs); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - public void setRawBufferSize(int size) { - try { - sRawBufferSize.invokeExact((Tessellator) this, size); - } catch (Throwable throwable) { - throw new RuntimeException(throwable); - } - } - - public int getRawBufferSize() { - try { - return (int) gRawBufferSize.invokeExact((Tessellator) this); - } catch (Throwable throwable) { - throw new RuntimeException(throwable); - } - } - - private int dataX(int offset, int vi) { - return rawBuffer[offset + vertexOffset(vi)]; - } - - private int dataY(int offset, int vi) { - return rawBuffer[offset + vertexOffset(vi) + 1]; - } - - private int dataZ(int offset, int vi) { - return rawBuffer[offset + vertexOffset(vi) + 2]; - } - @Override public int draw() { - // Adapted from Neodymium - - FLAGS.hasBrightness = this.hasBrightness; - FLAGS.hasColor = this.hasColor; - FLAGS.hasNormals = this.hasNormals; - - final int verticesPerPrimitive = this.drawMode == GL11.GL_QUADS ? 4 : 3; - - for (int quadI = 0; quadI < this.vertexCount / verticesPerPrimitive; quadI++) { - final int srcOffset = quadI * (verticesPerPrimitive * 8); - if (empty(srcOffset)) continue; - - final ModelQuad quad = quadBuf.getInstance(); - quad.setState(this.rawBuffer, srcOffset, FLAGS, this.drawMode, -offset.x, -offset.y, -offset.z); - quad.setShaderBlockId(shaderBlockId); - this.collectedQuads.add(quad); - } - - final int i = this.rawBufferIndex * 4; - this.discard(); - return i; - } - - private boolean empty(int srcOffset) { - return dataX(srcOffset, 0) == dataX(srcOffset, 1) && dataX(srcOffset, 1) == dataX(srcOffset, 2) - && dataX(srcOffset, 2) == dataX(srcOffset, 3) - && dataY(srcOffset, 0) == dataY(srcOffset, 1) - && dataY(srcOffset, 1) == dataY(srcOffset, 2) - && dataY(srcOffset, 2) == dataY(srcOffset, 3); + // Delegate to TessellatorManager for shared logic + return TessellatorManager.processDrawForCapturingTessellator(this); } @Override @@ -140,6 +67,17 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns reset(); } + @Override + public boolean gtnhlib$isCompiling() { + // Check if the current state in TessellatorManager is COMPILING + return TessellatorManager.isCurrentlyCompiling(); + } + + @Override + public void gtnhlib$setCompiling(boolean compiling) { + // NOOP - CapturingTessellator never needs the compiling flag (it's only for vanilla Tessellator) + } + public List getQuads() { return collectedQuads; } @@ -239,7 +177,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns /** * Sets the normal based on a given normal matrix - * + * * @param normal The normal vector * @param dest The vector that gets transformed * @param normalMatrix The normal matrix (typically the transpose of the inverse transformation matrix) @@ -276,15 +214,12 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns } public void ensureBuffer() { - int rawBufferSize = getRawBufferSize(); if (rawBufferIndex >= rawBufferSize - 32) { if (rawBufferSize == 0) { rawBufferSize = 0x10000; - setRawBufferSize(rawBufferSize); rawBuffer = new int[rawBufferSize]; } else { rawBufferSize *= 2; - setRawBufferSize(rawBufferSize); rawBuffer = Arrays.copyOf(rawBuffer, rawBufferSize); } } @@ -303,7 +238,7 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns public static class Flags { - boolean hasTexture; + public boolean hasTexture; public boolean hasBrightness; public boolean hasColor; public boolean hasNormals; @@ -315,5 +250,39 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns this.hasNormals = hasNormals; } + /** + * Copy constructor for creating immutable snapshots of flag state. + */ + public Flags(Flags other) { + this.hasTexture = other.hasTexture; + this.hasBrightness = other.hasBrightness; + this.hasColor = other.hasColor; + this.hasNormals = other.hasNormals; + } + + /** + * Updates this Flags instance with new values. Used to avoid repeated field assignments. + */ + public void copyFrom(boolean hasTexture, boolean hasBrightness, boolean hasColor, boolean hasNormals) { + this.hasTexture = hasTexture; + this.hasBrightness = hasBrightness; + this.hasColor = hasColor; + this.hasNormals = hasNormals; + } + + @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; + } + + @Override + public int hashCode() { + return Objects.hash(hasTexture, hasBrightness, hasColor, hasNormals); + } + } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java new file mode 100644 index 00000000..21f1e1c3 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/DrawCallback.java @@ -0,0 +1,20 @@ +package com.gtnewhorizon.gtnhlib.client.renderer; + +import java.util.List; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; + +/** + * Callback interface for per-draw notifications during display list compilation. + */ +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. + * + * @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 + */ + void onDraw(List quads, CapturingTessellator.Flags flags); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/ITessellatorInstance.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/ITessellatorInstance.java index f9a73502..d9b084b4 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/ITessellatorInstance.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/ITessellatorInstance.java @@ -1,6 +1,27 @@ package com.gtnewhorizon.gtnhlib.client.renderer; +/** + * Interface for Tessellator instances to support GTNHLib's capturing/compiling features. + */ public interface ITessellatorInstance { + /** + * Discard the current drawing state without rendering. Standard implementation should set isDrawing = false and + * call reset(). + */ void discard(); + + /** + * Check if this Tessellator instance is in compiling mode (display list compilation). + * + * @return true if currently compiling, false otherwise + */ + boolean gtnhlib$isCompiling(); + + /** + * Set the compiling mode flag for this Tessellator instance. + * + * @param compiling true to enable compiling mode, false to disable + */ + void gtnhlib$setCompiling(boolean compiling); } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java new file mode 100644 index 00000000..0d56d439 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/QuadExtractor.java @@ -0,0 +1,80 @@ +package com.gtnewhorizon.gtnhlib.client.renderer; + +import java.util.List; + +import org.lwjgl.opengl.GL11; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; +import com.gtnewhorizon.gtnhlib.util.ObjectPooler; + +/** + * Utility class for extracting ModelQuad objects from Tessellator raw buffers. This is used by both vanilla Tessellator + * (during display list compilation) and CapturingTessellator. + */ +public final class QuadExtractor { + + private static final int VERTEX_STRIDE = 8; // ints per vertex in Tessellator raw buffer + + private QuadExtractor() { + // Utility class - no instantiation + } + + /** + * Builds ModelQuad objects from a Tessellator's raw buffer. Used by both vanilla Tessellator (during compiling) and + * CapturingTessellator. + * + * @param rawBuffer The Tessellator's raw int[] buffer + * @param vertexCount Number of vertices in the buffer + * @param drawMode GL draw mode (GL_QUADS, GL_TRIANGLES, etc.) + * @param hasTexture Whether texture coordinates are present + * @param hasBrightness Whether brightness/light data is present + * @param hasColor Whether color data is present + * @param hasNormals Whether normal vectors are present + * @param offsetX X offset to apply to all vertices + * @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 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, + CapturingTessellator.Flags flags) { + + flags.copyFrom(hasTexture, hasBrightness, hasColor, hasNormals); + + final int verticesPerPrimitive = drawMode == GL11.GL_QUADS ? 4 : 3; + + for (int quadI = 0; quadI < vertexCount / verticesPerPrimitive; quadI++) { + final int srcOffset = quadI * (verticesPerPrimitive * VERTEX_STRIDE); + if (isEmptyQuad(rawBuffer, srcOffset)) continue; + + final ModelQuad quad = quadBuf.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 9f91e325..f6890908 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager.java @@ -1,13 +1,17 @@ package com.gtnewhorizon.gtnhlib.client.renderer; import java.nio.ByteBuffer; +import java.util.ArrayList; import java.util.List; import net.minecraft.client.renderer.Tessellator; +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.ModelQuadViewMutable; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; @@ -15,26 +19,60 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; @SuppressWarnings("unused") public class TessellatorManager { + private static final Logger LOGGER = LogManager.getLogger("TessellatorManager"); + + private enum CaptureMode { + CAPTURING, // startCapturing() - batch mode until explicit stop + COMPILING // setCompiling() - per-draw callback mode + } + + private static class CaptureState { + + 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 + + CaptureState(CaptureMode mode, DrawCallback callback) { + this.mode = mode; + this.callback = callback; + } + } + private static final ThreadLocal capturingTessellator = ThreadLocal .withInitial(CapturingTessellator::new); - private static final ThreadLocal currentlyCapturing = ThreadLocal.withInitial(() -> Boolean.FALSE); + private static final ThreadLocal> captureStack = ThreadLocal.withInitial(ArrayList::new); private static final Thread mainThread = Thread.currentThread(); + // Recursion protection (compiling is main-thread only) + private static boolean isInCompilingCallback = false; + public static Tessellator get() { - if (currentlyCapturing.get()) { + final ArrayList stack = captureStack.get(); + if (!stack.isEmpty()) { return capturingTessellator.get(); } else if (isOnMainThread()) { return Tessellator.instance; } else { - // TODO: Verify this works correctly and nothing unexpected is grabbing a tessellator off the main thread - // when not capturing throw new IllegalStateException("Tried to get the Tessellator off the main thread when not capturing!"); } } public static boolean isCurrentlyCapturing() { - return currentlyCapturing.get(); + CaptureState current = peekState(); + return current != null && current.mode == CaptureMode.CAPTURING; + } + + /** + * Checks if the current (top of stack) state is COMPILING mode. Used by CapturingTessellator to determine if draw() + * should be intercepted for callbacks. Only the current state matters - nested CAPTURING inside COMPILING should + * capture, not intercept. + * + * @return true if the current state is COMPILING + */ + static boolean isCurrentlyCompiling() { + CaptureState current = peekState(); + return current != null && current.mode == CaptureMode.COMPILING; } public static boolean isOnMainThread() { @@ -45,38 +83,132 @@ public class TessellatorManager { return instance == Tessellator.instance || isOnMainThread(); } + /** + * Gets the current (top) capture state, or null if stack is empty. + */ + private static CaptureState peekState() { + ArrayList stack = captureStack.get(); + return stack.isEmpty() ? null : stack.get(stack.size() - 1); + } + + /** + * Gets the current capture state, throwing if not in expected mode. + */ + private static CaptureState requireMode(CaptureMode expected, String errorMsg) { + ArrayList stack = captureStack.get(); + if (stack.isEmpty() || stack.get(stack.size() - 1).mode != expected) { + throw new IllegalStateException(errorMsg); + } + return stack.get(stack.size() - 1); + } + + /** + * Sets the compiling flag on vanilla Tessellator.instance if it implements ITessellatorInstance. + */ + private static void setVanillaTessellatorCompiling(boolean compiling) { + if (Tessellator.instance instanceof ITessellatorInstance tessInst) { + tessInst.gtnhlib$setCompiling(compiling); + } + } + + /** + * Checks if there are any COMPILING states remaining in the stack. Scans from top to bottom (most likely to find + * recent COMPILING states first). + */ + private static boolean hasCompilingInStack(ArrayList stack) { + for (int i = stack.size() - 1; i >= 0; i--) { + if (stack.get(i).mode == CaptureMode.COMPILING) { + return true; + } + } + return false; + } + + /** + * 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. + */ + private static void saveUncommittedQuadsIfNeeded(ArrayList stack, CapturingTessellator tess) { + if (stack.isEmpty() || tess.getQuads().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))); + tess.getQuads().clear(); + } + } + public static void startCapturing() { startCapturingAndGet(); } public static CapturingTessellator startCapturingAndGet() { - if (currentlyCapturing.get()) - throw new IllegalStateException("Tried to start capturing when already capturing!"); + ArrayList stack = captureStack.get(); final CapturingTessellator tess = capturingTessellator.get(); - if (!tess.getQuads().isEmpty()) - throw new IllegalStateException("Tried to start capturing with existing collected Quads!"); - tess.storeTranslation(); - currentlyCapturing.set(true); + // Save any uncommitted quads if parent is CAPTURING + saveUncommittedQuadsIfNeeded(stack, tess); + + // Validate no orphan quads exist + if (!tess.getQuads().isEmpty()) { + throw new IllegalStateException("Tried to start capturing with existing collected Quads!"); + } + + tess.storeTranslation(); + stack.add(new CaptureState(CaptureMode.CAPTURING, null)); return tess; } - /// 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() { - if (!currentlyCapturing.get()) throw new IllegalStateException("Tried to stop capturing when not capturing!"); - currentlyCapturing.set(false); + /// 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() { + CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!"); + ArrayList stack = captureStack.get(); + final CapturingTessellator tess = capturingTessellator.get(); - // Be sure we got all the quads + // Flush any pending draw if (tess.isDrawing) tess.draw(); - final var quads = tess.getQuads(); - tess.discard(); + // 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(); - return quads; + // 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 + } else { + tess.discard(); + } + + 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; } /// Stops the CapturingTessellator, stores the quads in a buffer (based on the VertexFormat provided), and clears @@ -124,16 +256,205 @@ public class TessellatorManager { return vao.upload(stopCapturingToBuffer(format)); } - static { - System.out.println("[TessellatorManager] Initialized on thread " + mainThread.getName()); + /** + * Fast check called from ASM-injected bytecode in Tessellator.draw(). Checks if the Tessellator instance is in + * compiling mode (display list compilation active). + * + * @param tess The Tessellator instance + * @return true if draw() should be intercepted, false otherwise + */ + public static boolean shouldInterceptDraw(Tessellator tess) { + return ((ITessellatorInstance) tess).gtnhlib$isCompiling(); + } + + /** + * Intercepts Tessellator.draw() during display list compilation. Extracts quads 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). + * + * @param tess The vanilla Tessellator instance + * @return The result that draw() should return + */ + public static int interceptDraw(Tessellator tess) { + // Detect recursive draw() calls from within callback + if (isInCompilingCallback) { + throw new IllegalStateException( + "Tessellator.draw() called from within a compiling callback - this is not allowed!"); + } + + // Get callback from stack + CaptureState current = requireMode(CaptureMode.COMPILING, "interceptDraw called but not in COMPILING mode!"); + if (current.callback == null) { + throw new IllegalStateException("interceptDraw called but callback is null!"); + } + + // Build quads from vanilla tess's buffer using main thread capturing tessellator's infrastructure + 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); + + // Invoke callback with collected quads (protect against recursion) + isInCompilingCallback = true; + try { + current.callback.onDraw(helper.collectedQuads, helper.flags); + } finally { + isInCompilingCallback = false; + } + helper.clearQuads(); + + int result = tess.rawBufferIndex * 4; + ((ITessellatorInstance) tess).discard(); + return result; + } + + /** + * Helper for CapturingTessellator to process its draw() call using shared logic. + */ + static int processDrawForCapturingTessellator(CapturingTessellator tess) { + CaptureState current = peekState(); + + 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(); + } + } + + int result = tess.rawBufferIndex * 4; + tess.discard(); + return result; } public static void cleanup() { // Ensure we've cleaned everything up final CapturingTessellator tessellator = capturingTessellator.get(); + final ArrayList stack = captureStack.get(); - currentlyCapturing.set(false); + // Check if we're cleaning up during active compiling + if (isOnMainThread()) { + final CaptureState current = peekState(); + if (current != null && current.mode == CaptureMode.COMPILING) { + LOGGER.warn( + "[TessellatorManager] cleanup() called while compiling is active - this may indicate cleanup() called during display list compilation!", + new Exception("Stack trace")); + setVanillaTessellatorCompiling(false); + } + } + + stack.clear(); tessellator.discard(); tessellator.clearQuads(); + isInCompilingCallback = false; } + + /** + * Set display list compiling mode with per-draw callbacks. While compiling, each Tessellator.draw() will + * automatically invoke the callback. The callback receives only the quads from that specific draw call. + * + * Nesting: Compiling can be nested inside capturing mode (for VBO capture of display list contents), and COMPILING + * can now be nested inside COMPILING (for nested glNewList() calls). Each nested level gets its own callback + * invoked independently. + * + * @param callback Called for each draw() with the newly captured quads + * @throws IllegalArgumentException if callback is null + */ + public static void setCompiling(DrawCallback callback) { + if (callback == null) throw new IllegalArgumentException("Callback cannot be null"); + if (!isOnMainThread()) { + throw new IllegalStateException("Display list compilation can only happen on main thread!"); + } + + ArrayList stack = captureStack.get(); + + // Nested COMPILING is now allowed for nested display list compilation + // No check needed - just push a new COMPILING state + + final CapturingTessellator tess = capturingTessellator.get(); + if (!tess.getQuads().isEmpty()) { + throw new IllegalStateException("Tried to start compiling with existing collected Quads!"); + } + + stack.add(new CaptureState(CaptureMode.COMPILING, callback)); + + // Set flag on Tessellator.instance if it exists and implements ITessellatorInstance + // This flag stays true as long as ANY compiling state exists + setVanillaTessellatorCompiling(true); + tess.storeTranslation(); + } + + /** + * Stop display list compiling mode. If there's a pending draw, flushes it and invokes callback one final time. + * Clears the callback and any remaining quads. + * + * For nested COMPILING: Only the innermost (current) compilation is stopped. The parent compilation continues. The + * compiling flag is only cleared when ALL compilation levels have been exited. + * + * @throws IllegalStateException if not currently compiling + */ + public static void stopCompiling() { + if (!isOnMainThread()) { + throw new IllegalStateException("stopCompiling() can only be called from main thread!"); + } + + requireMode(CaptureMode.COMPILING, "Not currently compiling!"); + ArrayList stack = captureStack.get(); + + final CapturingTessellator tess = capturingTessellator.get(); + + // Flush any pending draw BEFORE popping stack (draw will still trigger callback via stack check) + if (tess.isDrawing) { + tess.draw(); + } + + // Now pop the stack + stack.remove(stack.size() - 1); + + // Only clear flag if there are no more COMPILING states in the stack + if (!hasCompilingInStack(stack)) { + setVanillaTessellatorCompiling(false); + } + + // Clear any remaining quads (shouldn't be any if callback worked correctly) + tess.clearQuads(); + tess.discard(); + tess.restoreTranslation(); + } + } 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 d9fcc46a..daaab68e 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 @@ -33,6 +33,12 @@ public class ModelQuad implements ModelQuadViewMutable { private boolean hasAmbientOcclusion = true; private int shaderBlockId; + public ModelQuad() {} + + public ModelQuad(ModelQuadView source) { + copyFrom(source); + } + @Override public void setX(int idx, float x) { this.data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x); @@ -258,4 +264,46 @@ public class ModelQuad implements ModelQuadViewMutable { setLight(0, DEFAULT_LIGHTMAP); setLight(0, DEFAULT_LIGHTMAP); } + + /** + * Deep copies all data from the source quad into this quad. Used when quads need to be retained beyond their pool + * lifecycle. + * + * @param source The quad to copy from + */ + public ModelQuad copyFrom(ModelQuadView source) { + // Optimize for ModelQuad-to-ModelQuad copies + if (source instanceof ModelQuad sourceQuad) { + System.arraycopy(sourceQuad.data, 0, this.data, 0, VERTEX_SIZE * 4); + this.flags = sourceQuad.flags; + this.normal = sourceQuad.normal; + this.sprite = sourceQuad.sprite; + this.colorIdx = sourceQuad.colorIdx; + this.direction = sourceQuad.direction; + this.hasAmbientOcclusion = sourceQuad.hasAmbientOcclusion; + this.shaderBlockId = sourceQuad.shaderBlockId; + } else { + // Fallback for generic ModelQuadView sources - copy element by element + for (int i = 0; i < 4; i++) { + setX(i, source.getX(i)); + setY(i, source.getY(i)); + setZ(i, source.getZ(i)); + setColor(i, source.getColor(i)); + setTexU(i, source.getTexU(i)); + setTexV(i, source.getTexV(i)); + setLight(i, source.getLight(i)); + setForgeNormal(i, source.getForgeNormal(i)); + } + + // Copy metadata + this.flags = source.getFlags(); + this.normal = source.getComputedFaceNormal(); + this.sprite = source.celeritas$getSprite(); + this.colorIdx = source.getColorIndex(); + this.direction = source.getLightFace(); + this.hasAmbientOcclusion = source.hasAmbientOcclusion(); + this.shaderBlockId = source.getShaderBlockId(); + } + return this; + } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/util/ModelQuadUtil.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/util/ModelQuadUtil.java index 441c94ac..cdfe9d18 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/util/ModelQuadUtil.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/cel/util/ModelQuadUtil.java @@ -9,8 +9,13 @@ import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties import static java.lang.Math.abs; import static java.lang.Math.max; +import java.util.ArrayList; +import java.util.List; + import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; /// Provides some utilities and constants for interacting with vanilla's model quad vertex format. @@ -135,4 +140,21 @@ public class ModelQuadUtil { return (sl << 16) | bl; } + /** + * Deep copies a list of quads. Useful when quads need to persist beyond their pool lifecycle (e.g., from + * CapturingTessellator's object pool). + * + * @param sourceQuads The quads to copy + * @return A new list containing deep copies of all quads + */ + public static List deepCopyQuads(List sourceQuads) { + final int size = sourceQuads.size(); + final List quadCopies = new ArrayList<>(size); + // noinspection ForLoopReplaceableByForEach + for (int i = 0; i < size; i++) { + quadCopies.add(new ModelQuad(sourceQuads.get(i))); + } + return quadCopies; + } + } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorQuadWriter.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorQuadWriter.java new file mode 100644 index 00000000..ebe1d806 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorQuadWriter.java @@ -0,0 +1,43 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.quad.writers; + +import java.nio.ByteBuffer; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; + +public class PositionColorQuadWriter implements IWriteQuads { + + private boolean direct; + + public PositionColorQuadWriter() { + init(false); + } + + public void init(boolean direct) { + this.direct = direct; + } + + @Override + public void writeQuad(ModelQuadView quad, ByteBuffer buf) { + if (direct) { + writeQuadDirect(quad, buf); + } else { + writeQuadIndirect(quad, buf); + } + } + + protected void writeQuadDirect(ModelQuadView quad, ByteBuffer buf) { + throw new UnsupportedOperationException("Direct mode not supported yet"); + } + + protected void writeQuadIndirect(ModelQuadView quad, ByteBuffer buf) { + for (int idx = 0; idx < 4; ++idx) { + // Position (3 floats) + buf.putFloat(quad.getX(idx)); + buf.putFloat(quad.getY(idx)); + buf.putFloat(quad.getZ(idx)); + + // Color (4 ubytes packed as int) + buf.putInt(quad.getColor(idx)); + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightNormalWriter.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightNormalWriter.java new file mode 100644 index 00000000..2e60d957 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightNormalWriter.java @@ -0,0 +1,53 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.quad.writers; + +import java.nio.ByteBuffer; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; + +public class PositionColorTextureLightNormalWriter implements IWriteQuads { + + private boolean direct; + + public PositionColorTextureLightNormalWriter() { + init(false); + } + + public void init(boolean direct) { + this.direct = direct; + } + + @Override + public void writeQuad(ModelQuadView quad, ByteBuffer buf) { + if (direct) { + writeQuadDirect(quad, buf); + } else { + writeQuadIndirect(quad, buf); + } + } + + protected void writeQuadDirect(ModelQuadView quad, ByteBuffer buf) { + throw new UnsupportedOperationException("Direct mode not supported yet"); + } + + protected void writeQuadIndirect(ModelQuadView quad, ByteBuffer buf) { + for (int idx = 0; idx < 4; ++idx) { + // Position (3 floats) + buf.putFloat(quad.getX(idx)); + buf.putFloat(quad.getY(idx)); + buf.putFloat(quad.getZ(idx)); + + // Color (4 ubytes packed as int) + buf.putInt(quad.getColor(idx)); + + // Texture (2 floats) + buf.putFloat(quad.getTexU(idx)); + buf.putFloat(quad.getTexV(idx)); + + // Light/Brightness (2 shorts packed as int) + buf.putInt(quad.getLight(idx)); + + // Normal + Padding (int) + buf.putInt(quad.getForgeNormal(idx)); + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightmapWriter.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightmapWriter.java new file mode 100644 index 00000000..5b1c5c13 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionColorTextureLightmapWriter.java @@ -0,0 +1,50 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.quad.writers; + +import java.nio.ByteBuffer; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; + +public class PositionColorTextureLightmapWriter implements IWriteQuads { + + private boolean direct; + + public PositionColorTextureLightmapWriter() { + init(false); + } + + public void init(boolean direct) { + this.direct = direct; + } + + @Override + public void writeQuad(ModelQuadView quad, ByteBuffer buf) { + if (direct) { + writeQuadDirect(quad, buf); + } else { + writeQuadIndirect(quad, buf); + } + } + + protected void writeQuadDirect(ModelQuadView quad, ByteBuffer buf) { + throw new UnsupportedOperationException("Direct mode not supported yet"); + } + + protected void writeQuadIndirect(ModelQuadView quad, ByteBuffer buf) { + for (int idx = 0; idx < 4; ++idx) { + // Position (3 floats) + buf.putFloat(quad.getX(idx)); + buf.putFloat(quad.getY(idx)); + buf.putFloat(quad.getZ(idx)); + + // Color (4 ubytes packed as int) + buf.putInt(quad.getColor(idx)); + + // Texture (2 floats) + buf.putFloat(quad.getTexU(idx)); + buf.putFloat(quad.getTexV(idx)); + + // Light/Brightness (2 shorts packed as int) + buf.putInt(quad.getLight(idx)); + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionTextureLightNormalWriter.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionTextureLightNormalWriter.java new file mode 100644 index 00000000..4d5f5fbd --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/quad/writers/PositionTextureLightNormalWriter.java @@ -0,0 +1,50 @@ +package com.gtnewhorizon.gtnhlib.client.renderer.quad.writers; + +import java.nio.ByteBuffer; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; + +public class PositionTextureLightNormalWriter implements IWriteQuads { + + private boolean direct; + + public PositionTextureLightNormalWriter() { + init(false); + } + + public void init(boolean direct) { + this.direct = direct; + } + + @Override + public void writeQuad(ModelQuadView quad, ByteBuffer buf) { + if (direct) { + writeQuadDirect(quad, buf); + } else { + writeQuadIndirect(quad, buf); + } + } + + protected void writeQuadDirect(ModelQuadView quad, ByteBuffer buf) { + throw new UnsupportedOperationException("Direct mode not supported yet"); + } + + protected void writeQuadIndirect(ModelQuadView quad, ByteBuffer buf) { + for (int idx = 0; idx < 4; ++idx) { + // Position (3 floats) + buf.putFloat(quad.getX(idx)); + buf.putFloat(quad.getY(idx)); + buf.putFloat(quad.getZ(idx)); + + // Texture (2 floats) + buf.putFloat(quad.getTexU(idx)); + buf.putFloat(quad.getTexV(idx)); + + // Light/Brightness (2 shorts packed as int) + buf.putInt(quad.getLight(idx)); + + // Normal + Padding (int) + buf.putInt(quad.getForgeNormal(idx)); + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/stacks/IStateStack.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/stacks/IStateStack.java index a8c58671..451d136b 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/stacks/IStateStack.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/stacks/IStateStack.java @@ -4,28 +4,28 @@ public interface IStateStack { /** * Push the current state onto the stack. - * + * * @return This state stack for chaining */ T push(); /** * Pop a state from the stack. - * + * * @return This state stack for chaining */ T pop(); /** * Check if the stack is empty. - * + * * @return true if the stack is empty */ boolean isEmpty(); /** * Clear the stack and reset to default state. - * + * * @return This state stack for chaining */ @SuppressWarnings("unchecked") @@ -35,4 +35,67 @@ public interface IStateStack { } return (T) this; } + + // ==================== Lazy Copy-on-Write API ==================== + + /** + * Increment depth counter without copying state (lazy push). + *

+ * This is the entry point for lazy copy-on-write optimization. Unlike {@link #push()}, this method does not + * immediately save the current state. Instead, the state will only be saved when {@link #beforeModify()} is called, + * indicating that a modification is about to occur. + *

+ * Usage pattern: + * + *

+     * stack.pushDepth();
+     * // ... later, before modifying state:
+     * stack.beforeModify();
+     * stack.setValue(newValue);
+     * // ... when done:
+     * stack.popDepth();
+     * 
+ * + * @return The new depth after pushing + */ + default int pushDepth() { + push(); + return getDepth(); + } + + /** + * Decrement depth and restore state only if it was modified at this depth. + *

+ * For stacks that track modifications, this will only restore the saved state if {@link #beforeModify()} was called + * at the current depth. For stacks that don't track modifications (default implementation), this behaves the same + * as {@link #pop()}. + * + * @return This state stack for chaining + */ + @SuppressWarnings("unchecked") + default T popDepth() { + pop(); + return (T) this; + } + + /** + * Called before modifying state to trigger lazy save if needed. + *

+ * When using the lazy copy-on-write pattern with {@link #pushDepth()}, call this method before any state + * modification. If the state hasn't been saved at the current depth yet, this will save it. + *

+ * For implementations that don't support lazy copy-on-write, this is a no-op. + */ + default void beforeModify() { + // Default: no-op for stacks that don't support lazy copy-on-write + } + + /** + * Get the current stack depth. + * + * @return The current depth (0 when empty) + */ + default int getDepth() { + return 0; // Default for stacks that don't track depth separately + } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vbo/VertexBuffer.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vbo/VertexBuffer.java index bf4624ab..e9ddbb50 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vbo/VertexBuffer.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vbo/VertexBuffer.java @@ -102,6 +102,16 @@ public class VertexBuffer implements AutoCloseable { GL11.glDrawArrays(drawMode, 0, this.vertexCount); } + /** + * Draw a range of vertices from this buffer. + * + * @param first First vertex index to draw + * @param count Number of vertices to draw + */ + public void draw(int first, int count) { + GL11.glDrawArrays(drawMode, first, count); + } + public void setupState() { bindVBO(); format.setupBufferState(0L); diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vertex/DefaultVertexFormat.java b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vertex/DefaultVertexFormat.java index 8bd1e2d1..371304b3 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vertex/DefaultVertexFormat.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/client/renderer/vertex/DefaultVertexFormat.java @@ -2,9 +2,13 @@ package com.gtnewhorizon.gtnhlib.client.renderer.vertex; import com.google.common.collect.ImmutableList; import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.ItemVBOQuadWriter; +import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionColorQuadWriter; +import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionColorTextureLightNormalWriter; +import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionColorTextureLightmapWriter; import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionColorTextureQuadWriter; import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionQuadWriter; import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionTextureColorQuadWriter; +import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionTextureLightNormalWriter; import com.gtnewhorizon.gtnhlib.client.renderer.quad.writers.PositionTextureQuadWriter; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Type; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement.Usage; @@ -33,9 +37,14 @@ public class DefaultVertexFormat { new ImmutableList.Builder().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT) .add(NORMAL_ELEMENT).add(PADDING_ELEMENT).build(), new ItemVBOQuadWriter()); + public static final VertexFormat POSITION_TEXTURE_LIGHT_NORMAL = new VertexFormat( + new ImmutableList.Builder().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT) + .add(LIGHT_ELEMENT).add(NORMAL_ELEMENT).add(PADDING_ELEMENT).build(), + new PositionTextureLightNormalWriter()); public static final VertexFormat POSITION_COLOR_TEXTURE_LIGHT_NORMAL = new VertexFormat( new ImmutableList.Builder().add(POSITION_ELEMENT).add(COLOR_ELEMENT) - .add(TEXTURE_ELEMENT).add(LIGHT_ELEMENT).add(NORMAL_ELEMENT).add(PADDING_ELEMENT).build()); + .add(TEXTURE_ELEMENT).add(LIGHT_ELEMENT).add(NORMAL_ELEMENT).add(PADDING_ELEMENT).build(), + new PositionColorTextureLightNormalWriter()); public static final VertexFormat POSITION_TEXTURE_COLOR_LIGHT = new VertexFormat( new ImmutableList.Builder().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT) .add(COLOR_ELEMENT).add(LIGHT_ELEMENT).build()); @@ -43,7 +52,8 @@ public class DefaultVertexFormat { new ImmutableList.Builder().add(POSITION_ELEMENT).build(), new PositionQuadWriter()); public static final VertexFormat POSITION_COLOR = new VertexFormat( - new ImmutableList.Builder().add(POSITION_ELEMENT).add(COLOR_ELEMENT).build()); + new ImmutableList.Builder().add(POSITION_ELEMENT).add(COLOR_ELEMENT).build(), + new PositionColorQuadWriter()); public static final VertexFormat POSITION_COLOR_LIGHT = new VertexFormat( new ImmutableList.Builder().add(POSITION_ELEMENT).add(COLOR_ELEMENT).add(LIGHT_ELEMENT) .build()); @@ -60,7 +70,8 @@ public class DefaultVertexFormat { new PositionTextureColorQuadWriter()); public static final VertexFormat POSITION_COLOR_TEX_LIGHTMAP = new VertexFormat( new ImmutableList.Builder().add(POSITION_ELEMENT).add(COLOR_ELEMENT) - .add(TEXTURE_ELEMENT).add(LIGHT_ELEMENT).build()); + .add(TEXTURE_ELEMENT).add(LIGHT_ELEMENT).build(), + new PositionColorTextureLightmapWriter()); public static final VertexFormat POSITION_TEXTURE_LIGHT_COLOR = new VertexFormat( new ImmutableList.Builder().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT) .add(LIGHT_ELEMENT).add(COLOR_ELEMENT).build()); diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/core/fml/transformers/TessellatorTransformer.java b/src/main/java/com/gtnewhorizon/gtnhlib/core/fml/transformers/TessellatorTransformer.java new file mode 100644 index 00000000..8584c9c6 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/core/fml/transformers/TessellatorTransformer.java @@ -0,0 +1,115 @@ +package com.gtnewhorizon.gtnhlib.core.fml.transformers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.minecraft.launchwrapper.IClassTransformer; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; + +import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser; + +/** + * Transformer the Tessellator and inject draw() interception. + */ +public class TessellatorTransformer implements IClassTransformer { + + private static final String TessellatorClass = "net/minecraft/client/renderer/Tessellator"; + + private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(TessellatorClass); + + public static List getTransformerExclusions() { + return Collections.unmodifiableList(new ArrayList<>()); + } + + public boolean shouldRfbTransform(byte[] basicClass) { + return cstPoolParser.find(basicClass, false); + } + + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + if (basicClass == null) return null; + + // Only transform the Tessellator class itself + if (!transformedName.equals("net.minecraft.client.renderer.Tessellator")) { + return basicClass; + } + + final ClassReader cr = new ClassReader(basicClass); + final ClassNode cn = new ClassNode(); + cr.accept(cn, 0); + final boolean changed = transformClassNode(cn); + if (changed) { + // Use COMPUTE_FRAMES since we're modifying control flow with jumps + final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cn.accept(cw); + return cw.toByteArray(); + } + return basicClass; + } + + /** + * @return Was the class changed? + */ + public boolean transformClassNode(ClassNode cn) { + if (cn == null) { + return false; + } + return transformTessellatorDraw(cn); + } + + /** + * Injects intercept check at the start of Tessellator.draw() to handle display list compilation. + * + * @param cn The Tessellator ClassNode + * @return true if the class was modified + */ + private boolean transformTessellatorDraw(ClassNode cn) { + for (MethodNode mn : cn.methods) { + // Handle both deobfuscated and obfuscated names + if (mn.name.equals("draw") || mn.name.equals("func_78381_a")) { + InsnList inject = new InsnList(); + LabelNode skipLabel = new LabelNode(); + + // if (TessellatorManager.shouldInterceptDraw(this)) + inject.add(new VarInsnNode(Opcodes.ALOAD, 0)); // this + inject.add( + new MethodInsnNode( + Opcodes.INVOKESTATIC, + "com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager", + "shouldInterceptDraw", + "(Lnet/minecraft/client/renderer/Tessellator;)Z", + false)); + inject.add(new JumpInsnNode(Opcodes.IFEQ, skipLabel)); // if false, skip + + // return TessellatorManager.interceptDraw(this); + inject.add(new VarInsnNode(Opcodes.ALOAD, 0)); // this + inject.add( + new MethodInsnNode( + Opcodes.INVOKESTATIC, + "com/gtnewhorizon/gtnhlib/client/renderer/TessellatorManager", + "interceptDraw", + "(Lnet/minecraft/client/renderer/Tessellator;)I", + false)); + inject.add(new InsnNode(Opcodes.IRETURN)); + inject.add(skipLabel); + + // Insert at the start of the method + mn.instructions.insert(inject); + return true; + } + } + return false; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/core/rfb/GTNHLibRfbPlugin.java b/src/main/java/com/gtnewhorizon/gtnhlib/core/rfb/GTNHLibRfbPlugin.java index 27b584f0..2325839b 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/core/rfb/GTNHLibRfbPlugin.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/core/rfb/GTNHLibRfbPlugin.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.gtnewhorizon.gtnhlib.core.rfb.transformers.RFBTessellatorRedirector; +import com.gtnewhorizon.gtnhlib.rfb.TessellatorTransformerWrapper; import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext; import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; @@ -27,6 +28,6 @@ public class GTNHLibRfbPlugin implements RfbPlugin { } boolean isObf = RetroFuturaBootstrap.API.launchClassLoader().findClassMetadata("net.minecraft.world.World") == null; - return new RfbClassTransformer[] { new RFBTessellatorRedirector(isObf) }; + return new RfbClassTransformer[] { new TessellatorTransformerWrapper(), new RFBTessellatorRedirector(isObf) }; } } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTessellator.java b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTessellator.java index 99a395fc..e2a0549d 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTessellator.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTessellator.java @@ -9,6 +9,7 @@ import net.minecraft.client.renderer.Tessellator; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -20,6 +21,9 @@ import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; @Mixin(Tessellator.class) public abstract class MixinTessellator implements ITessellatorInstance { + @Unique + private boolean gtnhlib$isCompiling = false; + @Shadow public boolean isDrawing; @@ -52,4 +56,14 @@ public abstract class MixinTessellator implements ITessellatorInstance { reset(); } + @Override + public boolean gtnhlib$isCompiling() { + return gtnhlib$isCompiling; + } + + @Override + public void gtnhlib$setCompiling(boolean compiling) { + this.gtnhlib$isCompiling = compiling; + } + } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/rfb/TessellatorTransformerWrapper.java b/src/main/java/com/gtnewhorizon/gtnhlib/rfb/TessellatorTransformerWrapper.java new file mode 100644 index 00000000..f026fe8e --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/rfb/TessellatorTransformerWrapper.java @@ -0,0 +1,72 @@ +package com.gtnewhorizon.gtnhlib.rfb; + +import java.util.jar.Manifest; + +import org.intellij.lang.annotations.Pattern; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.gtnewhorizon.gtnhlib.core.fml.transformers.TessellatorTransformer; +import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; +import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; +import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; + +/** RFB wrapper for {@link TessellatorTransformer} */ +public class TessellatorTransformerWrapper implements RfbClassTransformer { + + public final TessellatorTransformer inner = new TessellatorTransformer(); + + @Pattern("[a-z0-9-]+") + @Override + public @NotNull String id() { + return "tessellator"; + } + + @Override + public @NotNull String @Nullable [] sortAfter() { + // Must run after mixins to ensure Tessellator class is fully prepared + return new String[] { "mixin:mixin" }; + } + + @Override + public @NotNull String @Nullable [] sortBefore() { + // Must run before the redirector that modifies calls TO Tessellator + return new String[] { "redirector" }; + } + + @Override + public @NotNull String @Nullable [] additionalExclusions() { + return TessellatorTransformer.getTransformerExclusions().toArray(new String[0]); + } + + @Override + public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, + @NotNull ClassNodeHandle classNode) { + // Only transform the Tessellator class itself + if (!"net.minecraft.client.renderer.Tessellator".equals(className)) { + return false; + } + if (!classNode.isPresent()) { + return false; + } + if (!classNode.isOriginal()) { + // If a class is already a transformed ClassNode, conservatively continue processing. + return true; + } + return inner.shouldRfbTransform(classNode.getOriginalBytes()); + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + // Double-check we're only transforming Tessellator + if (!"net.minecraft.client.renderer.Tessellator".equals(className)) { + return; + } + final boolean changed = inner.transformClassNode(classNode.getNode()); + if (changed) { + classNode.computeFrames(); + } + } +} diff --git a/src/main/resources/META-INF/gtnhlib_at.cfg b/src/main/resources/META-INF/gtnhlib_at.cfg index 3b376132..15726ce8 100644 --- a/src/main/resources/META-INF/gtnhlib_at.cfg +++ b/src/main/resources/META-INF/gtnhlib_at.cfg @@ -15,8 +15,8 @@ public net.minecraft.client.renderer.Tessellator field_78408_v # xOffset public net.minecraft.client.renderer.Tessellator field_78407_w # yOffset public net.minecraft.client.renderer.Tessellator field_78417_x # zOffset public net.minecraft.client.renderer.Tessellator field_78415_z # isDrawing -public net.minecraft.client.renderer.Tessellator field_78388_E # bufferSize +public net.minecraft.client.renderer.Tessellator field_78388_E # rawBufferSize +public net.minecraft.client.renderer.Tessellator rawBufferSize # rawBufferSize public net.minecraft.client.renderer.Tessellator field_78410_t # isColorDisabled public net.minecraft.client.renderer.Tessellator func_78379_d()V # void reset() - public net.minecraft.command.CommandHandler field_71562_a # commandMap 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 new file mode 100644 index 00000000..a493fa9e --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/client/renderer/TessellatorManagerTest.java @@ -0,0 +1,367 @@ +package com.gtnewhorizon.gtnhlib.test.client.renderer; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +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.quad.ModelQuadViewMutable; + +/** + * Unit tests for TessellatorManager compiling mode and capturing mode. + */ +public class TessellatorManagerTest { + + @AfterEach + void cleanup() { + // Ensure clean state after each test + TessellatorManager.cleanup(); + } + + @Test + void testSetCompilingWithNullCallback() { + assertThrows( + IllegalArgumentException.class, + () -> TessellatorManager.setCompiling(null), + "setCompiling(null) should throw IllegalArgumentException"); + } + + @Test + void testNestedCompiling() { + // Nested COMPILING is now ALLOWED for nested display list compilation + TessellatorManager.setCompiling((quads, flags) -> {}); + assertDoesNotThrow( + () -> TessellatorManager.setCompiling((quads, flags) -> {}), + "Nested setCompiling() should be allowed"); + TessellatorManager.stopCompiling(); // Stop inner + TessellatorManager.stopCompiling(); // Stop outer + } + + @Test + void testNestedCompilingCallbacks() { + // Test that nested COMPILING levels have independent callbacks + final java.util.List callOrder = new java.util.ArrayList<>(); + + // Outer compilation + TessellatorManager.setCompiling((quads, flags) -> { callOrder.add("outer"); }); + + CapturingTessellator outerTess = (CapturingTessellator) TessellatorManager.get(); + outerTess.startDrawingQuads(); + outerTess.pos(0, 0, 0).tex(0, 0).endVertex(); + outerTess.pos(1, 0, 0).tex(1, 0).endVertex(); + outerTess.pos(1, 1, 0).tex(1, 1).endVertex(); + outerTess.pos(0, 1, 0).tex(0, 1).endVertex(); + outerTess.draw(); // Should trigger outer callback + + assertEquals(1, callOrder.size(), "Outer callback should have been called once"); + assertEquals("outer", callOrder.get(0)); + + // Nested inner compilation + TessellatorManager.setCompiling((quads, flags) -> { callOrder.add("inner"); }); + + CapturingTessellator innerTess = (CapturingTessellator) TessellatorManager.get(); + assertSame(outerTess, innerTess, "Should reuse same tessellator instance"); + + innerTess.startDrawingQuads(); + innerTess.pos(2, 0, 0).tex(0, 0).endVertex(); + innerTess.pos(3, 0, 0).tex(1, 0).endVertex(); + innerTess.pos(3, 1, 0).tex(1, 1).endVertex(); + innerTess.pos(2, 1, 0).tex(0, 1).endVertex(); + innerTess.draw(); // Should trigger inner callback (not outer) + + assertEquals(2, callOrder.size(), "Inner callback should have been called"); + assertEquals("inner", callOrder.get(1), "Most recent call should be inner"); + + TessellatorManager.stopCompiling(); // Stop inner + + // Back in outer context - draws should trigger outer callback again + outerTess.startDrawingQuads(); + outerTess.pos(4, 0, 0).tex(0, 0).endVertex(); + outerTess.pos(5, 0, 0).tex(1, 0).endVertex(); + outerTess.pos(5, 1, 0).tex(1, 1).endVertex(); + outerTess.pos(4, 1, 0).tex(0, 1).endVertex(); + outerTess.draw(); // Should trigger outer callback + + assertEquals(3, callOrder.size()); + assertEquals("outer", callOrder.get(2), "After inner exits, outer callback should work again"); + + TessellatorManager.stopCompiling(); // Stop outer + + // Verify call order + assertEquals( + java.util.Arrays.asList("outer", "inner", "outer"), + callOrder, + "Callbacks should be invoked in correct nested order"); + } + + @Test + void testStopCompilingWhenNotCompiling() { + assertThrows( + IllegalStateException.class, + TessellatorManager::stopCompiling, + "stopCompiling() when not compiling should throw IllegalStateException"); + } + + @Test + void testNestedCapturing() { + TessellatorManager.startCapturing(); + assertDoesNotThrow( + TessellatorManager::startCapturing, + "startCapturing() when already capturing should be allowed for nesting"); + TessellatorManager.stopCapturingToPooledQuads(); + TessellatorManager.stopCapturingToPooledQuads(); + } + + @Test + void testNestingCapturingInsideCompiling() { + TessellatorManager.setCompiling((quads, flags) -> {}); + assertDoesNotThrow( + TessellatorManager::startCapturing, + "startCapturing() when compiling should be allowed for nesting"); + TessellatorManager.stopCapturingToPooledQuads(); + TessellatorManager.stopCompiling(); + } + + @Test + void testSetCompilingAndStop() { + // Basic lifecycle test - should not throw + TessellatorManager.setCompiling((quads, flags) -> {}); + TessellatorManager.stopCompiling(); + } + + @Test + void testCleanupClearsCompilingState() { + TessellatorManager.setCompiling((quads, 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) -> {})); + TessellatorManager.stopCompiling(); + } + + @Test + void testCapturingLifecycle() { + TessellatorManager.startCapturing(); + List quads = TessellatorManager.stopCapturingToPooledQuads(); + assertNotNull(quads, "stopCapturingToPooledQuads should return non-null list"); + } + + @Test + void testStopCapturingWhenNotCapturing() { + assertThrows( + IllegalStateException.class, + TessellatorManager::stopCapturingToPooledQuads, + "stopCapturingToPooledQuads() when not capturing should throw IllegalStateException"); + } + + @Test + void testNestedCapturingQuadIsolation() { + // Start parent capture + CapturingTessellator parentTess = TessellatorManager.startCapturingAndGet(); + parentTess.startDrawingQuads(); + parentTess.pos(0, 0, 0).tex(0, 0).endVertex(); + parentTess.pos(1, 0, 0).tex(1, 0).endVertex(); + parentTess.pos(1, 1, 0).tex(1, 1).endVertex(); + 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"); + + // Start nested child capture + CapturingTessellator childTess = TessellatorManager.startCapturingAndGet(); + assertSame(parentTess, childTess, "Should reuse same tessellator instance"); + assertEquals(0, childTess.getQuads().size(), "Child should start with 0 quads"); + + childTess.startDrawingQuads(); + childTess.pos(2, 0, 0).tex(0, 0).endVertex(); + childTess.pos(3, 0, 0).tex(1, 0).endVertex(); + childTess.pos(3, 1, 0).tex(1, 1).endVertex(); + childTess.pos(2, 1, 0).tex(0, 1).endVertex(); + childTess.draw(); + + List childQuads = TessellatorManager.stopCapturingToPooledQuads(); + 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"); + + // Parent can continue capturing + parentTess.startDrawingQuads(); + parentTess.pos(4, 0, 0).tex(0, 0).endVertex(); + parentTess.pos(5, 0, 0).tex(1, 0).endVertex(); + parentTess.pos(5, 1, 0).tex(1, 1).endVertex(); + parentTess.pos(4, 1, 0).tex(0, 1).endVertex(); + parentTess.draw(); + + List parentQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(2, parentQuads.size(), "Parent should have 2 quads total"); + assertEquals(0.0f, parentQuads.get(0).getX(0), 0.001f, "First parent quad should have correct position"); + assertEquals(4.0f, parentQuads.get(1).getX(0), 0.001f, "Second parent quad should have correct position"); + } + + @Test + void testMultiLevelNestedCapturing() { + // Test 3-level nesting: grandparent → parent → child + CapturingTessellator grandparent = TessellatorManager.startCapturingAndGet(); + grandparent.startDrawingQuads(); + grandparent.pos(0, 0, 0).tex(0, 0).endVertex(); + grandparent.pos(1, 0, 0).tex(1, 0).endVertex(); + grandparent.pos(1, 1, 0).tex(1, 1).endVertex(); + grandparent.pos(0, 1, 0).tex(0, 1).endVertex(); + grandparent.draw(); + + CapturingTessellator parent = TessellatorManager.startCapturingAndGet(); + parent.startDrawingQuads(); + parent.pos(2, 0, 0).tex(0, 0).endVertex(); + parent.pos(3, 0, 0).tex(1, 0).endVertex(); + parent.pos(3, 1, 0).tex(1, 1).endVertex(); + parent.pos(2, 1, 0).tex(0, 1).endVertex(); + parent.draw(); + + CapturingTessellator child = TessellatorManager.startCapturingAndGet(); + child.startDrawingQuads(); + child.pos(4, 0, 0).tex(0, 0).endVertex(); + child.pos(5, 0, 0).tex(1, 0).endVertex(); + child.pos(5, 1, 0).tex(1, 1).endVertex(); + child.pos(4, 1, 0).tex(0, 1).endVertex(); + child.draw(); + + List childQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(1, childQuads.size(), "Child should have 1 quad"); + assertEquals(4.0f, childQuads.get(0).getX(0), 0.001f); + + List parentQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(1, parentQuads.size(), "Parent should have 1 quad"); + assertEquals(2.0f, parentQuads.get(0).getX(0), 0.001f); + + List grandparentQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(1, grandparentQuads.size(), "Grandparent should have 1 quad"); + assertEquals(0.0f, grandparentQuads.get(0).getX(0), 0.001f); + } + + @Test + void testFlagsEqualsAndHashCode() { + // Test that Flags instances with identical values are equal + CapturingTessellator.Flags flags1 = new CapturingTessellator.Flags(true, true, false, true); + CapturingTessellator.Flags flags2 = new CapturingTessellator.Flags(true, true, false, true); + CapturingTessellator.Flags flags3 = new CapturingTessellator.Flags(true, false, false, true); + + // Same values should be equal + assertEquals(flags1, flags2, "Flags with identical values should be equal"); + assertEquals(flags1.hashCode(), flags2.hashCode(), "Equal flags should have same hashCode"); + + // Different values should not be equal + assertNotEquals(flags1, flags3, "Flags with different values should not be equal"); + + // Reflexive + assertEquals(flags1, flags1, "Flags should equal itself"); + + // Copy constructor should produce equal flags + 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) -> { + // Compiling callback - start capturing inside + CapturingTessellator parentTess = TessellatorManager.startCapturingAndGet(); + parentTess.startDrawingQuads(); + parentTess.pos(0, 0, 0).tex(0, 0).endVertex(); + parentTess.pos(1, 0, 0).tex(1, 0).endVertex(); + parentTess.pos(1, 1, 0).tex(1, 1).endVertex(); + parentTess.pos(0, 1, 0).tex(0, 1).endVertex(); + parentTess.draw(); + + // Nest another capturing inside + CapturingTessellator childTess = TessellatorManager.startCapturingAndGet(); + childTess.startDrawingQuads(); + childTess.pos(2, 0, 0).tex(0, 0).endVertex(); + childTess.pos(3, 0, 0).tex(1, 0).endVertex(); + childTess.pos(3, 1, 0).tex(1, 1).endVertex(); + childTess.pos(2, 1, 0).tex(0, 1).endVertex(); + childTess.draw(); + + List childQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(1, childQuads.size()); + + List parentQuads = TessellatorManager.stopCapturingToPooledQuads(); + assertEquals(1, parentQuads.size()); + }); + + TessellatorManager.stopCompiling(); + } +}