diff --git a/README.MD b/README.MD index 5e3c21268..48cf9feb2 100644 --- a/README.MD +++ b/README.MD @@ -15,7 +15,7 @@ # Required Dependencies * [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.23 -* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.8.19 +* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.8.21 * NOTE: Some mods are not required, but a specific version is required if present - see: `Permanent Incompatibilities` below. # Known (temporary) Incompatibilities diff --git a/dependencies.gradle b/dependencies.gradle index b66bfcad0..4476be2f5 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -58,7 +58,7 @@ dependencies { // Iris Shaders compileOnly('org.jetbrains:annotations:26.0.2') - api("com.github.GTNewHorizons:GTNHLib:0.8.19:dev") + api("com.github.GTNewHorizons:GTNHLib:0.8.21:dev") shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") { exclude module: "antlr4" // we only want to shadow the runtime module diff --git a/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java b/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java index d6fb745c0..02d802e6b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java +++ b/src/main/java/com/gtnewhorizons/angelica/AngelicaMod.java @@ -18,7 +18,7 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; name = "Angelica", version = Tags.VERSION, dependencies = """ - required-after:gtnhlib@[0.8.19,);\ + required-after:gtnhlib@[0.8.21,);\ before:lwjgl3ify@[1.5.3,);\ after:hodgepodge@[2.4.4,);\ after:CodeChickenCore@[1.2.0,);\ diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java index caaa39931..20f63a1a3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CommandBufferBuilder.java @@ -30,7 +30,8 @@ public final class CommandBufferBuilder { public static void buildOptimizedFromRawBuffer( CommandBuffer rawBuffer, Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer, + final CompiledLineBuffer compiledLineBuffer, + final Map compiledPrimitiveBuffers, VertexBuffer[] ownedVbos, int glListId, CommandBuffer finalBuffer) { @@ -43,7 +44,7 @@ public final class CommandBufferBuilder { } // Collect all merged draw ranges sorted by command index - final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer); + final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); // Buffer optimizer state final BufferTransformOptimizer opt = new BufferTransformOptimizer(); @@ -82,9 +83,9 @@ public final class CommandBufferBuilder { */ public static void buildUnoptimizedFromRawBuffer( CommandBuffer rawBuffer, - List accumulatedDraws, Map compiledQuadBuffers, CompiledLineBuffer compiledLineBuffer, + Map compiledPrimitiveBuffers, VertexBuffer[] ownedVbos, CommandBuffer finalBuffer) { @@ -96,7 +97,7 @@ public final class CommandBufferBuilder { } // Collect all merged draw ranges sorted by command index - final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer); + final List allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); rawBuffer.resetRead(); int cmdIndex = 0; @@ -130,21 +131,53 @@ public final class CommandBufferBuilder { /** * Collect all draw ranges from compiled buffers, sorted by command index. */ - private static List collectDrawRanges( + static List collectDrawRanges( Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer) { + CompiledLineBuffer compiledLineBuffer, + Map compiledPrimitiveBuffers) { final List allRanges = new ArrayList<>(); - for (CompiledFormatBuffer compiledBuffer : compiledQuadBuffers.values()) { - for (DrawRange range : compiledBuffer.mergedRanges()) { - allRanges.add(new DrawRangeWithBuffer(range, compiledBuffer.vbo(), compiledBuffer.flags().hasBrightness)); + // Add quad ranges + final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]); + for (int b = 0; b < quadBufferArray.length; b++) { + final CompiledFormatBuffer compiledBuffer = quadBufferArray[b]; + final DrawRange[] ranges = compiledBuffer.mergedRanges(); + for (int i = 0; i < ranges.length; i++) { + allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags().hasBrightness)); } } + // Add immediate mode line ranges if (compiledLineBuffer != null) { - for (DrawRange range : compiledLineBuffer.mergedRanges()) { - allRanges.add(new DrawRangeWithBuffer(range, compiledLineBuffer.vbo(), false)); + final DrawRange[] ranges = compiledLineBuffer.mergedRanges(); + for (int i = 0; i < ranges.length; i++) { + allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), false)); + } + } + + // Add tessellator primitive ranges (lines and triangles) - grouped by format + if (compiledPrimitiveBuffers != null && !compiledPrimitiveBuffers.isEmpty()) { + final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]); + for (int p = 0; p < primBufferArray.length; p++) { + final CompiledPrimitiveBuffers primBuffers = primBufferArray[p]; + final boolean hasBrightness = primBuffers.flags().hasBrightness; + // Tessellator lines + if (primBuffers.hasLines()) { + final DrawRange[] ranges = primBuffers.lineMergedRanges(); + final VertexBuffer vbo = primBuffers.lineVbo(); + for (int i = 0; i < ranges.length; i++) { + allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness)); + } + } + // Tessellator triangles + if (primBuffers.hasTriangles()) { + final DrawRange[] ranges = primBuffers.triangleMergedRanges(); + final VertexBuffer vbo = primBuffers.triangleVbo(); + for (int i = 0; i < ranges.length; i++) { + allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness)); + } + } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java index 596365edf..a97d23012 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledFormatBuffer.java @@ -15,7 +15,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; * */ @Desugar -record CompiledFormatBuffer( +public record CompiledFormatBuffer( VertexBuffer vbo, CapturingTessellator.Flags flags, DrawRange[] mergedRanges, diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java new file mode 100644 index 000000000..523299994 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompiledPrimitiveBuffers.java @@ -0,0 +1,31 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.github.bsideup.jabel.Desugar; +import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; + +/** + * Compiled VBOs containing tessellator primitives (lines and triangles) for a single vertex format. + * Separate VBOs are used for lines (GL_LINES) and triangles (GL_TRIANGLES) since they have different draw modes. + *

