Compare commits

...
Author SHA1 Message Date
Jason Mitchell 77875f7f91 Stop recording normals... we're already baking them into a VBO 2025-12-08 15:28:07 -08:00
Jason Mitchell 241c32def1 Add some transformer exclusions 2025-12-08 14:57:27 -08:00
sisyphussy a8107f97e8 Add VAO's (#1126) 2025-12-07 16:51:32 -08:00
Death FuelandJason Mitchell 8bec433699 GT5 custom glyph handling and visual fixes (#1148)
Co-authored-by: Jason Mitchell <[email protected]>
2025-12-06 09:48:03 -08:00
Kotmatross 2d39fb2397 [BCF] Fix z-fighting on GT ores 2: here we go again edition (#1161) 2025-12-06 08:17:26 -08:00
Jason Mitchell cfd8eb1411 fix compatability profile detection (#1159) 2025-12-05 17:01:20 -08:00
Jason Mitchell 59c270a5b9 glFrontFace, glHint, and glBlendColor (#1156) 2025-12-05 16:11:04 -08:00
Jason Mitchell 87ac03281c Add clear depth in display lists 2025-12-04 09:21:22 -08:00
Jason Mitchell 36b82fa2ce Update README.MD 2025-12-03 16:01:26 -08:00
Jason Mitchell 2fc2e2e38d Fix some small things
* Bump nhlib dep due to crash when Iris is disabled
* Use jabel for tests
* use joml isIdentity
* remove Integer usage
2025-12-03 10:54:20 -08:00
44 changed files with 1569 additions and 208 deletions

No files matched your search

+2 -2
View File
@@ -14,8 +14,8 @@
# Required Dependencies
* [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.19
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.8.6
* [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.23
* [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
+5
View File
@@ -5,6 +5,11 @@ plugins {
minecraft {
extraRunJvmArguments.add("-Dangelica.enableTestBlocks=true")
extraRunJvmArguments.add("-Dangelica.dumpClass=true")
/* extraRunJvmArguments.addAll(
"-Dlegacy.debugClassLoading=true",
"-Dlegacy.debugClassLoadingFiner=true",
"-Dlegacy.debugClassLoadingSave=true")*/
//extraRunJvmArguments.add("-Dangelica.redirectorLogspam=true")
}
+2 -1
View File
@@ -58,7 +58,7 @@ dependencies {
// Iris Shaders
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.8.18: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
@@ -114,6 +114,7 @@ dependencies {
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
testAnnotationProcessor("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1")
compileOnly("mega:fluidlogged-mc1.7.10:0.1.2")
}
@@ -18,7 +18,7 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
name = "Angelica",
version = Tags.VERSION,
dependencies = """
required-after:gtnhlib@[0.8.18,);\
required-after:gtnhlib@[0.8.21,);\
before:lwjgl3ify@[1.5.3,);\
after:hodgepodge@[2.4.4,);\
after:CodeChickenCore@[1.2.0,);\
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
@@ -380,11 +381,11 @@ public class BatchingFontRenderer {
}
public float getGlyphScaleX() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphScaleY() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphSpacing() {
@@ -431,13 +432,13 @@ public class BatchingFontRenderer {
boolean curStrikethrough = false;
boolean curUnderline = false;
final float glyphScaleY = getGlyphScaleY();
final float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2);
final float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY;
float glyphScaleY = getGlyphScaleY();
float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2);
final float underlineY = heightNorth + (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY;
float underlineStartX = 0.0f;
float underlineEndX = 0.0f;
final float strikethroughY = heightNorth + ((float) (underlying.FONT_HEIGHT / 2) - 1.0f) * glyphScaleY;
float strikethroughStartX = 0.0f;
float strikethroughEndX = 0.0f;
@@ -507,12 +508,22 @@ public class BatchingFontRenderer {
continue;
}
if (FontConfig.enableCustomFont) {
String chrReplacement = GlyphReplacements.customGlyphs.get(String.valueOf(chr));
if (chrReplacement != null) {
chr = chrReplacement.charAt(0);
}
}
if (curRandom) {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY * fontProvider.getYScaleMultiplier() / 2);
float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY * fontProvider.getYScaleMultiplier();
// Check ASCII space, NBSP, NNBSP
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
curX += 4 * this.getWhitespaceScale();
@@ -527,6 +538,7 @@ public class BatchingFontRenderer {
final float vSz = fontProvider.getVSize(chr);
final float itOff = curItalic ? 1.0F : 0.0F; // italic offset
final float shadowOffset = fontProvider.getShadowOffset();
final float xShift = (fontProvider instanceof FontProviderCustom ? getGlyphScaleX() * FontConfig.customFontScale : 0.0f); // corrective factor to improve text alignment
final int shadowCopies = FontConfig.shadowCopies;
final int boldCopies = FontConfig.boldCopies;
final ResourceLocation texture = fontProvider.getTexture(chr);
@@ -535,20 +547,20 @@ public class BatchingFontRenderer {
if (enableShadow) {
for (int n = 1; n <= shadowCopies; n++) {
final float shadowOffsetPart = shadowOffset * ((float) n / shadowCopies);
pushTexRect(curX + shadowOffsetPart, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
pushTexRect(curX + shadowOffsetPart - xShift, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
if (curBold) {
pushTexRect(curX + 2.0f * shadowOffsetPart, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
pushTexRect(curX + 2.0f * shadowOffsetPart - xShift, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
}
}
}
pushTexRect(curX, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
pushTexRect(curX - xShift, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
if (curBold) {
for (int n = 1; n <= boldCopies; n++) {
final float shadowOffsetPart = shadowOffset * ((float) n / boldCopies);
pushTexRect(curX + shadowOffsetPart, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
pushTexRect(curX + shadowOffsetPart - xShift, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
}
}
@@ -17,4 +17,5 @@ public interface FontProvider {
float getVSize(char chr);
float getShadowOffset();
ResourceLocation getTexture(char chr);
float getYScaleMultiplier();
}
@@ -270,12 +270,12 @@ public final class FontProviderCustom implements FontProvider {
@Override
public float getXAdvance(char chr) {
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance;
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance * FontConfig.customFontScale;
}
@Override
public float getGlyphW(char chr) {
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW;
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW * FontConfig.customFontScale;
}
@Override
@@ -297,4 +297,9 @@ public final class FontProviderCustom implements FontProvider {
public ResourceLocation getTexture(char chr) {
return getAtlas(chr).texture;
}
@Override
public float getYScaleMultiplier() {
return FontConfig.customFontScale;
}
}
@@ -103,4 +103,9 @@ public final class FontProviderMC implements FontProvider {
public ResourceLocation getTexture(char chr) {
return locationFontTexture;
}
@Override
public float getYScaleMultiplier() {
return 1;
}
}
@@ -90,4 +90,9 @@ public final class FontProviderUnicode implements FontProvider {
final int uniPage = chr / 256;
return getUnicodePageLocation(uniPage);
}
@Override
public float getYScaleMultiplier() {
return 1;
}
}
@@ -25,7 +25,6 @@ public class FontStrategist {
@Getter
private static final Font[] availableFonts;
public static final Logger LOGGER = LogManager.getLogger("Angelica");
public static boolean customFontInUse;
static {
// get available fonts without duplicates (250 copies of dialog.plain need not apply)
@@ -68,21 +67,6 @@ public class FontStrategist {
List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks();
defaultResourcePacks.add(fontResourcePack);
Minecraft.getMinecraft().refreshResources();
// determine if a custom font is in use based on config values
boolean primaryFontFound = false;
boolean fallbackFontFound = false;
for (Font availableFont : availableFonts) {
if (Objects.equals(FontConfig.customFontNamePrimary, availableFont.getFontName())) {
primaryFontFound = true;
break;
}
if (Objects.equals(FontConfig.customFontNameFallback, availableFont.getFontName())) {
fallbackFontFound = true;
break;
}
}
customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound));
}
/**
@@ -112,20 +96,14 @@ public class FontStrategist {
public static void reloadCustomFontProviders() {
FontProviderCustom.getPrimary().setFont(null);
FontProviderCustom.getFallback().setFont(null);
boolean primaryFontFound = false;
boolean fallbackFontFound = false;
for (int i = 0; i < availableFonts.length; i++) {
if (Objects.equals(FontConfig.customFontNamePrimary, availableFonts[i].getFontName())) {
FontProviderCustom.getPrimary().reloadFont(i);
primaryFontFound = true;
}
if (Objects.equals(FontConfig.customFontNameFallback, availableFonts[i].getFontName())) {
FontProviderCustom.getFallback().reloadFont(i);
fallbackFontFound = true;
}
if (primaryFontFound && fallbackFontFound) { break; }
}
customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound));
}
public static boolean isSplashFontRendererActive(FontRenderer fontRenderer) {
@@ -56,6 +56,7 @@ public class FontConfigScreen extends GuiScreen {
SliderClone.Option optGlyphSpacing = new SliderClone.Option(-2f, 2f, 0.05f);
SliderClone.Option optFontAAMode = new SliderClone.Option(0, 2, 1);
SliderClone.Option optFontAAStrength = new SliderClone.Option(1, 24, 1);
SliderClone.Option optCustomFontScale = new SliderClone.Option(0.1f, 3, 0.05f);
public FontConfigScreen(GuiScreen parent) {
this.title = I18n.format("options.angelica.fontconfig.title");
@@ -214,6 +215,16 @@ public class FontConfigScreen extends GuiScreen {
.formatString("%.0f")
.build()
);
sliders.add(new SliderClone.SliderCloneBuilder()
.width(sliderWidth)
.height(sliderHeight)
.option(optCustomFontScale)
.initialValue(FontConfig.customFontScale)
.setter(value -> FontConfig.customFontScale = value)
.langKey("options.angelica.fontconfig.custom_font_scale")
.formatString("x%3.2f")
.build()
);
final int halfWidth = this.width / 2;
final int sliderSpacing = 4;
@@ -279,7 +290,6 @@ public class FontConfigScreen extends GuiScreen {
currentFallbackFontName = null;
selectedPrimaryFontListPos = -1;
selectedFallbackFontListPos = -1;
FontStrategist.customFontInUse = false;
super.buttonList.clear();
this.initButtons();
}
@@ -47,6 +47,11 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableVBOClouds;
@Config.Comment("Uses cached attributes for VBO rendering, resulting in less CPU overhead. Disable if you notice any graphical issues.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableVAO;
@Config.Comment("Enable NotFine features")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
@@ -194,12 +199,13 @@ public class AngelicaConfig {
"Add a block class here if you see flickering (z-fighting) with fixBlockCrack enabled"
})
@Config.DefaultStringList({
"gregtech.common.blocks.BlockOres",
"gregtech.common.blocks.GTBlockOre",
"shukaro.artifice.block.world.BlockOre",
"bartworks.system.material.BWMetaGeneratedOres",
"gtPlusPlus.core.block.base.BlockBaseOre",
})
public static String[] blockCrackFixRenderPassWhitelist_;
public static String[] blockCrackFixRenderPassWhitelist__;
@Config.Comment("Register HardcodedCustomUniforms in Iris Shaders. May help with compatibility in certain shader packs")
@Config.DefaultBoolean(false)
@@ -65,4 +65,9 @@ public class FontConfig {
@Config.DefaultInt(7)
@Config.RangeInt(min = 1, max = 24)
public static int fontAAStrength;
@Config.Comment("Custom font scale multiplier, for bugfixes.")
@Config.DefaultFloat(1.5F)
@Config.RangeFloat(min = 0.1F, max = 3F)
public static float customFontScale;
}
@@ -30,7 +30,8 @@ public final class CommandBufferBuilder {
public static void buildOptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
final CompiledLineBuffer compiledLineBuffer,
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> 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<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer);
final List<DrawRangeWithBuffer> 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<AccumulatedDraw> accumulatedDraws,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
CommandBuffer finalBuffer) {
@@ -96,7 +97,7 @@ public final class CommandBufferBuilder {
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer);
final List<DrawRangeWithBuffer> 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<DrawRangeWithBuffer> collectDrawRanges(
static List<DrawRangeWithBuffer> collectDrawRanges(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer) {
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
final List<DrawRangeWithBuffer> 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));
}
}
}
}
@@ -15,7 +15,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
* </ul>
*/
@Desugar
record CompiledFormatBuffer(
public record CompiledFormatBuffer(
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawRange[] mergedRanges,
@@ -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.
* <p>
* 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;
}
}
@@ -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;
@@ -101,7 +102,7 @@ public class DisplayListManager {
return currentRenderingList != -1;
}
static boolean isIdentity(Matrix4f m) {
public static boolean isIdentity(Matrix4f m) {
return (m.properties() & Matrix4f.PROPERTY_IDENTITY) != 0;
}
@@ -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<AccumulatedDraw> accumulatedDraws = null; // Accumulates quad draws for batching
private static List<AccumulatedLineDraw> accumulatedLineDraws = null; // Accumulates line draws
private static List<AccumulatedLineDraw> accumulatedLineDraws = null; // Accumulates immediate mode line draws
private static List<AccumulatedPrimitiveDraw> 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<AccumulatedDraw> draws,
List<AccumulatedLineDraw> lineDraws,
List<AccumulatedPrimitiveDraw> primitiveDraws,
Matrix4fStack transform,
boolean wasTessellatorCompiling,
ImmediateModeRecorder immediateRecorder
@@ -181,10 +184,13 @@ public class DisplayListManager {
public static void recordDisable(int cap) { if (currentRecorder != null) currentRecorder.recordDisable(cap); }
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); }
@@ -205,7 +211,6 @@ public class DisplayListManager {
public static void recordOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { if (currentRecorder != null) currentRecorder.recordOrtho(left, right, bottom, top, zNear, zFar); }
public static void recordFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { if (currentRecorder != null) currentRecorder.recordFrustum(left, right, bottom, top, zNear, zFar); }
public static void recordViewport(int x, int y, int width, int height) { if (currentRecorder != null) currentRecorder.recordViewport(x, y, width, height); }
public static void recordNormal(float nx, float ny, float nz) { if (currentRecorder != null) currentRecorder.recordNormal(nx, ny, nz); }
public static void recordPointSize(float size) { if (currentRecorder != null) currentRecorder.recordPointSize(size); }
public static void recordLineWidth(float width) { if (currentRecorder != null) currentRecorder.recordLineWidth(width); }
public static void recordLineStipple(int factor, int pattern) { if (currentRecorder != null) currentRecorder.recordLineStipple(factor, pattern); }
@@ -219,6 +224,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); }
@@ -412,7 +418,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);
}
@@ -423,23 +429,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;
@@ -471,23 +490,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<CapturingTessellator.Flags, CompiledFormatBuffer> 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<CapturingTessellator.Flags, CompiledPrimitiveBuffers> 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
@@ -513,6 +536,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;
@@ -525,6 +549,7 @@ public class DisplayListManager {
recordingThread = null;
accumulatedDraws = null;
accumulatedLineDraws = null;
accumulatedPrimitiveDraws = null;
relativeTransform = null;
immediateModeRecorder = null;
glListId = -1;
@@ -651,22 +676,74 @@ public class DisplayListManager {
*/
private static VertexBuffer[] extractOwnedVbos(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer) {
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
final List<VertexBuffer> 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<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compilePrimitiveBuffers(
List<AccumulatedPrimitiveDraw> primitiveDraws) {
if (primitiveDraws == null || primitiveDraws.isEmpty()) {
return Collections.emptyMap();
}
// Group draws by vertex format
final Map<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> 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<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiled = new HashMap<>();
@SuppressWarnings("unchecked")
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer>[] entries =
formatBuffers.entrySet().toArray(new Map.Entry[0]);
for (int i = 0; i < entries.length; i++) {
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> 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.
@@ -683,29 +760,15 @@ public class DisplayListManager {
List<DisplayListCommand> currentCommands,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
int glListId) {
final List<DisplayListCommand> optimized = new ArrayList<>();
final TransformOptimizer transformOpt = new TransformOptimizer(glListId);
// Collect all merged draw ranges (quads + lines) sorted by command index
final List<DrawRangeWithBuffer> 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<DrawRangeWithBuffer> allRanges = CommandBufferBuilder.collectDrawRanges(
compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Process command stream with interleaved draws
final OptimizationContextImpl ctx = new OptimizationContextImpl(transformOpt, optimized);
@@ -754,19 +817,19 @@ public class DisplayListManager {
static OptimizedListResult buildOptimizedDisplayList(
List<DisplayListCommand> currentCommands,
List<AccumulatedDraw> accumulatedDraws,
List<AccumulatedLineDraw> accumulatedLineDraws,
List<AccumulatedPrimitiveDraw> accumulatedPrimitiveDraws,
int glListId) {
// Compile quad VBOs
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws);
// Compile line VBO
final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws);
// Compile tessellator primitive VBOs (lines, triangles) - grouped by format
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> 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);
}
@@ -816,7 +879,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;
@@ -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() {
@@ -1000,48 +1001,43 @@ public class GLStateManager {
}
public static void glNormal3b(byte nx, byte ny, byte nz) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordNormal(nx, ny, nz);
// Also update immediate mode recorder for glBegin/glEnd capture
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(b2f(nx), b2f(ny), b2f(nz));
}
} else {
GL11.glNormal3b(nx, ny, nz);
return;
}
GL11.glNormal3b(nx, ny, nz);
}
public static void glNormal3d(double nx, double ny, double nz) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordNormal((float)nx, (float)ny, (float)nz);
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
} else {
GL11.glNormal3d(nx, ny, nz);
return;
}
GL11.glNormal3d(nx, ny, nz);
}
public static void glNormal3f(float nx, float ny, float nz) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordNormal(nx, ny, nz);
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(nx, ny, nz);
}
} else {
GL11.glNormal3f(nx, ny, nz);
return;
}
GL11.glNormal3f(nx, ny, nz);
}
public static void glNormal3i(int nx, int ny, int nz) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordNormal(nx, ny, nz);
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
} else {
GL11.glNormal3i(nx, ny, nz);
return;
}
GL11.glNormal3i(nx, ny, nz);
}
public static void glDepthFunc(int func) {
@@ -1245,9 +1241,10 @@ public class GLStateManager {
public static void glClearDepth(double depth) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glClearDepth in display lists not yet implemented - if you see this, please report!");
DisplayListManager.recordClearDepth(depth);
} else {
GL11.glClearDepth(depth);
}
GL11.glClearDepth(depth);
}
// ALPHA
@@ -3190,7 +3187,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) {
@@ -3202,8 +3200,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);
}
@@ -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.
* <p>
* Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color),
* this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size.
* <p>
* 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<ModelLine> allLines = new ArrayList<>();
final List<ModelTriangle> allTriangles = new ArrayList<>();
// Ranges for lines
final List<DrawRange> lineMergedRanges = new ArrayList<>();
final List<DrawRange> 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<DrawRange> triangleMergedRanges = new ArrayList<>();
final List<DrawRange> 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<ModelPrimitiveView> 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));
}
}
}
}
@@ -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.
* <p>
* 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<ModelPrimitiveView> primitives;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex;
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> 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<ModelPrimitiveView> deepCopyPrimitives(List<ModelPrimitiveView> source) {
final int size = source.size();
final List<ModelPrimitiveView> 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);
}
}
@@ -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) {
@@ -304,14 +317,6 @@ public final class CommandBuffer {
writeFloat(units);
}
public void writeNormal(float x, float y, float z) {
ensureCapacity(16);
writeInt(GLCommand.NORMAL);
writeFloat(x);
writeFloat(y);
writeFloat(z);
}
public void writeColor(float r, float g, float b, float a) {
ensureCapacity(20);
writeInt(GLCommand.COLOR);
@@ -330,6 +335,21 @@ public final class CommandBuffer {
writeFloat(a);
}
public void writeClearDepth(double depth) {
ensureCapacity(12);
writeInt(GLCommand.CLEAR_DEPTH);
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) {
@@ -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 -> {
@@ -246,13 +256,6 @@ public final class CommandBufferExecutor {
ptr += 8;
GLStateManager.glPolygonOffset(factor, units);
}
case GLCommand.NORMAL -> {
final float x = memGetFloat(ptr);
final float y = memGetFloat(ptr + 4);
final float z = memGetFloat(ptr + 8);
ptr += 12;
GLStateManager.glNormal3f(x, y, z);
}
case GLCommand.COLOR -> {
final float r = memGetFloat(ptr);
final float g = memGetFloat(ptr + 4);
@@ -269,6 +272,19 @@ public final class CommandBufferExecutor {
ptr += 16;
GLStateManager.glClearColor(r, g, b, a);
}
case GLCommand.CLEAR_DEPTH -> {
final double depth = memGetDouble(ptr);
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 -> {
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -154,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());
@@ -162,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());
@@ -179,10 +182,15 @@ public final class CommandBufferProcessor {
case GLCommand.POINT_SIZE -> out.writePointSize(raw.readFloat());
case GLCommand.LINE_WIDTH -> out.writeLineWidth(raw.readFloat());
case GLCommand.POLYGON_OFFSET -> out.writePolygonOffset(raw.readFloat(), raw.readFloat());
case GLCommand.NORMAL -> out.writeNormal(raw.readFloat(), raw.readFloat(), raw.readFloat());
case GLCommand.COLOR -> out.writeColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat());
case GLCommand.CLEAR_COLOR -> out.writeClearColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat());
// 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());
@@ -255,17 +263,6 @@ public final class CommandBufferProcessor {
}
}
/**
* Check if a matrix is identity (within epsilon).
*/
public static boolean isIdentity(Matrix4f m) {
final float eps = 1e-6f;
return Math.abs(m.m00() - 1) < eps && Math.abs(m.m01()) < eps && Math.abs(m.m02()) < eps && Math.abs(m.m03()) < eps
&& Math.abs(m.m10()) < eps && Math.abs(m.m11() - 1) < eps && Math.abs(m.m12()) < eps && Math.abs(m.m13()) < eps
&& Math.abs(m.m20()) < eps && Math.abs(m.m21()) < eps && Math.abs(m.m22() - 1) < eps && Math.abs(m.m23()) < eps
&& Math.abs(m.m30()) < eps && Math.abs(m.m31()) < eps && Math.abs(m.m32()) < eps && Math.abs(m.m33() - 1) < eps;
}
/**
* Lightweight transform optimizer for buffer-to-buffer processing.
* Tracks accumulated MODELVIEW transform and emits MultMatrix commands when needed.
@@ -316,7 +313,7 @@ public final class CommandBufferProcessor {
}
public boolean isIdentity() {
return CommandBufferProcessor.isIdentity(accumulated);
return DisplayListManager.isIdentity(accumulated);
}
public void markAbsoluteMatrix() {
@@ -340,7 +337,7 @@ public final class CommandBufferProcessor {
return;
}
if (CommandBufferProcessor.isIdentity(lastEmitted)) {
if (DisplayListManager.isIdentity(lastEmitted)) {
out.writeMultMatrix(GL11.GL_MODELVIEW, target);
} else {
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
@@ -51,6 +51,16 @@ public class CommandRecorder {
commandCount++;
}
public void recordClearDepth(double depth) {
buffer.writeClearDepth(depth);
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++;
@@ -71,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++;
@@ -171,11 +186,6 @@ public class CommandRecorder {
commandCount++;
}
public void recordNormal(float nx, float ny, float nz) {
buffer.writeNormal(nx, ny, nz);
commandCount++;
}
public void recordPointSize(float size) {
buffer.writePointSize(size);
commandCount++;
@@ -241,6 +251,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++;
@@ -2,12 +2,12 @@ package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
@@ -96,8 +96,8 @@ public final class CompiledDisplayList {
* Get counts of each command type in the buffer.
* Used for testing to verify optimization results.
*/
public Map<Integer, Integer> getCommandCounts() {
Map<Integer, Integer> counts = new HashMap<>();
public Int2IntMap getCommandCounts() {
Int2IntMap counts = new Int2IntOpenHashMap();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return counts;
}
@@ -105,7 +105,7 @@ public final class CompiledDisplayList {
long end = ptr + commandBuffer.limit();
while (ptr < end) {
int cmd = memGetInt(ptr);
counts.merge(cmd, 1, Integer::sum);
counts.mergeInt(cmd, 1, Integer::sum);
ptr += getCommandSize(cmd, ptr);
}
return counts;
@@ -115,8 +115,8 @@ public final class CompiledDisplayList {
* Get the sequence of command opcodes in order.
* Used for testing to verify command ordering.
*/
public List<Integer> getCommandOpcodes() {
List<Integer> opcodes = new ArrayList<>();
public IntList getCommandOpcodes() {
IntList opcodes = new IntArrayList();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return opcodes;
}
@@ -141,27 +141,29 @@ 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)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.NORMAL, GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16;
// 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;
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
@@ -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,6 +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]
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]
@@ -72,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
@@ -113,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";
@@ -130,9 +136,9 @@ public final class GLCommand {
case POINT_SIZE -> "POINT_SIZE";
case LINE_WIDTH -> "LINE_WIDTH";
case POLYGON_OFFSET -> "POLYGON_OFFSET";
case NORMAL -> "NORMAL";
case COLOR -> "COLOR";
case CLEAR_COLOR -> "CLEAR_COLOR";
case BLEND_COLOR -> "BLEND_COLOR";
case ALPHA_FUNC -> "ALPHA_FUNC";
case FOGF -> "FOGF";
case LIGHTF -> "LIGHTF";
@@ -146,6 +152,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";
@@ -4,6 +4,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.CustomFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.SharedDepthFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexArrayBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.compat.ModStatus;
@@ -178,10 +179,7 @@ public class HUDCaching {
if (quadWidth != width || quadHeight != height) {
quadWidth = width;
quadHeight = height;
if (quadVAO != null) {
quadVAO.close();
}
quadVAO = rebuildVAO(width, height);
rebuildVAO(width, height);
}
GLStateManager.disableDepthTest();
GLStateManager.enableTexture();
@@ -190,7 +188,7 @@ public class HUDCaching {
}
private static VertexBuffer rebuildVAO(float width, float height) {
private static void rebuildVAO(float width, float height) {
final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet();
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0, height, 0.0, 0, 0);
@@ -198,7 +196,7 @@ public class HUDCaching {
tessellator.addVertexWithUV(width, 0, 0.0, 1, 1);
tessellator.addVertexWithUV(0, 0, 0.0, 0, 1);
tessellator.draw();
return TessellatorManager.stopCapturingToVAO(DefaultVertexFormat.POSITION_TEXTURE);
quadVAO = TessellatorManager.stopCapturingToVAO(quadVAO, DefaultVertexFormat.POSITION_TEXTURE);
}
public static void disableHoloInventory() {
@@ -244,6 +244,7 @@ public final class AngelicaRedirector {
"org.lwjgl",
"com.gtnewhorizons.angelica.glsm.",
"com.gtnewhorizons.angelica.transform",
"com.gtnewhorizon.gtnhlib.asm.",
"me.eigenraven.lwjgl3ify"
};
}
@@ -104,6 +104,7 @@ public class SodiumBlockTransform {
"org.lwjgl",
"com.gtnewhorizons.angelica.glsm.",
"com.gtnewhorizons.angelica.transform",
"com.gtnewhorizon.gtnhlib.asm.",
"me.eigenraven.lwjgl3ify"
};
}
@@ -5,6 +5,7 @@ import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -111,6 +112,9 @@ public class ClientProxy extends CommonProxy {
FMLCommonHandler.instance().bus().register(Iris.INSTANCE);
MinecraftForge.EVENT_BUS.register(Iris.INSTANCE);
}
if (!AngelicaConfig.enableVAO) {
VAOManager.disableVao();
}
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
@@ -218,12 +218,11 @@ public class CloudRenderer implements IResourceManagerReloadListener {
}
private void build() {
TessellatorManager.startCapturing();
CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get();
CapturingTessellator tess = TessellatorManager.startCapturingAndGet();
vertices(tess);
this.vbo = TessellatorManager.stopCapturingToVBO(FORMAT);
this.vbo = TessellatorManager.stopCapturingToVAO(FORMAT);
}
private int fullCoord(double coord, int scale) { // Corrects misalignment of UV offset when on negative coords.
@@ -27,6 +27,7 @@ package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -126,7 +127,7 @@ public class ItemRenderListManager {
private int expiry;
public CachedVBO() {
this.vertexBuffer = new VertexBuffer(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_QUADS);
this.vertexBuffer = VAOManager.createVAO(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_QUADS);
}
private void render(int elapsedTicks) {
@@ -66,8 +66,7 @@ public class BlockRenderer {
final LightMode mode = LightMode.SMOOTH; // TODO: this.getLightingMode(block); is what was previously used. The flat pipeline is busted and was only an optimization for very few blocks.
final LightPipeline lighter = this.lighters.getLighter(mode);
TessellatorManager.startCapturing();
final CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get();
final CapturingTessellator tess = TessellatorManager.startCapturingAndGet();
tess.startDrawingQuads();
// Use setTranslation rather than setOffset so that the float data written to the internal buffer
// is done in subchunk-relative coordinates
@@ -101,8 +100,7 @@ public class BlockRenderer {
final int emitted = block.getLightValue(world, pos.x, pos.y, pos.z);
try {
TessellatorManager.startCapturing();
final CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get();
final CapturingTessellator tess = TessellatorManager.startCapturingAndGet();
tess.startDrawingQuads();
// Use setTranslation rather than setOffset so that the float data written to the internal buffer
// is done in subchunk-relative coordinates
@@ -52,17 +52,13 @@ public class HorizonRenderer {
}
private void rebuildBuffer() {
if (this.vertexBuffer != null) {
this.vertexBuffer.close();
}
TessellatorManager.startCapturing();
final CapturingTessellator tessellator = (CapturingTessellator) TessellatorManager.get();
final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet();
// Build the horizon quads into a buffer
tessellator.startDrawingQuads(); //(GL11.GL_QUADS, DefaultVertexFormat.POSITION);
buildHorizon(currentRenderDistance * 16, tessellator);
this.vertexBuffer = TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION);
this.vertexBuffer = TessellatorManager.stopCapturingToVAO(vertexBuffer, DefaultVertexFormat.POSITION);
}
private void buildQuad(Tessellator consumer, double x1, double z1, double x2, double z2) {
@@ -155,12 +151,9 @@ public class HorizonRenderer {
rebuildBuffer();
}
vertexBuffer.bind();
GL11.glVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
vertexBuffer.setupState();
vertexBuffer.draw(floatBuffer);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
vertexBuffer.unbind();
vertexBuffer.cleanupState();
}
public void destroy() {
@@ -11,7 +11,7 @@ import org.taumc.glsl.Util;
*/
class AttributeTransformer {
public static void transform(GLSLParser.Translation_unitContext translationUnit, AttributeParameters parameters, String profile, int version) {
boolean isCore = (profile.equals("core") || version > 140);
boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility"));
if (isCore) {
if (parameters.type == PatchShaderType.VERTEX) {
throw new IllegalStateException("Vertex shaders must be in the compatibility profile to run properly!");
@@ -157,6 +157,7 @@ options.angelica.fontconfig.font_aa_strength=Font AA Strength: %s
options.angelica.fontconfig.aamode.aa_none=Font AA: OFF
options.angelica.fontconfig.aamode.aa_4x=Font AA: 4x MSAA
options.angelica.fontconfig.aamode.aa_16x=Font AA: 16x MSAA
options.angelica.fontconfig.custom_font_scale=Custom Font Scale: %s
options.angelica.fontconfig.font_quality.tooltip=The quality at which custom fonts are rendered, making them less pixelated at the expense of some performance and memory.
options.angelica.fontconfig.shadow_offset.tooltip=The distance at which the fonts' shadows are drawn. Also affects the way §lbold§r text is drawn.
options.angelica.fontconfig.shadow_copies.tooltip=The number of shadows to be drawn behind text, all offset so as to provide a fake 3D effect.
@@ -167,6 +168,7 @@ options.angelica.fontconfig.whitespace_scale.tooltip=The scaling factor of blank
options.angelica.fontconfig.glyph_spacing.tooltip=The spacing between each individual glyph.
options.angelica.fontconfig.font_aa_strength.tooltip=The spacing of samples used in font antialiasing. High values may cause fonts to look blurry, low values may cause aliasing. See what works best with your settings.
options.angelica.fontconfig.aamode.tooltip=The font antialiasing mode. Can significantly improve the appearance and readability of text that's being scaled or viewed at oblique angles, at the expense of some performance.
options.angelica.fontconfig.custom_font_scale.tooltip=A multiplier that affects the scale of custom fonts. Adjust this if text in your font of choice looks under-/over-sized relative to text that does not use custom fonts.
options.angelica.droppedItemLimit=Dropped Item Render Limit
options.angelica.droppedItemLimit.tooltip=The maximum number of dropped items that will be rendered. Lower values can improve performance.
options.angelica.mobSpawnerRenderDistance=Mob spawner render distance
@@ -239,8 +239,8 @@ public class MixinRenderBlocks_CrackFix {
}
@Unique
private static Class<?>[] angelica$getCrackFixRenderPassWhitelist() {
if (angelica$currentCrackFixWhitelistArr != AngelicaConfig.blockCrackFixRenderPassWhitelist_) {
angelica$currentCrackFixWhitelistArr = AngelicaConfig.blockCrackFixRenderPassWhitelist_;
if (angelica$currentCrackFixWhitelistArr != AngelicaConfig.blockCrackFixRenderPassWhitelist__) {
angelica$currentCrackFixWhitelistArr = AngelicaConfig.blockCrackFixRenderPassWhitelist__;
angelica$currentCrackFixWhitelistClasses = Arrays.stream(angelica$currentCrackFixWhitelistArr).map((name) -> {
try {
return Class.forName(name);
@@ -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<ModelLine> createLines(int count) {
List<ModelLine> 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<ModelTriangle> createTriangles(int count) {
List<ModelTriangle> 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<ModelPrimitiveView> createMixedPrimitives(int lineCount, int triangleCount) {
List<ModelPrimitiveView> 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<ModelPrimitiveView> 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<ModelPrimitiveView> 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<ModelPrimitiveView> 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<ModelPrimitiveView> primitives = createMixedPrimitives(lineCount, triangleCount);
return createPrimitiveDraw(primitives, identity(), positionOnly(), commandIndex);
}
/**
* Create an AccumulatedPrimitiveDraw with specified transform.
*/
public static AccumulatedPrimitiveDraw createPrimitiveDrawWithTransform(
List<ModelPrimitiveView> primitives, Matrix4f transform, int commandIndex) {
return createPrimitiveDraw(primitives, transform, positionOnly(), commandIndex);
}
}
@@ -58,8 +58,8 @@ class GLSM_DisplayList_Batching_Test {
private Set<VertexBuffer> getUniqueVBOs(DisplayListCommand[] commands) {
Set<VertexBuffer> vbos = new HashSet<>();
for (DisplayListCommand cmd : commands) {
if (cmd instanceof DrawRangeCmd) {
vbos.add(((DrawRangeCmd) cmd).sharedVbo());
if (cmd instanceof DrawRangeCmd rangeCmd) {
vbos.add(rangeCmd.sharedVbo());
}
}
return vbos;
@@ -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.
*
* <p>Tests cover:
* <ul>
* <li>AccumulatedPrimitiveDraw deep copying behavior</li>
* <li>TessellatorPrimitiveBuffer accumulation and range merging</li>
* <li>Integration with buildOptimizedDisplayList for primitive VBOs</li>
* <li>Mixed quad + primitive display lists</li>
* </ul>
*/
@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<VertexBuffer> getUniqueVBOs(DisplayListCommand[] commands) {
Set<VertexBuffer> 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<ModelPrimitiveView> 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<ModelPrimitiveView> 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<ModelPrimitiveView> 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<ModelPrimitiveView> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
primitiveDraws.add(createLinesDraw(5, 0));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
primitiveDraws.add(createTrianglesDraw(3, 0));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
primitiveDraws.add(createLinesDraw(3, 0));
primitiveDraws.add(createTrianglesDraw(2, 1));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
quadDraws.add(createSimpleDraw(0)); // 1 quad
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
primitiveDraws.add(createLinesDraw(2, 1)); // 2 lines
List<DisplayListCommand> 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<VertexBuffer> uniqueVBOs = getUniqueVBOs(optimized);
assertEquals(2, uniqueVBOs.size(), "Commands should reference 2 unique VBOs");
}
@Test
void testBuildOptimizedDisplayListWithQuadsLinesAndTriangles() {
// Setup: All three types
List<AccumulatedDraw> quadDraws = new ArrayList<>();
quadDraws.add(createSimpleDraw(0));
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
primitiveDraws.add(createLinesDraw(2, 1));
primitiveDraws.add(createTrianglesDraw(2, 2));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
List<AccumulatedPrimitiveDraw> 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<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
List<ModelPrimitiveView> lines1 = new ArrayList<>();
lines1.add(createSimpleLine());
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0));
List<ModelPrimitiveView> lines2 = new ArrayList<>();
lines2.add(createSimpleLine());
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
quadDraws.add(createSimpleDraw(0));
List<DisplayListCommand> 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<AccumulatedDraw> quadDraws = new ArrayList<>();
quadDraws.add(createSimpleDraw(0));
List<AccumulatedPrimitiveDraw> primitiveDraws = new ArrayList<>();
List<DisplayListCommand> 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");
}
}
@@ -3,6 +3,8 @@ package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.GLCommand;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.IntList;
import org.joml.Matrix4f;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -11,8 +13,6 @@ import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@@ -68,7 +68,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
int individualTransformCount = counts.getOrDefault(GLCommand.TRANSLATE, 0)
+ counts.getOrDefault(GLCommand.ROTATE, 0)
@@ -122,7 +122,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
// Verify optimization: should have Push, Pop, and collapsed MultMatrix commands
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
int pushCount = counts.getOrDefault(GLCommand.PUSH_MATRIX, 0);
int popCount = counts.getOrDefault(GLCommand.POP_MATRIX, 0);
@@ -217,7 +217,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
// Verify optimization: MultMatrix should be emitted before CallList
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
List<Integer> opcodes = compiled.getCommandOpcodes();
IntList opcodes = compiled.getCommandOpcodes();
// Find positions of MultMatrix and CallList
int multMatrixIndex = opcodes.indexOf(GLCommand.MULT_MATRIX);
@@ -268,7 +268,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
@@ -356,7 +356,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
// Verify optimization: should collapse to 1 MultMatrix
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
@@ -416,7 +416,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
List<Integer> opcodes = compiled.getCommandOpcodes();
IntList opcodes = compiled.getCommandOpcodes();
// Find indices of key commands
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
@@ -467,7 +467,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
List<Integer> opcodes = compiled.getCommandOpcodes();
IntList opcodes = compiled.getCommandOpcodes();
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX);
@@ -507,7 +507,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
int loadMatrixCount = counts.getOrDefault(GLCommand.LOAD_MATRIX, 0);
assertEquals(1, loadMatrixCount,
@@ -155,4 +155,159 @@ class GLSM_DisplayList_UnitTest {
GLStateManager.glDisable(GL11.GL_LIGHTING);
GLStateManager.glDeleteLists(list, 1);
}
// ==================== ClearDepth Tests ====================
@Test
void testClearDepthInDisplayList() {
// Get initial clear depth
double initialDepth = GL11.glGetDouble(GL11.GL_DEPTH_CLEAR_VALUE);
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glClearDepth(0.5);
GLStateManager.glEndList();
// After compile, depth should be unchanged
assertEquals(initialDepth, GL11.glGetDouble(GL11.GL_DEPTH_CLEAR_VALUE), 0.0001, "ClearDepth should be unchanged after GL_COMPILE");
// Call the display list
GLStateManager.glCallList(list);
// Now depth should be 0.5
assertEquals(0.5, GL11.glGetDouble(GL11.GL_DEPTH_CLEAR_VALUE), 0.0001, "ClearDepth should be 0.5 after calling display list");
// Cleanup
GLStateManager.glClearDepth(1.0); // Reset to default
GLStateManager.glDeleteLists(list, 1);
}
@Test
void testClearDepthCompileAndExecute() {
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glClearDepth(0.25);
GLStateManager.glEndList();
// After compile and execute, depth should be changed
assertEquals(0.25, GL11.glGetDouble(GL11.GL_DEPTH_CLEAR_VALUE), 0.0001, "ClearDepth should be 0.25 after GL_COMPILE_AND_EXECUTE");
// Cleanup
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);
}
}
@@ -9,10 +9,11 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@@ -72,7 +73,7 @@ class RecordingDataStructuresTest {
assertNotNull(compiled.getCommandBuffer(), "Command buffer should not be null");
// Get command counts to verify structure
Map<Integer, Integer> counts = compiled.getCommandCounts();
Int2IntMap counts = compiled.getCommandCounts();
// Should have PushMatrix and PopMatrix
assertEquals(1, counts.getOrDefault(GLCommand.PUSH_MATRIX, 0), "Should have 1 PushMatrix");
@@ -24,7 +24,7 @@ public final class GLBit {
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (GLBit) obj;
GLBit that = (GLBit) obj;
return Objects.equals(this.name, that.name) && this.glEnum == that.glEnum && this.initial == that.initial;
}