mirror of
https://github.com/GTNewHorizons/GTNHLib.git
synced 2026-11-28 15:36:03 +00:00
Add compiling (callback) tessellator mode (#193)
This commit is contained in:
1 parent
010b994b83
commit
1ba88f027e
21 files changed
+1479
-121
No files matched your search
@@ -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<ModelQuadViewMutable> quads;
|
||||
private final CapturingTessellator.Flags flags;
|
||||
|
||||
public CapturedDraw(List<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags) {
|
||||
this.quads = quads;
|
||||
this.flags = flags;
|
||||
}
|
||||
|
||||
public List<ModelQuadViewMutable> quads() {
|
||||
return quads;
|
||||
}
|
||||
|
||||
public CapturingTessellator.Flags flags() {
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
@@ -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<ModelQuad> quadBuf = new ObjectPooler<>(ModelQuad::new);
|
||||
private final List<ModelQuadViewMutable> collectedQuads = new ObjectArrayList<>();
|
||||
private int shaderBlockId = -1;
|
||||
final ObjectPooler<ModelQuad> quadBuf = new ObjectPooler<>(ModelQuad::new);
|
||||
final List<ModelQuadViewMutable> 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<ModelQuadViewMutable> 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<ModelQuad> quadBuf, List<ModelQuadViewMutable> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<CapturedDraw> 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> capturingTessellator = ThreadLocal
|
||||
.withInitial(CapturingTessellator::new);
|
||||
|
||||
private static final ThreadLocal<Boolean> currentlyCapturing = ThreadLocal.withInitial(() -> Boolean.FALSE);
|
||||
private static final ThreadLocal<ArrayList<CaptureState>> 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<CaptureState> 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<CaptureState> 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<CaptureState> 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<CaptureState> 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<CaptureState> 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<CaptureState> 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<ModelQuadViewMutable> 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<CapturedDraw> stopCapturingToDraws() {
|
||||
CaptureState currentState = requireMode(CaptureMode.CAPTURING, "Tried to stop capturing when not capturing!");
|
||||
ArrayList<CaptureState> 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<CapturedDraw> 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<ModelQuadViewMutable> stopCapturingToPooledQuads() {
|
||||
final List<CapturedDraw> draws = stopCapturingToDraws();
|
||||
|
||||
// Flatten all draws into a single quad list
|
||||
final List<ModelQuadViewMutable> 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<CaptureState> 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<CaptureState> 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<CaptureState> 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<ModelQuadViewMutable> deepCopyQuads(List<ModelQuadViewMutable> sourceQuads) {
|
||||
final int size = sourceQuads.size();
|
||||
final List<ModelQuadViewMutable> quadCopies = new ArrayList<>(size);
|
||||
// noinspection ForLoopReplaceableByForEach
|
||||
for (int i = 0; i < size; i++) {
|
||||
quadCopies.add(new ModelQuad(sourceQuads.get(i)));
|
||||
}
|
||||
return quadCopies;
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,28 +4,28 @@ public interface IStateStack<T> {
|
||||
|
||||
/**
|
||||
* 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<T> {
|
||||
}
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
// ==================== Lazy Copy-on-Write API ====================
|
||||
|
||||
/**
|
||||
* Increment depth counter without copying state (lazy push).
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* Usage pattern:
|
||||
*
|
||||
* <pre>
|
||||
* stack.pushDepth();
|
||||
* // ... later, before modifying state:
|
||||
* stack.beforeModify();
|
||||
* stack.setValue(newValue);
|
||||
* // ... when done:
|
||||
* stack.popDepth();
|
||||
* </pre>
|
||||
*
|
||||
* @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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+14
-3
@@ -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<VertexFormatElement>().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<VertexFormatElement>().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<VertexFormatElement>().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<VertexFormatElement>().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT)
|
||||
.add(COLOR_ELEMENT).add(LIGHT_ELEMENT).build());
|
||||
@@ -43,7 +52,8 @@ public class DefaultVertexFormat {
|
||||
new ImmutableList.Builder<VertexFormatElement>().add(POSITION_ELEMENT).build(),
|
||||
new PositionQuadWriter());
|
||||
public static final VertexFormat POSITION_COLOR = new VertexFormat(
|
||||
new ImmutableList.Builder<VertexFormatElement>().add(POSITION_ELEMENT).add(COLOR_ELEMENT).build());
|
||||
new ImmutableList.Builder<VertexFormatElement>().add(POSITION_ELEMENT).add(COLOR_ELEMENT).build(),
|
||||
new PositionColorQuadWriter());
|
||||
public static final VertexFormat POSITION_COLOR_LIGHT = new VertexFormat(
|
||||
new ImmutableList.Builder<VertexFormatElement>().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<VertexFormatElement>().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<VertexFormatElement>().add(POSITION_ELEMENT).add(TEXTURE_ELEMENT)
|
||||
.add(LIGHT_ELEMENT).add(COLOR_ELEMENT).build());
|
||||
|
||||
+115
@@ -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<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -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) };
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user