+ * Contains range arrays for both optimized (merged) and unoptimized (per-draw) paths. + * Similar to CompiledFormatBuffer but handles primitives instead of quads. + */ +@Desugar +record CompiledPrimitiveBuffers( + CapturingTessellator.Flags flags, + VertexBuffer lineVbo, + DrawRange[] lineMergedRanges, + DrawRange[] linePerDrawRanges, + VertexBuffer triangleVbo, + DrawRange[] triangleMergedRanges, + DrawRange[] trianglePerDrawRanges +) { + public boolean hasLines() { + return lineVbo != null; + } + + public boolean hasTriangles() { + return triangleVbo != null; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java index cd0b0b1e9..f161ba647 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.glsm; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VBOManager; @@ -11,6 +12,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer; import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; @@ -32,7 +34,6 @@ import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.List; @@ -115,7 +116,8 @@ public class DisplayListManager { private static CommandRecorder currentRecorder = null; // Command recorder (null when not recording) private static volatile Thread recordingThread = null; // Thread that started recording (for thread-safety) private static List accumulatedDraws = null; // Accumulates quad draws for batching - private static List accumulatedLineDraws = null; // Accumulates line draws + private static List accumulatedLineDraws = null; // Accumulates immediate mode line draws + private static List accumulatedPrimitiveDraws = null; // Accumulates tessellator primitive draws (lines, triangles) private static Matrix4fStack relativeTransform = null; // Tracks relative transforms during compilation (with push/pop support) @Getter private static ImmediateModeRecorder immediateModeRecorder = null; // Records glBegin/glEnd/glVertex during compilation @@ -136,6 +138,7 @@ public class DisplayListManager { CommandRecorder recorder, List draws, List lineDraws, + List primitiveDraws, Matrix4fStack transform, boolean wasTessellatorCompiling, ImmediateModeRecorder immediateRecorder @@ -182,10 +185,12 @@ public class DisplayListManager { public static void recordClear(int mask) { if (currentRecorder != null) currentRecorder.recordClear(mask); } public static void recordClearColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordClearColor(r, g, b, a); } public static void recordClearDepth(double depth) { if (currentRecorder != null) currentRecorder.recordClearDepth(depth); } + public static void recordBlendColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordBlendColor(r, g, b, a); } public static void recordClearStencil(int s) { if (currentRecorder != null) currentRecorder.recordClearStencil(s); } public static void recordColor(float r, float g, float b, float a) { if (currentRecorder != null) currentRecorder.recordColor(r, g, b, a); } public static void recordColorMask(boolean r, boolean g, boolean b, boolean a) { if (currentRecorder != null) currentRecorder.recordColorMask(r, g, b, a); } public static void recordDepthMask(boolean flag) { if (currentRecorder != null) currentRecorder.recordDepthMask(flag); } + public static void recordFrontFace(int mode) { if (currentRecorder != null) currentRecorder.recordFrontFace(mode); } public static void recordDepthFunc(int func) { if (currentRecorder != null) currentRecorder.recordDepthFunc(func); } public static void recordBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { if (currentRecorder != null) currentRecorder.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); } public static void recordAlphaFunc(int func, float ref) { if (currentRecorder != null) currentRecorder.recordAlphaFunc(func, ref); } @@ -220,6 +225,7 @@ public class DisplayListManager { public static void recordPopAttrib() { if (currentRecorder != null) currentRecorder.recordPopAttrib(); } public static void recordFogf(int pname, float param) { if (currentRecorder != null) currentRecorder.recordFogf(pname, param); } public static void recordFogi(int pname, int param) { if (currentRecorder != null) currentRecorder.recordFogi(pname, param); } + public static void recordHint(int target, int mode) { if (currentRecorder != null) currentRecorder.recordHint(target, mode); } public static void recordFog(int pname, java.nio.FloatBuffer params) { if (currentRecorder != null) currentRecorder.recordFog(pname, params); } public static void recordLightf(int light, int pname, float param) { if (currentRecorder != null) currentRecorder.recordLightf(light, pname, param); } public static void recordLighti(int light, int pname, int param) { if (currentRecorder != null) currentRecorder.recordLighti(light, pname, param); } @@ -413,7 +419,7 @@ public class DisplayListManager { // Save current compilation context and start fresh for nested list final CompilationContext parentContext = new CompilationContext( glListId, glListMode, currentRecorder, accumulatedDraws, accumulatedLineDraws, - relativeTransform, tessellatorCompiling, immediateModeRecorder + accumulatedPrimitiveDraws, relativeTransform, tessellatorCompiling, immediateModeRecorder ); compilationStack.push(parentContext); } @@ -424,23 +430,36 @@ public class DisplayListManager { recordingThread = Thread.currentThread(); // Track which thread is recording currentRecorder = new CommandRecorder(); // Create command recorder accumulatedDraws = new ArrayList<>(64); // Fewer draws than commands typically - accumulatedLineDraws = new ArrayList<>(16); // Line draws are less common + accumulatedLineDraws = new ArrayList<>(16); // Immediate mode line draws are less common + accumulatedPrimitiveDraws = new ArrayList<>(16); // Tessellator primitive draws are less common relativeTransform = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH); relativeTransform.identity(); // Track relative transforms from identity immediateModeRecorder = new ImmediateModeRecorder(); // For glBegin/glEnd/glVertex // Start compiling mode with per-draw callback (works for both root and nested lists now) - TessellatorManager.setCompiling((quads, flags) -> { - if (quads.isEmpty()) { + // Callback receives quads (GL_QUADS) and primitives (GL_TRIANGLES, GL_LINES, etc.) + TessellatorManager.setCompiling((quads, primitives, flags) -> { + final boolean hasQuads = !quads.isEmpty(); + final boolean hasPrimitives = !primitives.isEmpty(); + + // Early exit to avoid allocations when nothing to accumulate + if (!hasQuads && !hasPrimitives) { return; } // Get relative transform (changes since glNewList, not absolute matrix state) final Matrix4f currentTransform = new Matrix4f(relativeTransform); + final int cmdIndex = getCommandCount(); - // Accumulate this draw for batching at glEndList() - final AccumulatedDraw draw = new AccumulatedDraw(quads, currentTransform, flags, getCommandCount()); - accumulatedDraws.add(draw); + // Accumulate quads for batching at glEndList() + if (hasQuads) { + accumulatedDraws.add(new AccumulatedDraw(quads, currentTransform, flags, cmdIndex)); + } + + // Accumulate primitives (lines, triangles) for batching at glEndList() + if (hasPrimitives) { + accumulatedPrimitiveDraws.add(new AccumulatedPrimitiveDraw(primitives, currentTransform, flags, cmdIndex)); + } }); tessellatorCompiling = true; @@ -472,23 +491,27 @@ public class DisplayListManager { final boolean hasCommands = rawCommandBuffer != null && rawCommandBuffer.size() > 0; final boolean hasDraws = accumulatedDraws != null && !accumulatedDraws.isEmpty(); final boolean hasLineDraws = accumulatedLineDraws != null && !accumulatedLineDraws.isEmpty(); + final boolean hasPrimitiveDraws = accumulatedPrimitiveDraws != null && !accumulatedPrimitiveDraws.isEmpty(); - if (hasCommands || hasDraws || hasLineDraws) { + if (hasCommands || hasDraws || hasLineDraws || hasPrimitiveDraws) { // Phase 1: Compile format-based VBOs (shared by both optimized and unoptimized paths) final Map compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws); - // Phase 2: Compile line VBO (shared by both paths) + // Phase 2: Compile immediate mode line VBO (shared by both paths) final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws); - // Collect all owned VBOs (quads + lines) - final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer); + // Phase 3: Compile tessellator primitive VBOs (lines, triangles) - grouped by format + final Map compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws); + + // Collect all owned VBOs (quads + immediate mode lines + tessellator primitives) + final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); // Build to CommandBuffer - optimize raw buffer to final buffer final CommandBuffer finalBuffer = new CommandBuffer(); if (DEBUG_DISPLAY_LISTS) { - CommandBufferBuilder.buildUnoptimizedFromRawBuffer(rawCommandBuffer, accumulatedDraws, compiledQuadBuffers, compiledLineBuffer, ownedVbos, finalBuffer); + CommandBufferBuilder.buildUnoptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, finalBuffer); } else { - CommandBufferBuilder.buildOptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, ownedVbos, glListId, finalBuffer); + CommandBufferBuilder.buildOptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, glListId, finalBuffer); } // Free the recorder (and its buffer) after optimization @@ -514,6 +537,7 @@ public class DisplayListManager { currentRecorder = parentContext.recorder; accumulatedDraws = parentContext.draws; accumulatedLineDraws = parentContext.lineDraws; + accumulatedPrimitiveDraws = parentContext.primitiveDraws; relativeTransform = parentContext.transform; tessellatorCompiling = parentContext.wasTessellatorCompiling; immediateModeRecorder = parentContext.immediateRecorder; @@ -526,6 +550,7 @@ public class DisplayListManager { recordingThread = null; accumulatedDraws = null; accumulatedLineDraws = null; + accumulatedPrimitiveDraws = null; relativeTransform = null; immediateModeRecorder = null; glListId = -1; @@ -652,22 +677,74 @@ public class DisplayListManager { */ private static VertexBuffer[] extractOwnedVbos( Map compiledQuadBuffers, - CompiledLineBuffer compiledLineBuffer) { + CompiledLineBuffer compiledLineBuffer, + Map compiledPrimitiveBuffers) { final List vbos = new ArrayList<>(); // Add quad VBOs - for (CompiledFormatBuffer buffer : compiledQuadBuffers.values()) { - vbos.add(buffer.vbo()); + final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]); + for (int i = 0; i < quadBufferArray.length; i++) { + vbos.add(quadBufferArray[i].vbo()); } - // Add line VBO if present + // Add immediate mode line VBO if present if (compiledLineBuffer != null) { vbos.add(compiledLineBuffer.vbo()); } + // Add tessellator primitive VBOs if present (one per format, separate for lines/triangles) + if (!compiledPrimitiveBuffers.isEmpty()) { + final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]); + for (int i = 0; i < primBufferArray.length; i++) { + final CompiledPrimitiveBuffers primBuffers = primBufferArray[i]; + if (primBuffers.hasLines()) { + vbos.add(primBuffers.lineVbo()); + } + if (primBuffers.hasTriangles()) { + vbos.add(primBuffers.triangleVbo()); + } + } + } + return vbos.toArray(new VertexBuffer[0]); } + /** + * Compile tessellator primitives (lines, triangles) into format-based VBOs. + * Groups draws by vertex format for optimal memory usage. + * + * @param primitiveDraws The accumulated primitive draws from tessellator callback + * @return Map of flags to compiled primitive buffers, empty map if no primitives + */ + private static Map compilePrimitiveBuffers( + List primitiveDraws) { + if (primitiveDraws == null || primitiveDraws.isEmpty()) { + return Collections.emptyMap(); + } + + // Group draws by vertex format + final Map formatBuffers = new HashMap<>(); + final int size = primitiveDraws.size(); + for (int i = 0; i < size; i++) { + final AccumulatedPrimitiveDraw draw = primitiveDraws.get(i); + formatBuffers.computeIfAbsent(draw.flags, TessellatorPrimitiveBuffer::new).addDraw(draw); + } + + // Compile each format's geometry into VBOs + final Map compiled = new HashMap<>(); + @SuppressWarnings("unchecked") + final Map.Entry[] entries = + formatBuffers.entrySet().toArray(new Map.Entry[0]); + for (int i = 0; i < entries.length; i++) { + final Map.Entry entry = entries[i]; + final CompiledPrimitiveBuffers result = entry.getValue().finish(); + if (result != null) { + compiled.put(entry.getKey(), result); + } + } + return compiled; + } + // ==================== Buffer-to-Buffer Optimization ==================== /** * Build optimized command list using pre-compiled VBOs. @@ -684,29 +761,15 @@ public class DisplayListManager { List currentCommands, Map compiledQuadBuffers, CompiledLineBuffer compiledLineBuffer, + Map compiledPrimitiveBuffers, int glListId) { final List optimized = new ArrayList<>(); final TransformOptimizer transformOpt = new TransformOptimizer(glListId); - // Collect all merged draw ranges (quads + lines) sorted by command index - final List allRanges = new ArrayList<>(); - - // Add quad ranges - for (CompiledFormatBuffer compiledBuffer : compiledQuadBuffers.values()) { - for (DrawRange range : compiledBuffer.mergedRanges()) { - allRanges.add(new DrawRangeWithBuffer(range, compiledBuffer.vbo(), compiledBuffer.flags().hasBrightness)); - } - } - - // Add line ranges - if (compiledLineBuffer != null) { - for (DrawRange range : compiledLineBuffer.mergedRanges()) { - allRanges.add(new DrawRangeWithBuffer(range, compiledLineBuffer.vbo(), false)); - } - } - - allRanges.sort(Comparator.comparingInt(r -> r.range().commandIndex())); + // Collect all merged draw ranges (quads + lines + primitives) sorted by command index + final List allRanges = CommandBufferBuilder.collectDrawRanges( + compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers); // Process command stream with interleaved draws final OptimizationContextImpl ctx = new OptimizationContextImpl(transformOpt, optimized); @@ -755,19 +818,19 @@ public class DisplayListManager { static OptimizedListResult buildOptimizedDisplayList( List currentCommands, List accumulatedDraws, - List accumulatedLineDraws, + List accumulatedPrimitiveDraws, int glListId) { // Compile quad VBOs final Map compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws); - // Compile line VBO - final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws); + // Compile tessellator primitive VBOs (lines, triangles) - grouped by format + final Map compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws); - // Extract owned VBOs - final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer); + // Extract owned VBOs (quads + primitives, no immediate mode lines in test path) + final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, null, compiledPrimitiveBuffers); // Build optimized commands using the new unified path - final DisplayListCommand[] optimized = buildOptimizedCommands(currentCommands, compiledQuadBuffers, compiledLineBuffer, glListId); + final DisplayListCommand[] optimized = buildOptimizedCommands(currentCommands, compiledQuadBuffers, null, compiledPrimitiveBuffers, glListId); return new OptimizedListResult(optimized, ownedVbos); } @@ -817,7 +880,7 @@ public class DisplayListManager { * Selects the optimal VertexFormat from GTNHLib defaults based on actual attribute usage. * This reduces memory usage by excluding unused attributes. */ - private static VertexFormat selectOptimalFormat(CapturingTessellator.Flags flags) { + static VertexFormat selectOptimalFormat(CapturingTessellator.Flags flags) { final boolean hasColor = flags.hasColor; final boolean hasTexture = flags.hasTexture; final boolean hasBrightness = flags.hasBrightness; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index 8ff171879..b27d37aea 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -881,9 +881,10 @@ public class GLStateManager { public static void glBlendColor(float red, float green, float blue, float alpha) { if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glBlendColor in display lists not yet implemented - if you see this, please report!"); + DisplayListManager.recordBlendColor(red, green, blue, alpha); + } else { + GL14.glBlendColor(red, green, blue, alpha); } - GL14.glBlendColor(red, green, blue, alpha); } public static void enableBlend() { @@ -3191,7 +3192,8 @@ public class GLStateManager { public static void glFrontFace(int mode) { if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glFrontFace in display lists not yet implemented - if you see this, please report!"); + DisplayListManager.recordFrontFace(mode); + return; } final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || polygonState.getFrontFace() != mode) { @@ -3203,8 +3205,12 @@ public class GLStateManager { } public static void glHint(int target, int mode) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glHint in display lists not yet implemented - if you see this, please report!"); + final boolean recording = DisplayListManager.isRecording(); + if (recording) { + DisplayListManager.recordHint(target, mode); + if (DisplayListManager.getListMode() == GL11.GL_COMPILE) { + return; + } } GL11.glHint(target, mode); } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java new file mode 100644 index 000000000..a138cace8 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/TessellatorPrimitiveBuffer.java @@ -0,0 +1,228 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; +import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; +import org.joml.Matrix4f; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +/** + * Accumulates tessellator primitives (lines, triangles) for a single vertex format during display list compilation. + * Similar to FormatBuffer but handles ModelPrimitiveView instances instead of quads. + *

+ * Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color), + * this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size. + *

+ * Primitives are separated by draw mode (GL_LINES, GL_TRIANGLES) into separate VBOs. + */ +class TessellatorPrimitiveBuffer { + final CapturingTessellator.Flags flags; + + // Accumulated primitives separated by type + final List allLines = new ArrayList<>(); + final List allTriangles = new ArrayList<>(); + + // Ranges for lines + final List lineMergedRanges = new ArrayList<>(); + final List linePerDrawRanges = new ArrayList<>(); + int currentLineVertexOffset = 0; + private int pendingLineStartVertex = -1; + private int pendingLineVertexCount = 0; + private Matrix4f pendingLineTransform = null; + private int pendingLineCommandIndex = -1; + + // Ranges for triangles + final List triangleMergedRanges = new ArrayList<>(); + final List trianglePerDrawRanges = new ArrayList<>(); + int currentTriangleVertexOffset = 0; + private int pendingTriangleStartVertex = -1; + private int pendingTriangleVertexCount = 0; + private Matrix4f pendingTriangleTransform = null; + private int pendingTriangleCommandIndex = -1; + + TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) { + this.flags = flags; + } + + /** + * Add a primitive draw to this buffer. + * Separates lines and triangles, tracking ranges for both merged and per-draw paths. + */ + void addDraw(AccumulatedPrimitiveDraw draw) { + final List primitives = draw.primitives; + final int size = primitives.size(); + + // Single pass: count and collect primitives by type + int lineCount = 0; + int triangleCount = 0; + for (int i = 0; i < size; i++) { + final ModelPrimitiveView prim = primitives.get(i); + if (prim instanceof ModelLine ml) { + allLines.add(ml); + lineCount++; + } else if (prim instanceof ModelTriangle mt) { + allTriangles.add(mt); + triangleCount++; + } + } + + // Process lines + if (lineCount > 0) { + final int lineVertexCount = lineCount * 2; // 2 vertices per line + linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex)); + + // Merge logic for optimized path + if (pendingLineTransform != null && pendingLineTransform.equals(draw.transform)) { + pendingLineVertexCount += lineVertexCount; + } else { + flushPendingLineRange(); + pendingLineStartVertex = currentLineVertexOffset; + pendingLineVertexCount = lineVertexCount; + pendingLineTransform = new Matrix4f(draw.transform); + pendingLineCommandIndex = draw.commandIndex; + } + currentLineVertexOffset += lineVertexCount; + } + + // Process triangles + if (triangleCount > 0) { + final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle + trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex)); + + // Merge logic for optimized path + if (pendingTriangleTransform != null && pendingTriangleTransform.equals(draw.transform)) { + pendingTriangleVertexCount += triangleVertexCount; + } else { + flushPendingTriangleRange(); + pendingTriangleStartVertex = currentTriangleVertexOffset; + pendingTriangleVertexCount = triangleVertexCount; + pendingTriangleTransform = new Matrix4f(draw.transform); + pendingTriangleCommandIndex = draw.commandIndex; + } + currentTriangleVertexOffset += triangleVertexCount; + } + } + + private void flushPendingLineRange() { + if (pendingLineTransform != null) { + lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex)); + pendingLineTransform = null; + } + } + + private void flushPendingTriangleRange() { + if (pendingTriangleTransform != null) { + triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex)); + pendingTriangleTransform = null; + } + } + + /** + * Compile all accumulated primitives into VBOs using optimal vertex format. + * @return The compiled buffers with separate VBOs for lines and triangles, or null if empty + */ + CompiledPrimitiveBuffers finish() { + flushPendingLineRange(); + flushPendingTriangleRange(); + + if (allLines.isEmpty() && allTriangles.isEmpty()) { + return null; + } + + // Use optimal format based on flags (same logic as quads) + final VertexFormat format = DisplayListManager.selectOptimalFormat(flags); + + final VertexBuffer lineVbo = allLines.isEmpty() ? null : compileLinesToVBO(format); + final VertexBuffer triangleVbo = allTriangles.isEmpty() ? null : compileTrianglesToVBO(format); + + return new CompiledPrimitiveBuffers( + flags, + lineVbo, + lineMergedRanges.toArray(new DrawRange[0]), + linePerDrawRanges.toArray(new DrawRange[0]), + triangleVbo, + triangleMergedRanges.toArray(new DrawRange[0]), + trianglePerDrawRanges.toArray(new DrawRange[0]) + ); + } + + private VertexBuffer compileLinesToVBO(VertexFormat format) { + final int vertexSize = format.getVertexSize(); + final int size = allLines.size(); + final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 2); + + for (int i = 0; i < size; i++) { + writePrimitiveToBuffer(allLines.get(i), buffer); + } + buffer.flip(); + + final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_LINES); + vbo.upload(buffer); + return vbo; + } + + private VertexBuffer compileTrianglesToVBO(VertexFormat format) { + final int vertexSize = format.getVertexSize(); + final int size = allTriangles.size(); + final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 3); + + for (int i = 0; i < size; i++) { + writePrimitiveToBuffer(allTriangles.get(i), buffer); + } + buffer.flip(); + + final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_TRIANGLES); + vbo.upload(buffer); + return vbo; + } + + /** + * Write a primitive's vertices to the buffer using the format specified by flags. + * Only writes attributes that are present in the format. + */ + private void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer) { + final int vertexCount = prim.getVertexCount(); + final boolean hasTexture = flags.hasTexture; + final boolean hasBrightness = flags.hasBrightness; + final boolean hasColor = flags.hasColor; + final boolean hasNormals = flags.hasNormals; + + for (int i = 0; i < vertexCount; i++) { + // Position (always present) - 12 bytes + buffer.putFloat(prim.getX(i)); + buffer.putFloat(prim.getY(i)); + buffer.putFloat(prim.getZ(i)); + + // Color (4 bytes, ABGR) - if present + if (hasColor) { + buffer.putInt(prim.getColor(i)); + } + + // Texture (2 floats = 8 bytes) - if present + if (hasTexture) { + buffer.putFloat(prim.getTexU(i)); + buffer.putFloat(prim.getTexV(i)); + } + + // Light/Brightness (4 bytes, packed) - if present + if (hasBrightness) { + buffer.putInt(prim.getLight(i)); + } + + // Normal (4 bytes, packed) - if present + if (hasNormals) { + buffer.putInt(prim.getForgeNormal(i)); + } + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java new file mode 100644 index 000000000..6ee4fae2f --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/AccumulatedPrimitiveDraw.java @@ -0,0 +1,58 @@ +package com.gtnewhorizons.angelica.glsm.recording; + +import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; +import org.joml.Matrix4f; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents an accumulated primitive draw call during display list compilation. + * Stores primitives (lines, triangles) from tessellator callback with their transform. + *

+ * Unlike AccumulatedLineDraw which stores ImmediateModeRecorder.LineVertex (16-byte: pos+color), + * this stores ModelPrimitiveView (32-byte: pos+color+tex+light+normal) from the tessellator. + */ +public class AccumulatedPrimitiveDraw { + public final List primitives; + public final Matrix4f transform; + public final CapturingTessellator.Flags flags; + public final int commandIndex; + + public AccumulatedPrimitiveDraw(List primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { + // Deep copy primitives - pooled primitives are reused after callback + this.primitives = deepCopyPrimitives(primitives); + this.transform = new Matrix4f(transform); + this.flags = flags; + this.commandIndex = commandIndex; + } + + /** + * Creates deep copies of all primitives in the list. + * Required because CapturingTessellator pools and reuses primitive objects. + */ + private static List deepCopyPrimitives(List source) { + final int size = source.size(); + final List copies = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + final ModelPrimitiveView prim = source.get(i); + if (prim instanceof ModelLine ml) { + copies.add(new ModelLine().copyFrom(ml)); + } else if (prim instanceof ModelTriangle mt) { + copies.add(new ModelTriangle().copyFrom(mt)); + } + } + return copies; + } + + @Override + public String toString() { + return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, mode=%d, flags=C%dT%dL%dN%d]", + primitives.size(), commandIndex, flags.drawMode, + flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, + flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java index ae908ef23..8ff25c1fc 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBuffer.java @@ -166,6 +166,12 @@ public final class CommandBuffer { writeInt(flag ? 1 : 0); } + public void writeFrontFace(int mode) { + ensureCapacity(8); + writeInt(GLCommand.FRONT_FACE); + writeInt(mode); + } + // === Two int commands === public void writeBindTexture(int target, int texture) { @@ -210,6 +216,13 @@ public final class CommandBuffer { writeInt(param); } + public void writeHint(int target, int mode) { + ensureCapacity(12); + writeInt(GLCommand.HINT); + writeInt(target); + writeInt(mode); + } + // === Three int commands === public void writeStencilFunc(int func, int ref, int mask) { @@ -336,6 +349,15 @@ public final class CommandBuffer { writeDouble(depth); } + public void writeBlendColor(float r, float g, float b, float a) { + ensureCapacity(20); + writeInt(GLCommand.BLEND_COLOR); + writeFloat(r); + writeFloat(g); + writeFloat(b); + writeFloat(a); + } + // === Mixed int+float commands === public void writeAlphaFunc(int func, float ref) { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java index 9dd3cc295..4c5339984 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferExecutor.java @@ -123,6 +123,10 @@ public final class CommandBufferExecutor { GLStateManager.glDepthMask(memGetInt(ptr) != 0); ptr += 4; } + case GLCommand.FRONT_FACE -> { + GLStateManager.glFrontFace(memGetInt(ptr)); + ptr += 4; + } // === Two int commands === case GLCommand.BIND_TEXTURE -> { @@ -161,6 +165,12 @@ public final class CommandBufferExecutor { ptr += 8; GLStateManager.glFogi(pname, param); } + case GLCommand.HINT -> { + final int target = memGetInt(ptr); + final int mode = memGetInt(ptr + 4); + ptr += 8; + GLStateManager.glHint(target, mode); + } // === Three int commands === case GLCommand.STENCIL_FUNC -> { @@ -274,6 +284,14 @@ public final class CommandBufferExecutor { ptr += 8; GLStateManager.glClearDepth(depth); } + case GLCommand.BLEND_COLOR -> { + final float r = memGetFloat(ptr); + final float g = memGetFloat(ptr + 4); + final float b = memGetFloat(ptr + 8); + final float a = memGetFloat(ptr + 12); + ptr += 16; + GLStateManager.glBlendColor(r, g, b, a); + } // === Mixed int+float commands === case GLCommand.ALPHA_FUNC -> { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java index 70241402f..b6d9be75b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandBufferProcessor.java @@ -155,6 +155,7 @@ public final class CommandBufferProcessor { case GLCommand.POP_MATRIX -> out.writePopMatrix(raw.readInt()); case GLCommand.STENCIL_MASK -> out.writeStencilMask(raw.readInt()); case GLCommand.DEPTH_MASK -> out.writeDepthMask(raw.readInt() != 0); + case GLCommand.FRONT_FACE -> out.writeFrontFace(raw.readInt()); // Two int commands case GLCommand.BIND_TEXTURE -> out.writeBindTexture(raw.readInt(), raw.readInt()); @@ -163,6 +164,7 @@ public final class CommandBufferProcessor { case GLCommand.LINE_STIPPLE -> out.writeLineStipple(raw.readInt(), raw.readInt()); case GLCommand.STENCIL_MASK_SEPARATE -> out.writeStencilMaskSeparate(raw.readInt(), raw.readInt()); case GLCommand.FOGI -> out.writeFogi(raw.readInt(), raw.readInt()); + case GLCommand.HINT -> out.writeHint(raw.readInt(), raw.readInt()); // Three int commands case GLCommand.STENCIL_FUNC -> out.writeStencilFunc(raw.readInt(), raw.readInt(), raw.readInt()); @@ -187,6 +189,9 @@ public final class CommandBufferProcessor { // Single double commands case GLCommand.CLEAR_DEPTH -> out.writeClearDepth(raw.readDouble()); + // Four float commands + case GLCommand.BLEND_COLOR -> out.writeBlendColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat()); + // Mixed int+float commands case GLCommand.ALPHA_FUNC -> out.writeAlphaFunc(raw.readInt(), raw.readFloat()); case GLCommand.FOGF -> out.writeFogf(raw.readInt(), raw.readFloat()); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java index 5592ade4e..8c6ce061d 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CommandRecorder.java @@ -56,6 +56,11 @@ public class CommandRecorder { commandCount++; } + public void recordBlendColor(float r, float g, float b, float a) { + buffer.writeBlendColor(r, g, b, a); + commandCount++; + } + public void recordClearStencil(int s) { buffer.writeClearStencil(s); commandCount++; @@ -76,6 +81,11 @@ public class CommandRecorder { commandCount++; } + public void recordFrontFace(int mode) { + buffer.writeFrontFace(mode); + commandCount++; + } + public void recordDepthFunc(int func) { buffer.writeDepthFunc(func); commandCount++; @@ -246,6 +256,11 @@ public class CommandRecorder { commandCount++; } + public void recordHint(int target, int mode) { + buffer.writeHint(target, mode); + commandCount++; + } + public void recordFog(int pname, FloatBuffer params) { buffer.writeFog(pname, params); commandCount++; diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java index a2f771e13..6b70fc482 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/CompiledDisplayList.java @@ -141,13 +141,13 @@ public final class CompiledDisplayList { GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM, GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.STENCIL_MASK, - GLCommand.DEPTH_MASK, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, + GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8; // Two int commands (12 bytes) case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL, GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI, - GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, + GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12; // Three int commands (16 bytes) @@ -158,13 +158,12 @@ public final class CompiledDisplayList { // Four int commands (20 bytes) case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK, GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE, - GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.DRAW_RANGE -> 20; - - // Single double commands (12 bytes) - case GLCommand.CLEAR_DEPTH -> 12; + GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR, + GLCommand.DRAW_RANGE -> 20; // Double commands case GLCommand.TRANSLATE, GLCommand.SCALE -> 32; // cmd + mode + 3 doubles + case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double case GLCommand.ROTATE -> 40; // cmd + mode + 4 doubles case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java index dc6b9e94a..568998b5c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/GLCommand.java @@ -27,6 +27,7 @@ public final class GLCommand { public static final int POP_MATRIX = 16; // [cmd:4][matrixMode:4] public static final int STENCIL_MASK = 17; // [cmd:4][mask:4] public static final int DEPTH_MASK = 18; // [cmd:4][flag:4] (0 or 1) + public static final int FRONT_FACE = 19; // [cmd:4][mode:4] // === Two int commands (12 bytes) === public static final int BIND_TEXTURE = 20; // [cmd:4][target:4][texture:4] @@ -35,6 +36,7 @@ public final class GLCommand { public static final int LINE_STIPPLE = 23; // [cmd:4][factor:4][pattern:4] public static final int STENCIL_MASK_SEPARATE = 24; // [cmd:4][face:4][mask:4] public static final int FOGI = 25; // [cmd:4][pname:4][param:4] + public static final int HINT = 26; // [cmd:4][target:4][mode:4] // === Three int commands (16 bytes) === public static final int STENCIL_FUNC = 30; // [cmd:4][func:4][ref:4][mask:4] @@ -55,9 +57,7 @@ public final class GLCommand { public static final int NORMAL = 53; // [cmd:4][x:4f][y:4f][z:4f] public static final int COLOR = 54; // [cmd:4][r:4f][g:4f][b:4f][a:4f] public static final int CLEAR_COLOR = 55; // [cmd:4][r:4f][g:4f][b:4f][a:4f] - - // === Double commands (single value) === - public static final int CLEAR_DEPTH = 56; // [cmd:4][depth:8d] = 12 bytes + public static final int BLEND_COLOR = 56; // [cmd:4][r:4f][g:4f][b:4f][a:4f] // === Mixed int+float commands === public static final int ALPHA_FUNC = 60; // [cmd:4][func:4][ref:4f] @@ -75,6 +75,7 @@ public final class GLCommand { public static final int SCALE = 72; // [cmd:4][mode:4][x:8d][y:8d][z:8d] = 32 bytes public static final int ORTHO = 73; // [cmd:4][left:8d][right:8d][bottom:8d][top:8d][zNear:8d][zFar:8d] = 52 bytes public static final int FRUSTUM = 74; // [cmd:4][left:8d][right:8d][bottom:8d][top:8d][zNear:8d][zFar:8d] = 52 bytes + public static final int CLEAR_DEPTH = 75; // [cmd:4][depth:8d] = 12 bytes // === Matrix commands (72 bytes) === public static final int MULT_MATRIX = 80; // [cmd:4][mode:4][m00-m33:64f] = 72 bytes @@ -116,12 +117,14 @@ public final class GLCommand { case POP_MATRIX -> "POP_MATRIX"; case STENCIL_MASK -> "STENCIL_MASK"; case DEPTH_MASK -> "DEPTH_MASK"; + case FRONT_FACE -> "FRONT_FACE"; case BIND_TEXTURE -> "BIND_TEXTURE"; case POLYGON_MODE -> "POLYGON_MODE"; case COLOR_MATERIAL -> "COLOR_MATERIAL"; case LINE_STIPPLE -> "LINE_STIPPLE"; case STENCIL_MASK_SEPARATE -> "STENCIL_MASK_SEPARATE"; case FOGI -> "FOGI"; + case HINT -> "HINT"; case STENCIL_FUNC -> "STENCIL_FUNC"; case STENCIL_OP -> "STENCIL_OP"; case TEX_PARAMETERI -> "TEX_PARAMETERI"; @@ -136,7 +139,7 @@ public final class GLCommand { case NORMAL -> "NORMAL"; case COLOR -> "COLOR"; case CLEAR_COLOR -> "CLEAR_COLOR"; - case CLEAR_DEPTH -> "CLEAR_DEPTH"; + case BLEND_COLOR -> "BLEND_COLOR"; case ALPHA_FUNC -> "ALPHA_FUNC"; case FOGF -> "FOGF"; case LIGHTF -> "LIGHTF"; @@ -150,6 +153,7 @@ public final class GLCommand { case SCALE -> "SCALE"; case ORTHO -> "ORTHO"; case FRUSTUM -> "FRUSTUM"; + case CLEAR_DEPTH -> "CLEAR_DEPTH"; case MULT_MATRIX -> "MULT_MATRIX"; case LOAD_MATRIX -> "LOAD_MATRIX"; case FOG -> "FOG"; diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java index 2e7815082..f66355d14 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListTestHelper.java @@ -1,9 +1,13 @@ package com.gtnewhorizons.angelica.glsm; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; import org.joml.Matrix4f; import java.util.ArrayList; @@ -205,4 +209,168 @@ public final class DisplayListTestHelper { public static Matrix4f scale(float s) { return new Matrix4f().scale(s); } + + // ==================== Primitive Builders (Lines, Triangles) ==================== + + /** + * Create a ModelLine from two vertex positions. + */ + public static ModelLine createLine(float x1, float y1, float z1, float x2, float y2, float z2) { + ModelLine line = new ModelLine(); + line.setX(0, x1); + line.setY(0, y1); + line.setZ(0, z1); + line.setColor(0, 0xFFFFFFFF); + line.setTexU(0, 0.0f); + line.setTexV(0, 0.0f); + line.setLight(0, 0); + line.setForgeNormal(0, 0); + + line.setX(1, x2); + line.setY(1, y2); + line.setZ(1, z2); + line.setColor(1, 0xFFFFFFFF); + line.setTexU(1, 1.0f); + line.setTexV(1, 1.0f); + line.setLight(1, 0); + line.setForgeNormal(1, 0); + return line; + } + + /** + * Create a simple unit line from (0,0,0) to (1,0,0). + */ + public static ModelLine createSimpleLine() { + return createLine(0, 0, 0, 1, 0, 0); + } + + /** + * Create multiple simple lines. + */ + public static List createLines(int count) { + List lines = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + lines.add(createLine(i, 0, 0, i + 1, 0, 0)); + } + return lines; + } + + /** + * Create a ModelTriangle from three vertex positions. + */ + public static ModelTriangle createTriangle(float x1, float y1, float z1, + float x2, float y2, float z2, + float x3, float y3, float z3) { + ModelTriangle tri = new ModelTriangle(); + tri.setX(0, x1); + tri.setY(0, y1); + tri.setZ(0, z1); + tri.setColor(0, 0xFFFFFFFF); + tri.setTexU(0, 0.0f); + tri.setTexV(0, 0.0f); + tri.setLight(0, 0); + tri.setForgeNormal(0, 0); + + tri.setX(1, x2); + tri.setY(1, y2); + tri.setZ(1, z2); + tri.setColor(1, 0xFFFFFFFF); + tri.setTexU(1, 1.0f); + tri.setTexV(1, 0.0f); + tri.setLight(1, 0); + tri.setForgeNormal(1, 0); + + tri.setX(2, x3); + tri.setY(2, y3); + tri.setZ(2, z3); + tri.setColor(2, 0xFFFFFFFF); + tri.setTexU(2, 0.5f); + tri.setTexV(2, 1.0f); + tri.setLight(2, 0); + tri.setForgeNormal(2, 0); + return tri; + } + + /** + * Create a simple unit triangle at origin. + */ + public static ModelTriangle createSimpleTriangle() { + return createTriangle(0, 0, 0, 1, 0, 0, 0.5f, 1, 0); + } + + /** + * Create multiple simple triangles. + */ + public static List createTriangles(int count) { + List triangles = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + triangles.add(createTriangle(i, 0, 0, i + 1, 0, 0, i + 0.5f, 1, 0)); + } + return triangles; + } + + /** + * Create a mixed list of primitives (lines and triangles). + */ + public static List createMixedPrimitives(int lineCount, int triangleCount) { + List primitives = new ArrayList<>(lineCount + triangleCount); + for (int i = 0; i < lineCount; i++) { + primitives.add(createLine(i, 0, 0, i + 1, 0, 0)); + } + for (int i = 0; i < triangleCount; i++) { + primitives.add(createTriangle(i, 1, 0, i + 1, 1, 0, i + 0.5f, 2, 0)); + } + return primitives; + } + + // ==================== AccumulatedPrimitiveDraw Builders ==================== + + /** + * Create an AccumulatedPrimitiveDraw with specified parameters. + */ + public static AccumulatedPrimitiveDraw createPrimitiveDraw( + List primitives, + Matrix4f transform, + CapturingTessellator.Flags flags, + int commandIndex) { + return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex); + } + + /** + * Create an AccumulatedPrimitiveDraw with lines only. + */ + public static AccumulatedPrimitiveDraw createLinesDraw(int lineCount, int commandIndex) { + List primitives = new ArrayList<>(lineCount); + for (ModelLine line : createLines(lineCount)) { + primitives.add(line); + } + return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); + } + + /** + * Create an AccumulatedPrimitiveDraw with triangles only. + */ + public static AccumulatedPrimitiveDraw createTrianglesDraw(int triangleCount, int commandIndex) { + List primitives = new ArrayList<>(triangleCount); + for (ModelTriangle tri : createTriangles(triangleCount)) { + primitives.add(tri); + } + return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); + } + + /** + * Create an AccumulatedPrimitiveDraw with mixed lines and triangles. + */ + public static AccumulatedPrimitiveDraw createMixedPrimitiveDraw(int lineCount, int triangleCount, int commandIndex) { + List primitives = createMixedPrimitives(lineCount, triangleCount); + return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex); + } + + /** + * Create an AccumulatedPrimitiveDraw with specified transform. + */ + public static AccumulatedPrimitiveDraw createPrimitiveDrawWithTransform( + List primitives, Matrix4f transform, int commandIndex) { + return createPrimitiveDraw(primitives, transform, positionOnly(), commandIndex); + } } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java new file mode 100644 index 000000000..4bee58c0b --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Primitive_Test.java @@ -0,0 +1,535 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; +import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; +import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; +import com.gtnewhorizons.angelica.AngelicaExtension; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw; +import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw; +import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; +import com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd; +import org.joml.Matrix4f; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static com.gtnewhorizons.angelica.glsm.DisplayListTestHelper.*; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests for display list primitive (lines, triangles) handling. + * + *

Tests cover: + *

    + *
  • AccumulatedPrimitiveDraw deep copying behavior
  • + *
  • TessellatorPrimitiveBuffer accumulation and range merging
  • + *
  • Integration with buildOptimizedDisplayList for primitive VBOs
  • + *
  • Mixed quad + primitive display lists
  • + *
+ */ +@ExtendWith(AngelicaExtension.class) +class GLSM_DisplayList_Primitive_Test { + + // ==================== Helper Methods ==================== + + private long countDrawRangeCmds(DisplayListCommand[] commands) { + long count = 0; + for (DisplayListCommand cmd : commands) { + if (cmd instanceof DrawRangeCmd) count++; + } + return count; + } + + private Set getUniqueVBOs(DisplayListCommand[] commands) { + Set vbos = new HashSet<>(); + for (DisplayListCommand cmd : commands) { + if (cmd instanceof DrawRangeCmd rangeCmd) { + vbos.add(rangeCmd.sharedVbo()); + } + } + return vbos; + } + + // ==================== AccumulatedPrimitiveDraw Tests ==================== + + @Test + void testAccumulatedPrimitiveDrawDeepCopiesLines() { + // Setup: Create a line and capture its original values + ModelLine originalLine = createSimpleLine(); + float originalX0 = originalLine.getX(0); + float originalY0 = originalLine.getY(0); + + List primitives = new ArrayList<>(); + primitives.add(originalLine); + + // Execute: Create AccumulatedPrimitiveDraw (should deep copy) + AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( + primitives, identity(), positionOnly(), 0); + + // Modify original + originalLine.setX(0, 999.0f); + originalLine.setY(0, 888.0f); + + // Verify: Copied primitive should be unchanged + ModelPrimitiveView copied = draw.primitives.get(0); + assertTrue(copied instanceof ModelLine, "Copied primitive should be a ModelLine"); + ModelLine copiedLine = (ModelLine) copied; + assertEquals(originalX0, copiedLine.getX(0), 0.001f, "Deep copy should preserve original X value"); + assertEquals(originalY0, copiedLine.getY(0), 0.001f, "Deep copy should preserve original Y value"); + } + + @Test + void testAccumulatedPrimitiveDrawDeepCopiesTriangles() { + // Setup: Create a triangle and capture its original values + ModelTriangle originalTri = createSimpleTriangle(); + float originalX0 = originalTri.getX(0); + float originalX1 = originalTri.getX(1); + float originalX2 = originalTri.getX(2); + + List primitives = new ArrayList<>(); + primitives.add(originalTri); + + // Execute: Create AccumulatedPrimitiveDraw (should deep copy) + AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( + primitives, identity(), positionOnly(), 0); + + // Modify original + originalTri.setX(0, 999.0f); + originalTri.setX(1, 888.0f); + originalTri.setX(2, 777.0f); + + // Verify: Copied primitive should be unchanged + ModelPrimitiveView copied = draw.primitives.get(0); + assertTrue(copied instanceof ModelTriangle, "Copied primitive should be a ModelTriangle"); + ModelTriangle copiedTri = (ModelTriangle) copied; + assertEquals(originalX0, copiedTri.getX(0), 0.001f, "Deep copy should preserve original X0 value"); + assertEquals(originalX1, copiedTri.getX(1), 0.001f, "Deep copy should preserve original X1 value"); + assertEquals(originalX2, copiedTri.getX(2), 0.001f, "Deep copy should preserve original X2 value"); + } + + @Test + void testAccumulatedPrimitiveDrawDeepCopiesMixedPrimitives() { + // Setup: Create mixed primitives + List primitives = createMixedPrimitives(2, 2); + + // Execute + AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( + primitives, identity(), positionOnly(), 0); + + // Verify: All primitives copied correctly + assertEquals(4, draw.primitives.size(), "Should have 4 primitives (2 lines + 2 triangles)"); + + int lineCount = 0; + int triCount = 0; + for (ModelPrimitiveView prim : draw.primitives) { + if (prim instanceof ModelLine) lineCount++; + else if (prim instanceof ModelTriangle) triCount++; + } + assertEquals(2, lineCount, "Should have 2 lines"); + assertEquals(2, triCount, "Should have 2 triangles"); + } + + @Test + void testAccumulatedPrimitiveDrawDeepCopiesTransform() { + // Setup + Matrix4f originalTransform = translate(1.0f, 2.0f, 3.0f); + List primitives = new ArrayList<>(); + primitives.add(createSimpleLine()); + + // Execute + AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw( + primitives, originalTransform, positionOnly(), 0); + + // Modify original transform + originalTransform.identity(); + + // Verify: Stored transform should be unchanged (not identity) + assertFalse(draw.transform.equals(new Matrix4f()), "Transform should be deep copied, not identity"); + assertEquals(1.0f, draw.transform.m30(), 0.001f, "Transform X translation should be preserved"); + assertEquals(2.0f, draw.transform.m31(), 0.001f, "Transform Y translation should be preserved"); + assertEquals(3.0f, draw.transform.m32(), 0.001f, "Transform Z translation should be preserved"); + } + + // ==================== TessellatorPrimitiveBuffer Tests ==================== + + @Test + void testPrimitiveBufferSeparatesLinesByTransform() { + // Setup: Create primitive buffer and add draws with different transforms + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + + AccumulatedPrimitiveDraw draw1 = createLinesDraw(2, 0); // 2 lines at identity + AccumulatedPrimitiveDraw draw2 = createPrimitiveDrawWithTransform( + createMixedPrimitives(2, 0), translate(1, 0, 0), 1); // 2 lines translated + + buffer.addDraw(draw1); + buffer.addDraw(draw2); + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify: Has lines, no triangles + assertNotNull(compiled, "Should compile non-empty buffer"); + assertTrue(compiled.hasLines(), "Should have lines"); + assertFalse(compiled.hasTriangles(), "Should not have triangles"); + + // 2 merged ranges (different transforms) + assertEquals(2, compiled.lineMergedRanges().length, + "Different transforms should produce separate merged ranges"); + } + + @Test + void testPrimitiveBufferMergesSameTransformLines() { + // Setup: Multiple draws with same transform + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + + buffer.addDraw(createLinesDraw(2, 0)); // 2 lines + buffer.addDraw(createLinesDraw(3, 0)); // 3 more lines, same transform + buffer.addDraw(createLinesDraw(1, 0)); // 1 more line, same transform + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify: 1 merged range (all same transform) + assertNotNull(compiled); + assertEquals(1, compiled.lineMergedRanges().length, + "Same transform draws should merge into 1 range"); + + // Total vertices: (2+3+1) lines * 2 vertices = 12 + assertEquals(12, compiled.lineMergedRanges()[0].vertexCount(), + "Merged range should contain all line vertices"); + } + + @Test + void testPrimitiveBufferSeparatesTrianglesByTransform() { + // Setup + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + + buffer.addDraw(createTrianglesDraw(2, 0)); // 2 triangles at identity + buffer.addDraw(createPrimitiveDrawWithTransform( + createMixedPrimitives(0, 2), translate(1, 0, 0), 1)); // 2 triangles translated + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify + assertNotNull(compiled); + assertFalse(compiled.hasLines(), "Should not have lines"); + assertTrue(compiled.hasTriangles(), "Should have triangles"); + + assertEquals(2, compiled.triangleMergedRanges().length, + "Different transforms should produce separate merged ranges"); + } + + @Test + void testPrimitiveBufferMergesSameTransformTriangles() { + // Setup + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + + buffer.addDraw(createTrianglesDraw(2, 0)); // 2 triangles + buffer.addDraw(createTrianglesDraw(3, 0)); // 3 more, same transform + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify: 1 merged range + assertNotNull(compiled); + assertEquals(1, compiled.triangleMergedRanges().length, + "Same transform draws should merge into 1 range"); + + // Total vertices: (2+3) triangles * 3 vertices = 15 + assertEquals(15, compiled.triangleMergedRanges()[0].vertexCount(), + "Merged range should contain all triangle vertices"); + } + + @Test + void testPrimitiveBufferHandlesMixedLinesAndTriangles() { + // Setup: Draw with mixed primitives + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + buffer.addDraw(createMixedPrimitiveDraw(3, 2, 0)); // 3 lines + 2 triangles + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify: Both types present + assertNotNull(compiled); + assertTrue(compiled.hasLines(), "Should have lines"); + assertTrue(compiled.hasTriangles(), "Should have triangles"); + + // Verify counts + assertEquals(6, compiled.lineMergedRanges()[0].vertexCount(), + "Should have 6 line vertices (3 lines * 2)"); + assertEquals(6, compiled.triangleMergedRanges()[0].vertexCount(), + "Should have 6 triangle vertices (2 triangles * 3)"); + } + + @Test + void testPrimitiveBufferEmptyReturnsNull() { + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + CompiledPrimitiveBuffers compiled = buffer.finish(); + assertNull(compiled, "Empty buffer should return null"); + } + + @Test + void testPrimitiveBufferPerDrawRangesTrackEachDraw() { + // Setup: Multiple draws + TessellatorPrimitiveBuffer buffer = new TessellatorPrimitiveBuffer(positionOnly()); + + buffer.addDraw(createLinesDraw(2, 0)); // 4 vertices + buffer.addDraw(createLinesDraw(3, 1)); // 6 vertices (same transform, different cmd index) + buffer.addDraw(createLinesDraw(1, 2)); // 2 vertices + + // Execute + CompiledPrimitiveBuffers compiled = buffer.finish(); + + // Verify: Per-draw ranges track each individual draw + assertNotNull(compiled); + assertEquals(3, compiled.linePerDrawRanges().length, + "Should have 3 per-draw ranges"); + + // Verify individual range sizes + assertEquals(4, compiled.linePerDrawRanges()[0].vertexCount()); + assertEquals(6, compiled.linePerDrawRanges()[1].vertexCount()); + assertEquals(2, compiled.linePerDrawRanges()[2].vertexCount()); + } + + @Test + void testDifferentFlagsProduceDifferentFormats() { + // Test that format-aware compilation uses optimal vertex sizes + // positionOnly = 12 bytes, positionColor = 16 bytes, fullFormat = 32 bytes + + // Position only (12 bytes per vertex) + TessellatorPrimitiveBuffer posOnlyBuffer = new TessellatorPrimitiveBuffer(positionOnly()); + posOnlyBuffer.addDraw(createLinesDraw(1, 0)); + CompiledPrimitiveBuffers posOnlyCompiled = posOnlyBuffer.finish(); + assertNotNull(posOnlyCompiled); + assertEquals(positionOnly(), posOnlyCompiled.flags(), "Should preserve positionOnly flags"); + + // Position + Color (16 bytes per vertex) + TessellatorPrimitiveBuffer posColorBuffer = new TessellatorPrimitiveBuffer(positionColor()); + posColorBuffer.addDraw(createPrimitiveDraw(createMixedPrimitives(1, 0), identity(), positionColor(), 0)); + CompiledPrimitiveBuffers posColorCompiled = posColorBuffer.finish(); + assertNotNull(posColorCompiled); + assertEquals(positionColor(), posColorCompiled.flags(), "Should preserve positionColor flags"); + + // Full format (32 bytes per vertex) + TessellatorPrimitiveBuffer fullBuffer = new TessellatorPrimitiveBuffer(fullFormat()); + fullBuffer.addDraw(createPrimitiveDraw(createMixedPrimitives(1, 0), identity(), fullFormat(), 0)); + CompiledPrimitiveBuffers fullCompiled = fullBuffer.finish(); + assertNotNull(fullCompiled); + assertEquals(fullFormat(), fullCompiled.flags(), "Should preserve fullFormat flags"); + + // Verify the flags differ (ensuring format selection works) + assertNotEquals(posOnlyCompiled.flags(), posColorCompiled.flags()); + assertNotEquals(posColorCompiled.flags(), fullCompiled.flags()); + } + + // ==================== Integration Tests ==================== + + @Test + void testBuildOptimizedDisplayListWithLinesOnly() { + // Setup: Only primitive draws + List quadDraws = new ArrayList<>(); + List primitiveDraws = new ArrayList<>(); + primitiveDraws.add(createLinesDraw(5, 0)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 1 VBO for lines + assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for lines"); + + // Verify: 1 DrawRangeCmd + assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); + } + + @Test + void testBuildOptimizedDisplayListWithTrianglesOnly() { + // Setup + List quadDraws = new ArrayList<>(); + List primitiveDraws = new ArrayList<>(); + primitiveDraws.add(createTrianglesDraw(3, 0)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 1 VBO for triangles + assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for triangles"); + assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); + } + + @Test + void testBuildOptimizedDisplayListWithMixedPrimitives() { + // Setup: Lines and triangles + List quadDraws = new ArrayList<>(); + List primitiveDraws = new ArrayList<>(); + primitiveDraws.add(createLinesDraw(3, 0)); + primitiveDraws.add(createTrianglesDraw(2, 1)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 2 VBOs (one for lines, one for triangles) + assertEquals(2, result.ownedVbos().length, + "Should have 2 VBOs (lines + triangles)"); + assertEquals(2, countDrawRangeCmds(optimized), + "Should have 2 DrawRangeCmds"); + } + + @Test + void testBuildOptimizedDisplayListWithQuadsAndPrimitives() { + // Setup: Mixed quads and primitives + List quadDraws = new ArrayList<>(); + quadDraws.add(createSimpleDraw(0)); // 1 quad + + List primitiveDraws = new ArrayList<>(); + primitiveDraws.add(createLinesDraw(2, 1)); // 2 lines + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 2 VBOs (quads + lines) + assertEquals(2, result.ownedVbos().length, + "Should have 2 VBOs (quads + lines)"); + assertEquals(2, countDrawRangeCmds(optimized), + "Should have 2 DrawRangeCmds"); + + // Verify unique VBOs in commands + Set uniqueVBOs = getUniqueVBOs(optimized); + assertEquals(2, uniqueVBOs.size(), "Commands should reference 2 unique VBOs"); + } + + @Test + void testBuildOptimizedDisplayListWithQuadsLinesAndTriangles() { + // Setup: All three types + List quadDraws = new ArrayList<>(); + quadDraws.add(createSimpleDraw(0)); + + List primitiveDraws = new ArrayList<>(); + primitiveDraws.add(createLinesDraw(2, 1)); + primitiveDraws.add(createTrianglesDraw(2, 2)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 3 VBOs (quads + lines + triangles) + assertEquals(3, result.ownedVbos().length, + "Should have 3 VBOs (quads + lines + triangles)"); + assertEquals(3, countDrawRangeCmds(optimized), + "Should have 3 DrawRangeCmds"); + } + + @Test + void testBuildOptimizedDisplayListPrimitiveTransformMerging() { + // Setup: Multiple draws with same transform should merge + List quadDraws = new ArrayList<>(); + List primitiveDraws = new ArrayList<>(); + + // Add 3 line draws at same transform + primitiveDraws.add(createLinesDraw(2, 0)); + primitiveDraws.add(createLinesDraw(3, 0)); + primitiveDraws.add(createLinesDraw(1, 0)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 1 VBO, 1 merged DrawRangeCmd + assertEquals(1, result.ownedVbos().length, "Should have 1 VBO"); + assertEquals(1, countDrawRangeCmds(optimized), + "Same-transform draws should merge into 1 DrawRangeCmd"); + } + + @Test + void testBuildOptimizedDisplayListPrimitiveDifferentTransforms() { + // Setup: Draws with different transforms + List quadDraws = new ArrayList<>(); + List primitiveDraws = new ArrayList<>(); + + List lines1 = new ArrayList<>(); + lines1.add(createSimpleLine()); + primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0)); + + List lines2 = new ArrayList<>(); + lines2.add(createSimpleLine()); + primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1)); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: 1 VBO (same format), 2 DrawRangeCmds (different transforms) + assertEquals(1, result.ownedVbos().length, + "Same-type primitives should share VBO"); + assertEquals(2, countDrawRangeCmds(optimized), + "Different transforms should produce separate DrawRangeCmds"); + } + + @Test + void testBuildOptimizedDisplayListNullPrimitiveDraws() { + // Setup: null primitiveDraws list (backwards compatibility) + List quadDraws = new ArrayList<>(); + quadDraws.add(createSimpleDraw(0)); + + List commands = new ArrayList<>(); + + // Execute: Pass null for primitiveDraws + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, null, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: Works normally with just quads + assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for quads"); + assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); + } + + @Test + void testBuildOptimizedDisplayListEmptyPrimitiveDraws() { + // Setup: Empty primitiveDraws list + List quadDraws = new ArrayList<>(); + quadDraws.add(createSimpleDraw(0)); + + List primitiveDraws = new ArrayList<>(); + + List commands = new ArrayList<>(); + + // Execute + OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList( + commands, quadDraws, primitiveDraws, 1); + DisplayListCommand[] optimized = result.commands(); + + // Verify: Works normally with just quads + assertEquals(1, result.ownedVbos().length, "Should have 1 VBO for quads"); + assertEquals(1, countDrawRangeCmds(optimized), "Should have 1 DrawRangeCmd"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_UnitTest.java index d77fe69b1..538432140 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_UnitTest.java @@ -196,4 +196,118 @@ class GLSM_DisplayList_UnitTest { GLStateManager.glClearDepth(1.0); GLStateManager.glDeleteLists(list, 1); } + + // ==================== BlendColor Tests ==================== + + @Test + void testBlendColorInDisplayList() { + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE); + GLStateManager.glBlendColor(0.2f, 0.4f, 0.6f, 0.8f); + GLStateManager.glEndList(); + + // Call the display list - should not throw + GLStateManager.glCallList(list); + + // Cleanup + GLStateManager.glBlendColor(0f, 0f, 0f, 0f); + GLStateManager.glDeleteLists(list, 1); + } + + @Test + void testBlendColorCompileAndExecute() { + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE); + GLStateManager.glBlendColor(0.5f, 0.5f, 0.5f, 1.0f); + GLStateManager.glEndList(); + + // Should not throw - display list was executed + GLStateManager.glCallList(list); + + // Cleanup + GLStateManager.glBlendColor(0f, 0f, 0f, 0f); + GLStateManager.glDeleteLists(list, 1); + } + + // ==================== FrontFace Tests ==================== + + @Test + void testFrontFaceInDisplayList() { + // Get initial front face + int initialMode = GL11.glGetInteger(GL11.GL_FRONT_FACE); + + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE); + GLStateManager.glFrontFace(GL11.GL_CW); + GLStateManager.glEndList(); + + // After compile, mode should be unchanged + assertEquals(initialMode, GL11.glGetInteger(GL11.GL_FRONT_FACE), "FrontFace should be unchanged after GL_COMPILE"); + + // Call the display list + GLStateManager.glCallList(list); + + // Now mode should be GL_CW + assertEquals(GL11.GL_CW, GL11.glGetInteger(GL11.GL_FRONT_FACE), "FrontFace should be GL_CW after calling display list"); + + // Cleanup + GLStateManager.glFrontFace(GL11.GL_CCW); // Reset to default + GLStateManager.glDeleteLists(list, 1); + } + + @Test + void testFrontFaceCompileAndExecute() { + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE); + GLStateManager.glFrontFace(GL11.GL_CW); + GLStateManager.glEndList(); + + // After compile and execute, mode should be changed + assertEquals(GL11.GL_CW, GL11.glGetInteger(GL11.GL_FRONT_FACE), "FrontFace should be GL_CW after GL_COMPILE_AND_EXECUTE"); + + // Cleanup + GLStateManager.glFrontFace(GL11.GL_CCW); + GLStateManager.glDeleteLists(list, 1); + } + + // ==================== Hint Tests ==================== + + @Test + void testHintInDisplayList() { + // Get initial hint value + int initialHint = GL11.glGetInteger(GL11.GL_LINE_SMOOTH_HINT); + + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE); + GLStateManager.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_NICEST); + GLStateManager.glEndList(); + + // After compile, hint should be unchanged + assertEquals(initialHint, GL11.glGetInteger(GL11.GL_LINE_SMOOTH_HINT), "Hint should be unchanged after GL_COMPILE"); + + // Call the display list + GLStateManager.glCallList(list); + + // Now hint should be GL_NICEST + assertEquals(GL11.GL_NICEST, GL11.glGetInteger(GL11.GL_LINE_SMOOTH_HINT), "Hint should be GL_NICEST after calling display list"); + + // Cleanup + GLStateManager.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_DONT_CARE); // Reset to default + GLStateManager.glDeleteLists(list, 1); + } + + @Test + void testHintCompileAndExecute() { + int list = GL11.glGenLists(1); + GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE); + GLStateManager.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_FASTEST); + GLStateManager.glEndList(); + + // After compile and execute, hint should be changed + assertEquals(GL11.GL_FASTEST, GL11.glGetInteger(GL11.GL_LINE_SMOOTH_HINT), "Hint should be GL_FASTEST after GL_COMPILE_AND_EXECUTE"); + + // Cleanup + GLStateManager.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_DONT_CARE); + GLStateManager.glDeleteLists(list, 1); + } }