GLSM Extraction (#1527)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-03-19 22:53:47 -07:00
1 parent b179340a0f
commit 37717bd4db
189 files changed
+2198 -1365

No files matched your search

@@ -1,125 +0,0 @@
package com.gtnewhorizons.angelica;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.states.VertexAttribState;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.PixelFormat;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL;
public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ExtensionContext.Store.CloseableResource {
private static boolean started = false;
private static DisplayMode displayMode;
public static String glVendor;
public static String glRenderer;
public static String glVersion;
private static final int EXPECTED_MODELVIEW_STACK_DEPTH = 1;
private static final int EXPECTED_PROJECTION_STACK_DEPTH = 1;
@Override
public void beforeAll(ExtensionContext context) throws LWJGLException {
if (!started) {
started = true;
displayMode = new DisplayMode(800, 600);
Display.setDisplayModeAndFullscreen(displayMode);
Display.setResizable(false);
Display.setFullscreen(false);
final PixelFormat format = new PixelFormat().withDepthBits(24).withStencilBits(8);
Display.create(format);
setMainThread(Thread.currentThread());
GLStateManager.preInit();
VertexAttribState.init(0);
GLStateManager.setRunningSplash(false);
GLStateManager.markSplashComplete();
GLStateManager.BYPASS_CACHE = false;
RenderSystem.initRenderer();
context.getRoot().getStore(GLOBAL).put("AngelicaExtension", this);
glVendor = GL11.glGetString(GL11.GL_VENDOR);
glRenderer = GL11.glGetString(GL11.GL_RENDERER);
glVersion = GL11.glGetString(GL11.GL_VERSION);
System.out.println("OpenGL Vendor: " + glVendor);
System.out.println("OpenGL Renderer: " + glRenderer);
System.out.println("OpenGL Version: " + glVersion);
}
}
private static void setMainThread(Thread thread) {
try {
// Use Unsafe to set final static field - works on all Java versions
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
final Unsafe unsafe = (Unsafe) unsafeField.get(null);
final Field mainThreadField = GLStateManager.class.getDeclaredField("MainThread");
final Object base = unsafe.staticFieldBase(mainThreadField);
final long offset = unsafe.staticFieldOffset(mainThreadField);
unsafe.putObject(base, offset, thread);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Failed to set MainThread for tests", e);
}
}
@Override
public void close() {
Display.destroy();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
GL11.glMatrixMode(GL11.GL_MODELVIEW);
while (GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH) > EXPECTED_MODELVIEW_STACK_DEPTH) {
GL11.glPopMatrix();
}
GL11.glLoadIdentity();
GL11.glMatrixMode(GL11.GL_PROJECTION);
while (GL11.glGetInteger(GL11.GL_PROJECTION_STACK_DEPTH) > EXPECTED_PROJECTION_STACK_DEPTH) {
GL11.glPopMatrix();
}
GL11.glLoadIdentity();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
final int error = GL11.glGetError();
assertEquals(GL11.GL_NO_ERROR, error,
() -> "GL Error: 0x" + Integer.toHexString(error));
final int modelviewDepth = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
final int projectionDepth = GL11.glGetInteger(GL11.GL_PROJECTION_STACK_DEPTH);
assertEquals(EXPECTED_MODELVIEW_STACK_DEPTH, modelviewDepth,
"MODELVIEW stack depth mismatch - unbalanced glPushMatrix/glPopMatrix");
assertEquals(EXPECTED_PROJECTION_STACK_DEPTH, projectionDepth,
"PROJECTION stack depth mismatch - unbalanced glPushMatrix/glPopMatrix");
final int matrixMode = GL11.glGetInteger(GL11.GL_MATRIX_MODE);
assertEquals(GL11.GL_MODELVIEW, matrixMode,
() -> "Matrix mode not reset to MODELVIEW, was: " + GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,4 +1,4 @@
package com.gtnewhorizons.angelica.glsm.ffp;
package com.gtnewhorizons.angelica.client.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import org.junit.jupiter.api.Test;
@@ -1,599 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CompatShaderTransformerTest {
@Test
void testModelViewMatrixReplacement() {
String src = """
#version 120
void main() {
vec4 pos = gl_ModelViewMatrix * gl_Vertex;
gl_Position = gl_ProjectionMatrix * pos;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("angelica_ModelViewMatrix"));
assertTrue(result.contains("angelica_ProjectionMatrix"));
assertFalse(result.contains("gl_ModelViewMatrix"));
assertFalse(result.contains("gl_ProjectionMatrix"));
assertTrue(result.contains("#version 330 core"));
}
@Test
void testNormalMatrixReplacement() {
String src = """
#version 120
void main() {
vec3 n = gl_NormalMatrix * gl_Normal;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("uniform mat3 angelica_NormalMatrix"));
assertFalse(result.contains("gl_NormalMatrix"));
}
@Test
void testModelViewProjectionMatrixExpression() {
String src = """
#version 120
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_ModelViewProjectionMatrix"));
assertTrue(result.contains("angelica_ProjectionMatrix"));
}
@Test
void testTextureFunctionRenames() {
String src = """
#version 120
uniform sampler2D tex;
void main() {
vec4 color = texture2D(tex, vec2(0.0));
}
""";
String result = CompatShaderTransformer.transform(src, false);
// texture2D → texture
assertFalse(result.contains("texture2D"));
assertTrue(result.contains("texture"));
}
@Test
void testFragColorHandling() {
String src = """
#version 120
void main() {
gl_FragColor = vec4(1.0);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertFalse(result.contains("gl_FragColor"));
// Should have layout-qualified output declaration
assertTrue(result.contains("angelica_FragData0"));
assertTrue(result.contains("layout"));
}
@Test
void testVersionUpgradeTo330() {
String src = """
#version 110
void main() {
gl_FragColor = vec4(1.0);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("#version 330 core"));
assertFalse(result.contains("#version 110"));
}
@Test
void testCompatibilityProfileStripped() {
String src = """
#version 330 compatibility
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("#version 330 core"));
assertFalse(result.contains("compatibility"));
}
@Test
void testPassthroughUnchangedShader() {
String src = """
#version 330 core
in vec3 position;
uniform mat4 mvp;
void main() {
gl_Position = mvp * vec4(position, 1.0);
}
""";
String result = CompatShaderTransformer.transform(src, false);
// Source should be returned as-is (passthrough)
assertEquals(src, result);
}
@Test
void testCombinedBuiltinsInSingleShader() {
String src = """
#version 120
uniform sampler2D tex;
void main() {
vec3 n = gl_NormalMatrix * gl_Normal;
vec4 pos = gl_ModelViewMatrix * gl_Vertex;
gl_Position = gl_ProjectionMatrix * pos;
vec4 color = texture2D(tex, vec2(0.0));
gl_FragColor = color;
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("angelica_ModelViewMatrix"));
assertTrue(result.contains("angelica_ProjectionMatrix"));
assertTrue(result.contains("angelica_NormalMatrix"));
assertFalse(result.contains("gl_ModelViewMatrix"));
assertFalse(result.contains("gl_ProjectionMatrix"));
assertFalse(result.contains("gl_NormalMatrix"));
assertFalse(result.contains("texture2D"));
assertFalse(result.contains("gl_FragColor"));
assertTrue(result.contains("#version 330 core"));
}
@Test
void testInverseMatrixReplacement() {
String src = """
#version 120
void main() {
vec4 pos = gl_ModelViewMatrixInverse * vec4(0.0, 0.0, 0.0, 1.0);
vec4 proj = gl_ProjectionMatrixInverse * vec4(0.0, 0.0, -1.0, 1.0);
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_ModelViewMatrixInverse"));
assertFalse(result.contains("gl_ProjectionMatrixInverse"));
}
@Test
void testTextureMatrixReplacement() {
String src = """
#version 120
void main() {
vec4 lmCoord = gl_TextureMatrix[1] * gl_MultiTexCoord1;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_TextureMatrix"));
}
@Test
void testFogStructAccess() {
String src = """
#version 120
void main() {
vec4 c = gl_Fog.color;
float d = gl_Fog.density;
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("angelica_Fog"), "gl_Fog should be renamed to angelica_Fog");
assertFalse(result.contains("gl_Fog"), "gl_Fog should not remain in output");
assertTrue(result.contains("angelica_FogParameters"), "Fog struct should be injected");
assertTrue(result.contains("uniform float angelica_FogDensity"), "Fog density uniform should be injected");
assertTrue(result.contains("uniform vec4 angelica_FogColor"), "Fog color uniform should be injected");
}
@Test
void testFogFragCoordVertex() {
String src = """
#version 120
void main() {
gl_FogFragCoord = length(gl_ModelViewMatrix * gl_Vertex);
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("out float angelica_FogFragCoord"), "Vertex shader should get 'out' declaration");
assertTrue(result.contains("angelica_FogFragCoord"), "gl_FogFragCoord should be renamed");
assertFalse(result.contains("gl_FogFragCoord"), "gl_FogFragCoord should not remain");
}
@Test
void testFogFragCoordFragment() {
String src = """
#version 120
void main() {
float f = gl_FogFragCoord;
gl_FragColor = vec4(f);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("in float angelica_FogFragCoord"), "Fragment shader should get 'in' declaration");
assertFalse(result.contains("gl_FogFragCoord"), "gl_FogFragCoord should not remain");
}
@Test
void testGlFrontColorVertex() {
String src = """
#version 120
void main() {
gl_FrontColor = vec4(1.0, 0.0, 0.0, 1.0);
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("vec4 angelica_FrontColor"), "gl_FrontColor should become angelica_FrontColor out varying");
assertFalse(result.contains("gl_FrontColor"), "gl_FrontColor should not remain");
}
@Test
void testShadow2DRename() {
String src = """
#version 120
uniform sampler2DShadow shadowMap;
void main() {
float s = shadow2D(shadowMap, vec3(0.0)).r;
gl_FragColor = vec4(s);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertFalse(result.contains("shadow2D("), "shadow2D should be renamed");
// shadow2D → texture with vec4 wrapping
assertTrue(result.contains("texture"), "shadow2D should be renamed to texture");
}
@Test
void testReservedWordTextureAsVariable() {
// Shader declares 'texture' as a sampler variable — this is valid in GLSL 120
// but 'texture' is a reserved word in GLSL 330+, causing parse failures without pre-rename
String src = """
#version 120
uniform sampler2D texture;
void main() {
gl_FragColor = texture2D(texture, vec2(0.5));
}
""";
// Should not throw — the pre-parse replaceTexture handles this
String result = CompatShaderTransformer.transform(src, true);
assertNotNull(result);
assertTrue(result.contains("#version 330 core"));
// The variable named 'texture' should have been renamed to gtexture (matching CommonTransformer convention)
assertTrue(result.contains("gtexture"), "Variable 'texture' should be renamed to gtexture");
}
@Test
void testCacheHit() {
String src = """
#version 120
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result1 = CompatShaderTransformer.transform(src, false);
String result2 = CompatShaderTransformer.transform(src, false);
assertSame(result1, result2, "Second call should return cached instance (same reference)");
}
@Test
void testAlphaTestDiscardInjected() {
String src = """
#version 120
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("uniform float angelica_currentAlphaTest"), "Alpha test uniform should be injected");
assertTrue(result.contains("angelica_FragData0 . a <= angelica_currentAlphaTest") || result.contains("angelica_FragData0.a <= angelica_currentAlphaTest"),
"Alpha test discard should be appended to main()");
}
@Test
void testTexelFetch3DTriggersTransformation() {
String src = """
#version 120
uniform sampler3D vol;
void main() {
vec4 v = texelFetch3D(vol, ivec3(0), 0);
gl_FragColor = v;
}
""";
String result = CompatShaderTransformer.transform(src, true);
// texelFetch3D should be renamed to texelFetch
assertFalse(result.contains("texelFetch3D"), "texelFetch3D should be renamed");
assertTrue(result.contains("texelFetch"), "texelFetch3D should become texelFetch");
}
@Test
void testVertexAttributeGlVertex() {
String src = """
#version 120
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_Vertex"), "gl_Vertex should be replaced");
assertTrue(result.contains("angelica_Vertex"), "should become angelica_Vertex");
assertTrue(result.contains("in vec4 angelica_Vertex"), "should have in declaration");
assertTrue(result.contains("location = 0"), "should use attribute location 0");
}
@Test
void testVertexAttributeGlColorInVertexShader() {
// gl_Color in a vertex shader is the per-vertex color attribute, not the fragment varying
String src = """
#version 120
varying vec4 v_Color;
void main() {
v_Color = gl_Color;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("angelica_Color"), "gl_Color → angelica_Color (vertex attribute)");
assertTrue(result.contains("in vec4 angelica_Color"), "should have in declaration");
assertTrue(result.contains("location = 1"), "should use attribute location 1");
assertFalse(result.contains("gl_Color"), "gl_Color should not remain");
}
@Test
void testVertexAttributeMultiTexCoord0() {
String src = """
#version 120
void main() {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_MultiTexCoord0"), "gl_MultiTexCoord0 should be replaced");
assertTrue(result.contains("angelica_MultiTexCoord0"), "should become angelica_MultiTexCoord0");
assertTrue(result.contains("in vec4 angelica_MultiTexCoord0"), "should have in declaration");
assertTrue(result.contains("location = 2"), "should use attribute location 2");
}
@Test
void testVertexAttributeMultiTexCoord1() {
String src = """
#version 120
void main() {
vec4 lm = gl_TextureMatrix[1] * gl_MultiTexCoord1;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_MultiTexCoord1"), "gl_MultiTexCoord1 should be replaced");
assertTrue(result.contains("angelica_MultiTexCoord1"), "should become angelica_MultiTexCoord1");
assertTrue(result.contains("location = 3"), "should use attribute location 3");
}
@Test
void testVertexAttributeGlNormal() {
String src = """
#version 120
void main() {
vec3 n = gl_NormalMatrix * gl_Normal;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_Normal"), "gl_Normal should be replaced");
assertTrue(result.contains("angelica_Normal"), "should become angelica_Normal");
assertTrue(result.contains("in vec3 angelica_Normal"), "should have in vec3 declaration");
assertTrue(result.contains("location = 4"), "should use attribute location 4");
}
@Test
void testTexCoordVaryingVertexShader() {
String src = """
#version 120
void main() {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_TexCoord"), "gl_TexCoord should be replaced");
assertTrue(result.contains("angelica_TexCoord0"), "should become angelica_TexCoord0");
assertTrue(result.contains("out vec4 angelica_TexCoord0"), "vertex shader should have 'out' declaration");
}
@Test
void testTexCoordVaryingFragmentShader() {
String src = """
#version 120
void main() {
vec2 uv = gl_TexCoord[0].xy;
gl_FragColor = vec4(uv, 0.0, 1.0);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertFalse(result.contains("gl_TexCoord"), "gl_TexCoord should be replaced");
assertTrue(result.contains("angelica_TexCoord0"), "should become angelica_TexCoord0");
assertTrue(result.contains("in vec4 angelica_TexCoord0"), "fragment shader should have 'in' declaration");
}
@Test
void testTexCoordMultipleIndices() {
String src = """
#version 120
void main() {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_TexCoord[1] = gl_MultiTexCoord1;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("out vec4 angelica_TexCoord0"), "should have TexCoord0 out");
assertTrue(result.contains("out vec4 angelica_TexCoord1"), "should have TexCoord1 out");
assertFalse(result.contains("gl_TexCoord"), "no gl_TexCoord should remain");
}
@Test
void testGlColorVertexVsFragmentDifferentTreatment() {
// Vertex: gl_Color = vertex attribute → angelica_Color
// Fragment: gl_Color = interpolated gl_FrontColor → angelica_FrontColor
String vertSrc = """
#version 120
void main() {
gl_FrontColor = gl_Color;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String fragSrc = """
#version 120
void main() {
gl_FragColor = gl_Color;
}
""";
String vertResult = CompatShaderTransformer.transform(vertSrc, false);
String fragResult = CompatShaderTransformer.transform(fragSrc, true);
// Vertex shader: gl_Color → angelica_Color (attribute), gl_FrontColor → angelica_FrontColor (out)
assertTrue(vertResult.contains("angelica_Color"), "vertex gl_Color → angelica_Color");
assertTrue(vertResult.contains("angelica_FrontColor"), "vertex gl_FrontColor → angelica_FrontColor");
assertFalse(vertResult.contains("gl_Color"), "no gl_Color should remain in vertex");
assertFalse(vertResult.contains("gl_FrontColor"), "no gl_FrontColor should remain");
// Fragment shader: gl_Color → angelica_FrontColor (in varying)
assertTrue(fragResult.contains("angelica_FrontColor"), "fragment gl_Color → angelica_FrontColor");
assertFalse(fragResult.contains("gl_Color"), "fragment should NOT have gl_Color");
}
@Test
void testDefinePreservedDuringTransformation() {
String src = """
#version 120
#define M_PI 3.1415926535897932384626433832795
void main() {
float x = 2.0 * M_PI;
gl_FragColor = vec4(x);
}
""";
String result = CompatShaderTransformer.transform(src, true);
assertTrue(result.contains("#define M_PI 3.1415926535897932384626433832795"),
"#define should be preserved through transformation\n\n" + result);
}
@Test
void testGlFrontLightModelProductSceneColor() {
String src = """
#version 120
void main() {
gl_FrontColor = gl_FrontLightModelProduct.sceneColor;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertFalse(result.contains("gl_FrontLightModelProduct"), "gl_FrontLightModelProduct should be replaced");
assertTrue(result.contains("uniform vec4 angelica_SceneColor"), "angelica_SceneColor uniform should be injected");
assertTrue(result.contains("angelica_SceneColor"), "should reference angelica_SceneColor");
}
@Test
void testVersionPatternDoesNotEatNextLine() {
String src = "#version 330\nsomeword\n";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("someword"), "Next-line word must not be eaten by version fixup");
assertTrue(result.contains("#version 330 core"), "Version should be upgraded to core");
}
@Test
void testModernShaderWithoutCoreKeyword() {
String src = """
#version 430
in vec3 Position;
uniform mat4 ModelViewMat;
uniform mat4 ProjMat;
out vec4 vertexColor;
out float fogDistance;
void main() {
vec4 finalPos = vec4(Position, 1.0);
vec4 modelPos = ModelViewMat * finalPos;
gl_Position = ProjMat * modelPos;
fogDistance = length(modelPos.xz);
vertexColor = vec4(1.0);
}
""";
String result = CompatShaderTransformer.transform(src, false);
assertTrue(result.contains("#version 430 core"), "Version should get 'core' profile added");
assertTrue(result.contains("in vec3 Position"), "'in' keyword must not be eaten");
assertTrue(result.contains("ModelViewMat"), "Shader content must be preserved");
assertTrue(result.contains("ProjMat"), "Shader content must be preserved");
assertTrue(result.contains("fogDistance"), "Shader content must be preserved");
}
@Test
void testLegacyQualifierConversion() {
String vertSrc = """
#version 120
attribute float a_Custom;
varying vec2 v_TexCoord;
void main() {
v_TexCoord = vec2(a_Custom);
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
""";
String fragSrc = """
#version 120
varying vec2 v_TexCoord;
void main() {
gl_FragColor = vec4(v_TexCoord, 0.0, 1.0);
}
""";
String vertResult = CompatShaderTransformer.transform(vertSrc, false);
String fragResult = CompatShaderTransformer.transform(fragSrc, true);
// attribute → in, varying → out (vertex)
assertFalse(vertResult.contains("attribute"), "no 'attribute' keyword in core profile");
assertFalse(vertResult.contains("varying"), "no 'varying' keyword in vertex");
assertTrue(vertResult.contains("in float a_Custom"), "attribute → in");
assertTrue(vertResult.contains("out vec2 v_TexCoord"), "varying → out in vertex");
// varying → in (fragment)
assertFalse(fragResult.contains("varying"), "no 'varying' keyword in fragment");
assertTrue(fragResult.contains("in vec2 v_TexCoord"), "varying → in in fragment");
}
}
@@ -1,219 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL20;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(AngelicaExtension.class)
class CompatUniformManagerTest {
private int program = 0;
@AfterEach
void cleanup() {
if (program != 0) {
GL20.glUseProgram(0);
GL20.glDeleteProgram(program);
program = 0;
}
}
@Test
void testProgramWithCompatUniforms() {
// Create a shader program that uses angelica_* uniforms
String vertSrc = """
#version 330 core
uniform mat4 angelica_ModelViewMatrix;
uniform mat4 angelica_ProjectionMatrix;
uniform mat3 angelica_NormalMatrix;
in vec3 position;
in vec3 normal;
out vec3 vNormal;
void main() {
vNormal = angelica_NormalMatrix * normal;
gl_Position = angelica_ProjectionMatrix * angelica_ModelViewMatrix * vec4(position, 1.0);
}
""";
String fragSrc = """
#version 330 core
in vec3 vNormal;
layout (location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(vNormal, 1.0);
}
""";
program = createAndLinkProgram(vertSrc, fragSrc);
// onLinkProgram should discover the uniform locations
CompatUniformManager.onLinkProgram(program);
assertTrue(CompatUniformManager.hasProgram(program));
int[] locs = CompatUniformManager.getLocations(program);
assertNotNull(locs);
// ModelView, Projection, NormalMatrix should have valid locations
assertNotEquals(-1, locs[CompatUniformManager.LOC_MODELVIEW], "angelica_ModelViewMatrix location");
assertNotEquals(-1, locs[CompatUniformManager.LOC_PROJECTION], "angelica_ProjectionMatrix location");
assertNotEquals(-1, locs[CompatUniformManager.LOC_NORMAL], "angelica_NormalMatrix location");
// Use program and upload — should not error
GL20.glUseProgram(program);
CompatUniformManager.onUseProgram(program);
// Verify no GL errors
assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after uniform upload");
}
@Test
void testProgramWithoutCompatUniforms() {
String vertSrc = """
#version 330 core
uniform mat4 mvp;
in vec3 position;
void main() {
gl_Position = mvp * vec4(position, 1.0);
}
""";
String fragSrc = """
#version 330 core
layout (location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(1.0);
}
""";
program = createAndLinkProgram(vertSrc, fragSrc);
CompatUniformManager.onLinkProgram(program);
// No angelica_* uniforms → not tracked
assertFalse(CompatUniformManager.hasProgram(program));
}
@Test
void testProgramWithFogUniforms() {
// All fog uniforms must be used in the shader to prevent the GLSL compiler from optimizing them away (which would make glGetUniformLocation return -1)
String vertSrc = """
#version 330 core
uniform float angelica_FogDensity;
uniform float angelica_FogStart;
uniform float angelica_FogEnd;
uniform vec4 angelica_FogColor;
in vec3 position;
out vec4 vFogData;
void main() {
gl_Position = vec4(position, 1.0);
float dist = length(position);
float linearFog = clamp((angelica_FogEnd - dist) / (angelica_FogEnd - angelica_FogStart), 0.0, 1.0);
float expFog = exp(-angelica_FogDensity * dist);
vFogData = angelica_FogColor * linearFog * expFog;
}
""";
String fragSrc = """
#version 330 core
in vec4 vFogData;
layout (location = 0) out vec4 fragColor;
void main() {
fragColor = vFogData;
}
""";
program = createAndLinkProgram(vertSrc, fragSrc);
CompatUniformManager.onLinkProgram(program);
assertTrue(CompatUniformManager.hasProgram(program));
int[] locs = CompatUniformManager.getLocations(program);
assertNotNull(locs);
// Fog uniforms should have valid locations (indices 6-9)
assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_DENSITY], "angelica_FogDensity location");
assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_START], "angelica_FogStart location");
assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_END], "angelica_FogEnd location");
assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_COLOR], "angelica_FogColor location");
// Use program and upload — should not error
GL20.glUseProgram(program);
CompatUniformManager.onUseProgram(program);
assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after fog uniform upload");
}
@Test
void testDeleteProgramCleansUp() {
String vertSrc = """
#version 330 core
uniform mat4 angelica_ModelViewMatrix;
in vec3 position;
void main() {
gl_Position = angelica_ModelViewMatrix * vec4(position, 1.0);
}
""";
String fragSrc = """
#version 330 core
layout (location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(1.0);
}
""";
program = createAndLinkProgram(vertSrc, fragSrc);
CompatUniformManager.onLinkProgram(program);
assertTrue(CompatUniformManager.hasProgram(program));
CompatUniformManager.onDeleteProgram(program);
assertFalse(CompatUniformManager.hasProgram(program));
}
private static int createAndLinkProgram(String vertSrc, String fragSrc) {
int vs = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
GL20.glShaderSource(vs, vertSrc);
GL20.glCompileShader(vs);
if (GL20.glGetShaderi(vs, GL20.GL_COMPILE_STATUS) == 0) {
String log = GL20.glGetShaderInfoLog(vs, 4096);
GL20.glDeleteShader(vs);
fail("Vertex shader compilation failed: " + log);
}
int fs = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
GL20.glShaderSource(fs, fragSrc);
GL20.glCompileShader(fs);
if (GL20.glGetShaderi(fs, GL20.GL_COMPILE_STATUS) == 0) {
String log = GL20.glGetShaderInfoLog(fs, 4096);
GL20.glDeleteShader(vs);
GL20.glDeleteShader(fs);
fail("Fragment shader compilation failed: " + log);
}
int prog = GL20.glCreateProgram();
GL20.glAttachShader(prog, vs);
GL20.glAttachShader(prog, fs);
GL20.glLinkProgram(prog);
if (GL20.glGetProgrami(prog, GL20.GL_LINK_STATUS) == 0) {
String log = GL20.glGetProgramInfoLog(prog, 4096);
GL20.glDeleteProgram(prog);
GL20.glDeleteShader(vs);
GL20.glDeleteShader(fs);
fail("Program link failed: " + log);
}
GL20.glDeleteShader(vs);
GL20.glDeleteShader(fs);
return prog;
}
}
@@ -1,270 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Tests GLSM display list behavior matches OpenGL spec. */
@ExtendWith(AngelicaExtension.class)
class DisplayListCompilationGLSMTest {
private int testList = -1;
private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) {
for (int i = 0; i < 16; i++) {
assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")");
}
}
@BeforeEach
void setup() {
// Ensure not recording from a previous failed test
if (DisplayListManager.isRecording()) {
try { GLStateManager.glEndList(); } catch (Exception ignored) {}
}
GLStateManager.disableBlend();
GLStateManager.disableDepthTest();
GLStateManager.disableCull();
// Reset matrix to identity for transform tests
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
}
@AfterEach
void cleanup() {
// End any open recording
if (DisplayListManager.isRecording()) {
try { GLStateManager.glEndList(); } catch (Exception ignored) {}
}
if (testList > 0) {
GLStateManager.glDeleteLists(testList, 1);
testList = -1;
}
GLStateManager.disableBlend();
GLStateManager.disableDepthTest();
GLStateManager.disableCull();
}
@Test
void glsm_compile_doesNotChangeState() {
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.enableBlend();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged");
GLStateManager.glEndList();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged");
GLStateManager.glCallList(testList);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed");
}
@Test
void glsm_compileAndExecute_changesStateImmediately() {
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed");
GLStateManager.glEndList();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains");
}
@Test
void glsm_compile_transformNotApplied() {
FloatBuffer before = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before);
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10, 20, 30);
FloatBuffer during = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during);
assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged");
GLStateManager.glEndList();
}
@Test
void glsm_compileAndExecute_transformQueuedUntilFlush() {
// Transforms queue until draw/glEndList (state commands don't flush)
FloatBuffer identity = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, identity);
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glTranslatef(10, 0, 0); // Queued
FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush);
assertMatrixEquals(identity, beforeFlush, "Before flush: transform queued");
GLStateManager.enableBlend(); // State commands DON'T flush transforms anymore
FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd);
assertMatrixEquals(identity, afterStateCmd, "After state cmd: transform still queued");
GLStateManager.glEndList(); // glEndList flushes pending transforms
FloatBuffer afterEndList = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterEndList);
assertEquals(10.0f, afterEndList.get(12), 0.001f, "After glEndList: transform applied");
}
@Test
void glsm_playback_appliesRecordedState() {
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.enableBlend();
GLStateManager.glEndList();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After compile: unchanged");
GLStateManager.glCallList(testList);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: enabled");
}
@Test
void glsm_compile_multipleStateChanges() {
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.enableBlend();
GLStateManager.enableDepthTest();
GLStateManager.enableCull();
GLStateManager.glEndList();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged");
assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged");
assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged");
GLStateManager.glCallList(testList);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled");
assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled");
assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled");
}
@Test
void glsm_compile_matrixModeChangeRecorded() {
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glTranslatef(5, 0, 0);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glTranslatef(10, 0, 0);
GLStateManager.glEndList();
FloatBuffer proj = BufferUtils.createFloatBuffer(16);
FloatBuffer mv = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv);
assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged");
assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged");
GLStateManager.glCallList(testList);
proj.clear(); mv.clear();
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv);
assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)");
assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)");
}
@Test
void glsm_compile_pushPopMatrixRecorded() {
GLStateManager.glTranslatef(100, 0, 0); // Base transform
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(10, 0, 0);
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile);
assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base");
GLStateManager.glCallList(testList);
FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay);
assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base");
}
@Test
void glsm_compileAndExecute_matrixModeFlushesTransforms() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glTranslatef(10, 0, 0); // Queued
GLStateManager.glRotatef(45, 0, 1, 0); // Queued
FloatBuffer beforeMode = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeMode);
assertEquals(0.0f, beforeMode.get(12), 0.001f, "Before MatrixMode: queued");
GLStateManager.glMatrixMode(GL11.GL_PROJECTION); // Barrier - flushes
FloatBuffer afterMode = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterMode);
assertNotEquals(0.0f, afterMode.get(12), "After MatrixMode: flushed to MODELVIEW");
FloatBuffer proj = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
assertEquals(0.0f, proj.get(12), 0.001f, "PROJECTION still identity");
GLStateManager.glEndList();
// Cleanup: restore matrix mode to MODELVIEW
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void glsm_compileAndExecute_pushPopMatrixQueued() {
// State commands don't flush, but push/pop ARE matrix barriers
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(10, 0, 0);
FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush);
assertEquals(0.0f, beforeFlush.get(12), 0.001f, "Before flush: queued");
GLStateManager.enableBlend(); // NOT a barrier in new model
FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd);
assertEquals(0.0f, afterStateCmd.get(12), 0.001f, "After state cmd: still queued");
GLStateManager.glPopMatrix(); // Matrix barrier: flushes transform, then pops
FloatBuffer afterPop = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop);
assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity (pushed state)");
GLStateManager.glEndList();
}
}
@@ -1,261 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.*;
/** Tests raw GL11 display list behavior (reference for GLSM). */
@ExtendWith(AngelicaExtension.class)
class DisplayListCompilationRawGLTest {
private int testList = -1;
private static void assertMatrixEquals(FloatBuffer expected, FloatBuffer actual, String message) {
for (int i = 0; i < 16; i++) {
assertEquals(expected.get(i), actual.get(i), 0.001f, message + " (element " + i + ")");
}
}
@BeforeEach
void setup() {
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_CULL_FACE);
}
@AfterEach
void cleanup() {
if (testList > 0) {
GL11.glDeleteLists(testList, 1);
testList = -1;
}
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_CULL_FACE);
}
@Test
void rawGL_compile_doesNotChangeState() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glEnable(GL11.GL_BLEND);
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE: state unchanged");
GL11.glEndList();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: state unchanged");
GL11.glCallList(testList);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: state changed");
}
@Test
void rawGL_compileAndExecute_changesStateImmediately() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GL11.glEnable(GL11.GL_BLEND);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "During GL_COMPILE_AND_EXECUTE: state changed");
GL11.glEndList();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE_AND_EXECUTE: state remains");
}
@Test
void rawGL_compile_transformNotApplied() {
FloatBuffer before = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before);
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glTranslatef(10, 20, 30);
FloatBuffer during = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during);
assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged");
GL11.glEndList();
}
@Test
void rawGL_compileAndExecute_transformAppliedImmediately() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GL11.glTranslatef(10, 0, 0);
FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrix);
assertEquals(10.0f, matrix.get(12), 0.001f, "During GL_COMPILE_AND_EXECUTE: transform applied");
GL11.glEndList();
}
@Test
void rawGL_compile_multipleStateChanges() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glEndList();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "After GL_COMPILE: BLEND unchanged");
assertFalse(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After GL_COMPILE: DEPTH_TEST unchanged");
assertFalse(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After GL_COMPILE: CULL_FACE unchanged");
GL11.glCallList(testList);
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "After playback: BLEND enabled");
assertTrue(GL11.glIsEnabled(GL11.GL_DEPTH_TEST), "After playback: DEPTH_TEST enabled");
assertTrue(GL11.glIsEnabled(GL11.GL_CULL_FACE), "After playback: CULL_FACE enabled");
}
@Test
void rawGL_compile_matrixModeChangeRecorded() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glTranslatef(5, 0, 0);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glTranslatef(10, 0, 0);
GL11.glEndList();
FloatBuffer proj = BufferUtils.createFloatBuffer(16);
FloatBuffer mv = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv);
assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged");
assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged");
GL11.glCallList(testList);
proj.clear(); mv.clear();
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv);
assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)");
assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)");
}
@Test
void rawGL_compile_pushPopMatrixRecorded() {
GL11.glTranslatef(100, 0, 0); // Base transform
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glPushMatrix();
GL11.glTranslatef(10, 0, 0);
GL11.glPopMatrix();
GL11.glEndList();
FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile);
assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base");
GL11.glCallList(testList);
FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay);
assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base (push/pop balanced)");
}
@Test
void rawGL_compileAndExecute_pushPopMatrixExecutedImmediately() {
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GL11.glPushMatrix();
GL11.glTranslatef(10, 0, 0);
FloatBuffer inside = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, inside);
assertEquals(10.0f, inside.get(12), 0.001f, "Inside push: translate visible");
GL11.glPopMatrix();
FloatBuffer afterPop = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop);
assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity");
GL11.glEndList();
}
// ==================== Immediate Mode with Transforms (Raw GL) ====================
@Test
void rawGL_compile_immediateModeWithTransforms() {
// Verifies GL_COMPILE doesn't execute, playback applies transforms
GL11.glLoadIdentity();
GL11.glTranslatef(100.0f, 0.0f, 0.0f); // Base position
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE);
GL11.glPushMatrix();
GL11.glTranslatef(50.0f, 25.0f, 0.0f);
GL11.glScalef(0.5f, 0.5f, 1.0f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0.0f, 0.0f, 0.0f);
GL11.glVertex3f(16.0f, 0.0f, 0.0f);
GL11.glVertex3f(16.0f, 16.0f, 0.0f);
GL11.glVertex3f(0.0f, 16.0f, 0.0f);
GL11.glEnd();
GL11.glPopMatrix();
GL11.glEndList();
// Matrix should still be at base position after GL_COMPILE
FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile);
assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix unchanged");
// Playback - push/pop should preserve base transform
GL11.glCallList(testList);
FloatBuffer afterPlayback = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlayback);
assertEquals(100.0f, afterPlayback.get(12), 0.001f, "After playback: base position preserved");
assertEquals(1.0f, afterPlayback.get(0), 0.001f, "After playback: no scale (popped)");
GL11.glLoadIdentity();
}
@Test
void rawGL_compileAndExecute_immediateModeExecutesImmediately() {
// Verifies GL_COMPILE_AND_EXECUTE executes transforms during recording
GL11.glLoadIdentity();
testList = GL11.glGenLists(1);
GL11.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE);
GL11.glScalef(0.5f, 0.5f, 0.5f);
FloatBuffer during = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during);
assertEquals(0.5f, during.get(0), 0.001f, "During COMPILE_AND_EXECUTE: scale applied");
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0.0f, 0.0f, 0.0f);
GL11.glVertex3f(1.0f, 0.0f, 0.0f);
GL11.glVertex3f(1.0f, 1.0f, 0.0f);
GL11.glVertex3f(0.0f, 1.0f, 0.0f);
GL11.glEnd();
GL11.glEndList();
FloatBuffer after = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, after);
assertEquals(0.5f, after.get(0), 0.001f, "After COMPILE_AND_EXECUTE: scale remains");
GL11.glLoadIdentity();
}
}
@@ -1,239 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DisplayListIdAllocatorTest {
@Test
void zeroNeverReturned() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator(1);
// Allocate enough IDs to fill the first word (32 IDs). None should be 0.
for (int i = 0; i < 31; i++) {
int id = alloc.allocRange(1);
assertNotEquals(0, id, "ID 0 must never be returned");
assertTrue(id > 0, "All returned IDs must be positive");
}
}
@Test
void singleAllocReturnsSequential() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// First alloc should be 1 (0 is reserved)
assertEquals(1, alloc.allocRange(1));
assertEquals(2, alloc.allocRange(1));
assertEquals(3, alloc.allocRange(1));
}
@Test
void isAllocatedTracksState() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
assertFalse(alloc.isAllocated(0), "ID 0 should not report as allocated via isAllocated");
assertFalse(alloc.isAllocated(1));
int id = alloc.allocRange(1);
assertTrue(alloc.isAllocated(id));
assertFalse(alloc.isAllocated(id + 1));
}
@Test
void freeAndReuse() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
int a = alloc.allocRange(1); // 1
int b = alloc.allocRange(1); // 2
int c = alloc.allocRange(1); // 3
alloc.free(b); // free 2
assertFalse(alloc.isAllocated(b));
// Next alloc should reuse 2 (lowestFreeIdx reset)
int d = alloc.allocRange(1);
assertEquals(b, d, "Freed ID should be reused");
}
@Test
void freeRangeReleasesAll() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
int base = alloc.allocRange(1);
alloc.allocRange(1);
alloc.allocRange(1);
// IDs 1, 2, 3 allocated
assertTrue(alloc.isAllocated(1));
assertTrue(alloc.isAllocated(2));
assertTrue(alloc.isAllocated(3));
alloc.freeRange(1, 3);
assertFalse(alloc.isAllocated(1));
assertFalse(alloc.isAllocated(2));
assertFalse(alloc.isAllocated(3));
}
@Test
void rangeAllocReturnsConsecutiveIds() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// Range alloc of 64 should return 64 consecutive IDs starting at a word-aligned base
int base = alloc.allocRange(64);
assertTrue(base > 0, "Base must be positive");
assertEquals(0, base % 32, "Range base should be word-aligned");
// All IDs in range must be allocated
for (int i = 0; i < 64; i++) {
assertTrue(alloc.isAllocated(base + i), "ID " + (base + i) + " should be allocated");
}
// ID just past range should not be allocated
assertFalse(alloc.isAllocated(base + 64));
}
@Test
void rangeAllocPartialWord() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// Allocate 10 IDs — less than a full word, still word-aligned base
int base = alloc.allocRange(10);
assertTrue(base > 0);
for (int i = 0; i < 10; i++) {
assertTrue(alloc.isAllocated(base + i));
}
// Bits past the 10 in that same word should be free
assertFalse(alloc.isAllocated(base + 10));
}
@Test
void autoGrowOnExhaustion() {
// Start very small — 1 word = 32 IDs (minus ID 0 = 31 usable)
DisplayListIDAllocator alloc = new DisplayListIDAllocator(1);
// Allocate all 31 usable IDs in the first word
for (int i = 0; i < 31; i++) {
int id = alloc.allocRange(1);
assertTrue(id > 0 && id < 32);
}
// Next alloc must trigger grow
int id = alloc.allocRange(1);
assertTrue(id >= 32, "After exhausting first word, should allocate from grown region");
assertTrue(alloc.isAllocated(id));
}
@Test
void autoGrowForRange() {
// Start with 1 word. Request 64 consecutive IDs — must grow.
DisplayListIDAllocator alloc = new DisplayListIDAllocator(1);
int base = alloc.allocRange(64);
assertTrue(base > 0);
for (int i = 0; i < 64; i++) {
assertTrue(alloc.isAllocated(base + i));
}
}
@Test
void freeZeroIsNoOp() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// Should not throw
alloc.free(0);
alloc.free(-1);
}
@Test
void isAllocatedOutOfBoundsReturnsFalse() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator(1);
assertFalse(alloc.isAllocated(99999), "Out-of-bounds ID should return false");
assertFalse(alloc.isAllocated(-1));
}
@Test
void invalidCountThrows() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
assertThrows(IllegalArgumentException.class, () -> alloc.allocRange(0));
assertThrows(IllegalArgumentException.class, () -> alloc.allocRange(-1));
}
@Test
void stressAllocFreeRealloc() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
int[] ids = new int[1000];
// Allocate 1000 IDs
for (int i = 0; i < 1000; i++) {
ids[i] = alloc.allocRange(1);
assertTrue(ids[i] > 0);
assertTrue(alloc.isAllocated(ids[i]));
}
// Free all odd-indexed IDs
for (int i = 1; i < 1000; i += 2) {
alloc.free(ids[i]);
assertFalse(alloc.isAllocated(ids[i]));
}
// Even-indexed IDs should still be allocated
for (int i = 0; i < 1000; i += 2) {
assertTrue(alloc.isAllocated(ids[i]));
}
// Reallocate 500 IDs — should reuse freed slots
for (int i = 0; i < 500; i++) {
int id = alloc.allocRange(1);
assertTrue(id > 0);
assertTrue(alloc.isAllocated(id));
}
}
@Test
void noDoubleAllocation() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// Allocate many IDs and verify uniqueness
java.util.Set<Integer> seen = new java.util.HashSet<>();
for (int i = 0; i < 500; i++) {
int id = alloc.allocRange(1);
assertTrue(seen.add(id), "Duplicate ID returned: " + id);
}
}
@Test
void rangeAfterSingleAllocs() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
// Fragment the bitmap with single allocs
for (int i = 0; i < 10; i++) {
alloc.allocRange(1);
}
// Now request a range — should skip past the occupied word(s)
int base = alloc.allocRange(32);
assertTrue(base > 0);
// The range must not overlap with any previously allocated ID
for (int i = 0; i < 32; i++) {
assertTrue(alloc.isAllocated(base + i));
}
// The first 10 IDs (1-10) should still be allocated
for (int i = 1; i <= 10; i++) {
assertTrue(alloc.isAllocated(i));
}
}
@Test
void multipleRanges() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
int base1 = alloc.allocRange(32);
int base2 = alloc.allocRange(32);
// Ranges must not overlap
assertTrue(base2 >= base1 + 32 || base1 >= base2 + 32,
"Ranges must not overlap: base1=" + base1 + " base2=" + base2);
// All IDs in both ranges must be allocated
for (int i = 0; i < 32; i++) {
assertTrue(alloc.isAllocated(base1 + i));
assertTrue(alloc.isAllocated(base2 + i));
}
}
@Test
void freeRangeThenReallocRange() {
DisplayListIDAllocator alloc = new DisplayListIDAllocator();
int base1 = alloc.allocRange(64);
alloc.freeRange(base1, 64);
// All should be free
for (int i = 0; i < 64; i++) {
assertFalse(alloc.isAllocated(base1 + i));
}
// Reallocate — should reuse the freed region
int base2 = alloc.allocRange(64);
assertEquals(base1, base2, "Freed range should be reused");
}
}
@@ -1,65 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import org.lwjgl.opengl.GL11;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Helper class for building test data for display list batching tests.
* Allows creating quads and AccumulatedDraws without GL context.
*/
public final class DisplayListTestHelper {
private DisplayListTestHelper() {}
public static void createSimpleDraw() {
final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator();
// Record a single quad using immediate mode
recorder.startDrawing(GL11.GL_QUADS);
recorder.addVertex(0, 0, 0);
recorder.addVertex(1, 0, 0);
recorder.addVertex(1, 1, 0);
recorder.addVertex(0, 1, 0);
DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end());
}
public static void createTextureDraw() {
final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator();
// Record a single quad using immediate mode
recorder.startDrawing(GL11.GL_QUADS);
recorder.setTextureUV(0, 0);
recorder.addVertex(0, 0, 0);
recorder.setTextureUV(1, 0);
recorder.addVertex(1, 0, 0);
recorder.setTextureUV(1, 1);
recorder.addVertex(1, 1, 0);
recorder.setTextureUV(0, 1);
recorder.addVertex(0, 1, 0);
DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end());
}
public static void createColorDraw() {
final DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator();
// Record a single quad using immediate mode
recorder.startDrawing(GL11.GL_QUADS);
recorder.setColorRGBA(255, 255, 255, 255);
recorder.addVertex(0, 0, 0);
recorder.addVertex(1, 0, 0);
recorder.addVertex(1, 1, 0);
recorder.addVertex(0, 1, 0);
DisplayListManager.addImmediateModeDraw(ImmediateModeRecorder.end());
}
public static CompiledDisplayList createDisplayList(Runnable runnable) {
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
runnable.run();
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(list);
assertNotNull(compiled, "Display list should be compiled");
return compiled;
}
}
@@ -1,203 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(AngelicaExtension.class)
class FeedbackManagerTest {
@BeforeEach
void setUp() {
FeedbackManager.reset();
}
@AfterEach
void tearDown() {
// Ensure we're back in render mode
if (FeedbackManager.isFeedbackMode()) {
FeedbackManager.glRenderMode(GL11.GL_RENDER);
}
FeedbackManager.reset();
}
@Test
void testStateMachine_noDraws_returnsZero() {
final FloatBuffer buf = BufferUtils.createFloatBuffer(64);
FeedbackManager.glFeedbackBuffer(GL11.GL_2D, buf);
FeedbackManager.glRenderMode(GL11.GL_FEEDBACK);
assertTrue(FeedbackManager.isFeedbackMode());
final int result = FeedbackManager.glRenderMode(GL11.GL_RENDER);
assertEquals(0, result, "No draws should produce 0 tokens");
assertFalse(FeedbackManager.isFeedbackMode());
}
@Test
void testOverflow_returnsNegative() {
// Buffer with only 2 floats — any triangle will overflow
final FloatBuffer buf = BufferUtils.createFloatBuffer(2);
FeedbackManager.glFeedbackBuffer(GL11.GL_2D, buf);
FeedbackManager.glRenderMode(GL11.GL_FEEDBACK);
// Set up identity matrices and a viewport
GLStateManager.getModelViewMatrix().identity();
GLStateManager.getProjectionMatrix().identity();
GLStateManager.getViewportState().setViewPort(0, 0, 800, 600);
GLStateManager.getViewportState().setDepthRange(0.0, 1.0);
// Upload 3 vertices to a VBO and draw
final int vao = GL30.glGenVertexArrays();
GLStateManager.glBindVertexArray(vao);
final float[] verts = { 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f, 0f };
final FloatBuffer vertBuf = BufferUtils.createFloatBuffer(9);
vertBuf.put(verts).flip();
final int vbo = GL15.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertBuf, GL15.GL_STATIC_DRAW);
GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 12, 0);
GLStateManager.glEnableVertexAttribArray(0);
FeedbackManager.processDrawArrays(GL11.GL_TRIANGLES, 0, 3);
final int result = FeedbackManager.glRenderMode(GL11.GL_RENDER);
assertEquals(-1, result, "Overflow should return -1");
// Cleanup
GLStateManager.glDisableVertexAttribArray(0);
GLStateManager.glBindVertexArray(0);
GL15.glDeleteBuffers(vbo);
GLStateManager.glDeleteVertexArrays(vao);
}
@Test
void testPassThrough() {
final FloatBuffer buf = BufferUtils.createFloatBuffer(64);
FeedbackManager.glFeedbackBuffer(GL11.GL_2D, buf);
FeedbackManager.glRenderMode(GL11.GL_FEEDBACK);
FeedbackManager.glPassThrough(42.0f);
final int result = FeedbackManager.glRenderMode(GL11.GL_RENDER);
assertEquals(2, result, "PassThrough should write 2 floats");
assertEquals(GL11.GL_PASS_THROUGH_TOKEN, buf.get(0), "First token should be PASS_THROUGH_TOKEN");
assertEquals(42.0f, buf.get(1), "Second token should be the pass-through value");
}
@Test
void testTriangleFeedback_GL2D() {
final FloatBuffer buf = BufferUtils.createFloatBuffer(128);
FeedbackManager.glFeedbackBuffer(GL11.GL_2D, buf);
FeedbackManager.glRenderMode(GL11.GL_FEEDBACK);
// Identity MV/proj, viewport (0,0,800,600)
GLStateManager.getModelViewMatrix().identity();
GLStateManager.getProjectionMatrix().identity();
GLStateManager.getViewportState().setViewPort(0, 0, 800, 600);
GLStateManager.getViewportState().setDepthRange(0.0, 1.0);
// Upload 3 vertices forming a triangle
final int vao = GL30.glGenVertexArrays();
GLStateManager.glBindVertexArray(vao);
// NDC vertices: (0,0,0), (1,0,0), (0,1,0)
// With identity MVP and viewport 800x600:
// NDC(0,0) → window(400, 300)
// NDC(1,0) → window(800, 300)
// NDC(0,1) → window(400, 600)
final float[] verts = { 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f, 0f };
final FloatBuffer vertBuf = BufferUtils.createFloatBuffer(9);
vertBuf.put(verts).flip();
final int vbo = GL15.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertBuf, GL15.GL_STATIC_DRAW);
GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 12, 0);
GLStateManager.glEnableVertexAttribArray(0);
FeedbackManager.processDrawArrays(GL11.GL_TRIANGLES, 0, 3);
final int count = FeedbackManager.glRenderMode(GL11.GL_RENDER);
// GL_2D: POLYGON_TOKEN, 3, x0, y0, x1, y1, x2, y2 = 8 floats
assertEquals(8, count, "Triangle in GL_2D should produce 8 floats");
assertEquals(GL11.GL_POLYGON_TOKEN, buf.get(0), 0.001f);
assertEquals(3.0f, buf.get(1), 0.001f);
// Vertex 0: NDC(0,0) → window(400, 300)
assertEquals(400.0f, buf.get(2), 0.01f);
assertEquals(300.0f, buf.get(3), 0.01f);
// Vertex 1: NDC(1,0) → window(800, 300)
assertEquals(800.0f, buf.get(4), 0.01f);
assertEquals(300.0f, buf.get(5), 0.01f);
// Vertex 2: NDC(0,1) → window(400, 600)
assertEquals(400.0f, buf.get(6), 0.01f);
assertEquals(600.0f, buf.get(7), 0.01f);
// Cleanup
GLStateManager.glDisableVertexAttribArray(0);
GLStateManager.glBindVertexArray(0);
GL15.glDeleteBuffers(vbo);
GLStateManager.glDeleteVertexArrays(vao);
}
@Test
void testIdentityTransform_viewportMapping() {
final FloatBuffer buf = BufferUtils.createFloatBuffer(64);
FeedbackManager.glFeedbackBuffer(GL11.GL_3D, buf);
FeedbackManager.glRenderMode(GL11.GL_FEEDBACK);
GLStateManager.getModelViewMatrix().identity();
GLStateManager.getProjectionMatrix().identity();
GLStateManager.getViewportState().setViewPort(0, 0, 800, 600);
GLStateManager.getViewportState().setDepthRange(0.0, 1.0);
final int vao = GL30.glGenVertexArrays();
GLStateManager.glBindVertexArray(vao);
// Single point at NDC origin (0,0,0)
final float[] verts = { 0f, 0f, 0f };
final FloatBuffer vertBuf = BufferUtils.createFloatBuffer(3);
vertBuf.put(verts).flip();
final int vbo = GL15.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertBuf, GL15.GL_STATIC_DRAW);
GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 12, 0);
GLStateManager.glEnableVertexAttribArray(0);
FeedbackManager.processDrawArrays(GL11.GL_POINTS, 0, 1);
final int count = FeedbackManager.glRenderMode(GL11.GL_RENDER);
// GL_3D point: POINT_TOKEN, x, y, z = 4 floats
assertEquals(4, count);
assertEquals(GL11.GL_POINT_TOKEN, buf.get(0), 0.001f);
// NDC(0,0,0) → window center (400, 300, 0.5)
assertEquals(400.0f, buf.get(1), 0.01f);
assertEquals(300.0f, buf.get(2), 0.01f);
assertEquals(0.5f, buf.get(3), 0.01f);
// Cleanup
GLStateManager.glDisableVertexAttribArray(0);
GLStateManager.glBindVertexArray(0);
GL15.glDeleteBuffers(vbo);
GLStateManager.glDeleteVertexArrays(vao);
}
}
@@ -1,98 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for {@link com.gtnewhorizons.angelica.glsm.states.BooleanState#setUnknownState()}.
* Verifies that per-buffer blend operations (glEnablei/glDisablei) properly invalidate
* the GLSM blend cache so subsequent global blend enable/disable calls are not skipped.
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_BlendUnknownState_UnitTest {
@BeforeEach
void setUp() {
resetGLState();
}
@AfterEach
void tearDown() {
resetGLState();
}
@Test
void testSetUnknownStateForcesCacheBypass() {
// Enable blend via GLSM — both cache and GL should agree
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "GL blend should be enabled");
assertTrue(GLStateManager.getBlendMode().isEnabled(), "GLSM blend cache should be enabled");
// Simulate a per-buffer disable that bypasses the cache (as glDisablei does)
GL30.glDisablei(GL11.GL_BLEND, 0);
GLStateManager.getBlendMode().setUnknownState();
// Cache still says enabled, but GL state for buffer 0 is now disabled
assertTrue(GLStateManager.getBlendMode().isEnabled(), "GLSM cache should still say enabled");
// Re-enable blend via GLSM — without setUnknownState, this would be a no-op
// because the cache thinks blend is already enabled
GLStateManager.enableBlend();
// Per GL spec, glEnable(GL_BLEND) enables blend for ALL draw buffers,
// overriding any per-buffer disables
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "GL blend should be re-enabled after setUnknownState");
}
@Test
void testDisableBufferBlendInvalidatesCache() {
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND));
// Use RenderSystem which should call setUnknownState internally
RenderSystem.disableBufferBlend(0);
// Now re-enable via GLSM — should issue the GL call
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "Blend should be re-enabled after disableBufferBlend");
}
@Test
void testEnableBufferBlendInvalidatesCache() {
// Start with blend disabled
GLStateManager.disableBlend();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND));
// Per-buffer enable bypasses cache
RenderSystem.enableBufferBlend(0);
// Disable via GLSM — should issue the GL call despite cache saying disabled
GLStateManager.disableBlend();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "Blend should be disabled after enableBufferBlend + disableBlend");
}
@Test
void testUnknownStateClearedAfterSetEnabled() {
GLStateManager.enableBlend();
// Mark unknown
GLStateManager.getBlendMode().setUnknownState();
// First setEnabled clears the unknown flag
GLStateManager.enableBlend();
// Second setEnabled should use normal caching (no redundant GL call)
// Verify state is consistent
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND));
assertTrue(GLStateManager.getBlendMode().isEnabled());
}
}
@@ -1,219 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.DisplayListVBO;
import com.gtnewhorizons.angelica.glsm.recording.GLCommand;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.HashSet;
import java.util.Set;
import static com.gtnewhorizons.angelica.glsm.DisplayListTestHelper.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for display list format-based batching behavior.
*
* <p>With format-based batching, VBO allocation depends ONLY on vertex format:
* <ul>
* <li>All draws with the same format share a single VBO</li>
* <li>Different transforms produce separate DrawRangeCmd but share the VBO</li>
* <li>Different formats produce separate VBOs</li>
* </ul>
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_Batching_Test {
private static int getVBOCount(CompiledDisplayList compiledDisplayList) {
Set<IVertexBuffer> vaos = new HashSet<>();
for (DisplayListVBO.SubVBO vbo : compiledDisplayList.getOwnedVbos().getVBOs()) {
vaos.add(vbo.getVAO().getVBO());
}
return vaos.size();
}
// ==================== Pure Unit Tests (No GL Context) ====================
@Test
void testConsecutiveDrawsWithSameFormatShareSingleVBO() {
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw();
createSimpleDraw();
createSimpleDraw();
});
// Verify: 1 VBO for all draws (format-based batching)
assertEquals(1, getVBOCount(compiled),
"3 draws with same format should produce 1 shared VBO");
// Verify: 1 DrawRangeCmd covering all geometry
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
assertEquals(1, drawCount,
"3 consecutive draws with same format and transform should produce 1 DrawRangeCmd");
}
@Test
void testDrawsWithDifferentFormatsProduceSeparateVBOs() {
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw();
createTextureDraw();
createColorDraw();
});
// Verify: 3 VBOs (one per format)
assertEquals(3, getVBOCount(compiled),
"3 draws with different formats should produce 3 VBOs");
// Verify: 3 DrawRangeCmds
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
int drawRestoreCount = counts.getOrDefault(GLCommand.DRAW_RANGE_RESTORE, 0);
assertEquals(1, drawCount, "3 draws with different formats should produce 3 DrawRangeCmds");
assertEquals(2, drawRestoreCount, "3 draws with different formats should produce 3 DrawRangeCmds");
}
@Test
void testDifferentTransformsSameFormatShareVBO() {
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw();
GLStateManager.glTranslatef(1, 0, 0);
createSimpleDraw();
GLStateManager.glTranslatef(2, 0, 0);
createSimpleDraw();
});
// Verify: 1 shared VBO (same format)
assertEquals(1, getVBOCount(compiled), "Draws with different transforms but same format should share 1 VBO");
// Verify: 3 DrawRangeCmds (one per draw, each with different transform)
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
assertEquals(3, drawCount, "3 draws with different transforms should produce 3 DrawRangeCmds");
assertEquals(2, multMatrixCount, "Should have MultMatrix commands for each unique transform");
}
@Test
void testManyDrawsSameFormatProduceSingleVBO() {
CompiledDisplayList compiled = createDisplayList(() -> {
for (int i = 0; i < 100; i++) {
createSimpleDraw();
}
});
// Verify: 1 shared VBO
assertEquals(1, getVBOCount(compiled), "100 draws with same format should produce 1 shared VBO");
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
assertEquals(1, drawCount,
"100 consecutive draws with same format and transform should produce 1 DrawRangeCmd");
}
@Test
void testCancellingTransformsProduceSeparateDrawRangeCmds() {
// This tests the specific bug where transforms cancel out over the sequence
// (e.g., translate(+0.5) then translate(-0.5)) but draws captured in between
// have different transform states that must be preserved.
//
// With format-based batching: 1 shared VBO, 3 DrawRangeCmds
// The key point: draws 1 and 3 have the same transform (identity) but draw 2
// has a different transform, so they can't all be merged.
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw();
GLStateManager.glTranslatef(0.5f, 0, 0);
createSimpleDraw();
GLStateManager.glTranslatef(-0.5f, 0, 0);
createSimpleDraw();
});
// Verify: 1 shared VBO (same format)
assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO regardless of transforms");
// Verify: 3 DrawRangeCmds (different transforms require separate draw commands)
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
assertEquals(3, drawCount, "Draws with different recorded transforms must produce separate DrawRangeCmds");
}
@Test
void testDrawsWithSameTransformProduceSingleDrawRangeCmd() {
CompiledDisplayList compiled = createDisplayList(() -> {
GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f);
createSimpleDraw();
createSimpleDraw();
createSimpleDraw();
});
// Verify: 1 shared VBO
assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO");
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
assertEquals(1, drawCount, "Draws with same format and transform should produce 1 DrawRangeCmd");
assertEquals(1, multMatrixCount, "Should have exactly 1 MultMatrix for the common transform");
}
/**
* Test that draws with same transform but different stateGeneration do NOT merge.
* This simulates state commands (draw barriers) between draws.
* <br>
* Scenario: Draw1, glColor(red), Draw2, glBindTexture, Draw3, Draw4
* All draws have same transform (gen=1) but different batches (0, 1, 2).
* Expected: 3 separate DrawRangeCmds (only draw 3 & 4 should get merged).
* <br>
* This test will FAIL until FormatBuffer is fixed to check stateGeneration.
*/
@Test
void testDrawsWithDifferentBatchIdDoNotMerge() {
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw();
DisplayListManager.drawBarrier();
createSimpleDraw();
DisplayListManager.drawBarrier();
createSimpleDraw();
createSimpleDraw();
});
// Verify: 1 shared VBO (same format)
assertEquals(1, getVBOCount(compiled), "Draws with same format should share 1 VBO");
// Verify: 3 DrawRangeCmds (NOT merged due to different batch IDs)
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
assertEquals(3, drawCount,
"Draws with same transform but different batch IDs (draw barriers between) must NOT merge");
}
@Test
void testInterleavedFormatsProduceSeparateVBOs() {
CompiledDisplayList compiled = createDisplayList(() -> {
createSimpleDraw(); // A
createSimpleDraw(); // A
createTextureDraw(); // B
createSimpleDraw(); // A
createSimpleDraw(); // A
});
Int2IntMap counts = compiled.getCommandCounts();
int drawCount = counts.getOrDefault(GLCommand.DRAW_RANGE, 0);
int drawRestoreCount = counts.getOrDefault(GLCommand.DRAW_RANGE_RESTORE, 0);
// Verify: 2 VBOs (one for format A, one for format B)
assertEquals(2, getVBOCount(compiled), "A A B A A pattern should produce 2 VBOs (one per format)");
// Verify: 2 DrawRangeCmds (all A's merged into 1, B is 1)
// With format-based batching, all A draws go into the same FormatBuffer
// and get merged (same transform). Order within same command index doesn't matter.
assertEquals(2, drawCount, "A A B A A pattern with same transform should produce 2 DrawRangeCmds (A's merged, B separate)");
assertEquals(1, drawRestoreCount, "A A B A A pattern with same transform should produce 2 DrawRangeCmds (A's merged, B separate)");
}
}
@@ -1,223 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
/**
* Tests for display list format optimization.
* Verifies that display lists work correctly with different vertex attribute combinations
* and that optimal formats are selected.
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_FormatOptimization_Test {
private int displayList = -1;
@AfterEach
void cleanup() {
if (displayList > 0) {
GLStateManager.glDeleteLists(displayList, 1);
displayList = -1;
}
// Reset GL state to avoid test pollution
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GLStateManager.glTexCoord2f(0.0f, 0.0f);
GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f);
}
@Test
void testPositionOnlyFormat() {
// Create a display list with only position data (no color, texture, brightness, or normals)
// Use GLStateManager for all calls to ensure they go through GLSM (test env doesn't redirect GL11)
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the list to ensure it doesn't crash (verifies compilation succeeded)
GLStateManager.glCallList(displayList);
}
@Test
void testPositionTextureFormat() {
// Create a display list with position and texture coordinates
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glTexCoord2f(0, 0);
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glTexCoord2f(1, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glTexCoord2f(1, 1);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glTexCoord2f(0, 1);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the list to ensure it doesn't crash (verifies compilation succeeded)
GLStateManager.glCallList(displayList);
}
@Test
void testPositionColorTextureFormat() {
// Create a display list with position, color, and texture
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glColor4f(1, 1, 1, 1);
GLStateManager.glTexCoord2f(0, 0);
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glColor4f(1, 0, 0, 1);
GLStateManager.glTexCoord2f(1, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glColor4f(0, 1, 0, 1);
GLStateManager.glTexCoord2f(1, 1);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glColor4f(0, 0, 1, 1);
GLStateManager.glTexCoord2f(0, 1);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the list and verify color is restored to last value (blue)
GLStateManager.glCallList(displayList);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f},
"After playback, color should be blue (last color in immediate mode block)");
}
@Test
void testFullFormat() {
// Create a display list with all attributes: position, color, texture, and normal
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glNormal3f(0, 0, 1);
GLStateManager.glColor4f(1, 1, 1, 1);
GLStateManager.glTexCoord2f(0, 0);
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glNormal3f(0, 0, 1);
GLStateManager.glColor4f(1, 0, 0, 1);
GLStateManager.glTexCoord2f(1, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glNormal3f(0, 0, 1);
GLStateManager.glColor4f(0, 1, 0, 1);
GLStateManager.glTexCoord2f(1, 1);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glNormal3f(0, 0, 1);
GLStateManager.glColor4f(0, 0, 1, 1);
GLStateManager.glTexCoord2f(0, 1);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the list and verify color is restored to last value (blue)
GLStateManager.glCallList(displayList);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f},
"After playback, color should be blue (last color in immediate mode block)");
}
@Test
void testMultipleDrawsInDisplayList() {
// Test a display list with multiple draws with different formats
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
// First draw: position only
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
// Second draw: position + color
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glColor4f(1, 0, 0, 1);
GLStateManager.glVertex3f(2, 0, 0);
GLStateManager.glColor4f(0, 1, 0, 1);
GLStateManager.glVertex3f(3, 0, 0);
GLStateManager.glColor4f(0, 0, 1, 1);
GLStateManager.glVertex3f(3, 1, 0);
GLStateManager.glColor4f(1, 1, 0, 1);
GLStateManager.glVertex3f(2, 1, 0);
GLStateManager.glEnd();
// Third draw: position + texture
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glTexCoord2f(0, 0);
GLStateManager.glVertex3f(4, 0, 0);
GLStateManager.glTexCoord2f(1, 0);
GLStateManager.glVertex3f(5, 0, 0);
GLStateManager.glTexCoord2f(1, 1);
GLStateManager.glVertex3f(5, 1, 0);
GLStateManager.glTexCoord2f(0, 1);
GLStateManager.glVertex3f(4, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the list and verify color is restored to last value from second draw (yellow)
// Third draw has no color, so doesn't affect GL_CURRENT_COLOR
GLStateManager.glCallList(displayList);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 1f, 0f, 1f},
"After playback, color should be yellow (last color from second draw)");
}
/**
* Verifies that color is properly restored after immediate mode VBO playback.
* After glCallList, GL_CURRENT_COLOR should be the last color set in the display list.
*/
@Test
void testColorRestoredAfterImmediateModeVBOPlayback() {
// Set initial color to white
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 1f, 1f, 1f}, "Initial color should be white");
// Create display list with immediate mode that sets color to BLUE (0, 0, 1, 1)
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Blue
GLStateManager.glVertex3f(0, 0, 0);
GLStateManager.glVertex3f(1, 0, 0);
GLStateManager.glVertex3f(1, 1, 0);
GLStateManager.glVertex3f(0, 1, 0);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Call the display list
GLStateManager.glCallList(displayList);
// After playback, GL_CURRENT_COLOR should be blue (the last color in the display list)
// AND the GLSM cache should also be blue (synced with GL)
verifyState(GL11.GL_CURRENT_COLOR, new float[]{0f, 0f, 1f, 1f},
"After display list playback, color should be blue (last color in the list)");
// Now set color to red - this should ACTUALLY change the color
GLStateManager.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{1f, 0f, 0f, 1f},
"After setting color to red, color should be red");
}
}
@@ -1,265 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.joml.Matrix4f;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests for nested display list execution.
* Verifies that child display lists compose correctly with parent transforms.
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_Nesting_Test {
private int parentList = -1;
private int childList = -1;
@AfterEach
void cleanup() {
if (parentList > 0) {
GLStateManager.glDeleteLists(parentList, 1);
parentList = -1;
}
if (childList > 0) {
GLStateManager.glDeleteLists(childList, 1);
childList = -1;
}
// Reset GL state
GLStateManager.glLoadIdentity();
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
@Test
void testNestedDisplayListWithParentTransform() {
// Create child list: just a simple quad at origin
childList = GL11.glGenLists(1);
GLStateManager.glNewList(childList, GL11.GL_COMPILE);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glVertex3f(1, 1, 0);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
GLStateManager.glEndList();
// Create parent list: translate then call child
parentList = GL11.glGenLists(1);
GLStateManager.glNewList(parentList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Parent transform
GLStateManager.glCallList(childList); // Should render child at (10,0,0)
GLStateManager.glEndList();
// Execute parent list
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(parentList);
// Check final matrix state - should have parent's translate applied
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: translate(10, 0, 0)
Matrix4f expected = new Matrix4f().translate(10.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
// Compare buffers directly (both are column-major OpenGL format)
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testNestedDisplayListWithBothTransforms() {
// Create child list: translate and draw
childList = GL11.glGenLists(1);
GLStateManager.glNewList(childList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); // Child transform
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glVertex3f(1, 1, 0);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
GLStateManager.glEndList();
// Create parent list: translate then call child
parentList = GL11.glGenLists(1);
GLStateManager.glNewList(parentList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Parent transform
GLStateManager.glCallList(childList); // Child adds (1,0,0) to parent's (10,0,0)
GLStateManager.glEndList();
// Execute parent list
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(parentList);
// Check final matrix state - should be translate(10,0,0) * translate(1,0,0) = translate(11,0,0)
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: translate(11, 0, 0) = parent(10) + child(1)
Matrix4f expected = new Matrix4f().translate(11.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
// Compare buffers directly
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testNestedDisplayListWithPushPop() {
// Create child list with push/pop (shouldn't affect parent's matrix)
childList = GL11.glGenLists(1);
GLStateManager.glNewList(childList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); // Child transform
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glVertex3f(1, 1, 0);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
GLStateManager.glPopMatrix(); // Restore matrix to parent's state
GLStateManager.glEndList();
// Create parent list
parentList = GL11.glGenLists(1);
GLStateManager.glNewList(parentList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Parent transform
GLStateManager.glCallList(childList); // Child uses push/pop
GLStateManager.glEndList();
// Execute parent list
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(parentList);
// Check final matrix state - should still be translate(10,0,0) because child did push/pop
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: translate(10, 0, 0) only (child's transform was popped)
Matrix4f expected = new Matrix4f().translate(10.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
// Compare buffers directly
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testDeepNesting() {
// Create deeply nested lists: grandchild -> child -> parent
int grandchildList = GL11.glGenLists(1);
GLStateManager.glNewList(grandchildList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); // Grandchild: +1
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex3f(0, 0, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glVertex3f(1, 1, 0);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
GLStateManager.glEndList();
childList = GL11.glGenLists(1);
GLStateManager.glNewList(childList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Child: +10
GLStateManager.glCallList(grandchildList); // Grandchild: +1
GLStateManager.glEndList();
parentList = GL11.glGenLists(1);
GLStateManager.glNewList(parentList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(100.0f, 0.0f, 0.0f); // Parent: +100
GLStateManager.glCallList(childList); // Child: +10, Grandchild: +1
GLStateManager.glEndList();
// Execute parent list
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(parentList);
// Check final matrix state - should be 100 + 10 + 1 = 111
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: translate(111, 0, 0)
Matrix4f expected = new Matrix4f().translate(111.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
// Compare buffers directly
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch", i));
}
GLStateManager.glPopMatrix();
// Cleanup grandchild
GLStateManager.glDeleteLists(grandchildList, 1);
}
@Test
void testMismatchedPushPopInSeparateLists() {
// This test verifies that push and pop matrix operations can be split across separate display lists.
// This is a uncommon but technically valid per the spec.
// Get initial stack depth
int initialDepth = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
// Create a display list that only pushes the matrix
int matrixPushList = GL11.glGenLists(1);
GLStateManager.glNewList(matrixPushList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glEndList();
// Create a display list that only pops the matrix
int matrixPopList = GL11.glGenLists(1);
GLStateManager.glNewList(matrixPopList, GL11.GL_COMPILE);
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
// Verify initial stack depth hasn't changed after compilation
assertEquals(initialDepth, GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH), "Stack depth should be unchanged after compiling display lists");
// Call the push list - should increase stack depth
GLStateManager.glCallList(matrixPushList);
int depthAfterPush = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
assertEquals(initialDepth + 1, depthAfterPush, "Stack depth should increase by 1 after calling push list");
// Optionally do some operations here that would benefit from the pushed matrix
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
// Call the pop list - should restore stack depth
GLStateManager.glCallList(matrixPopList);
int depthAfterPop = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
assertEquals(initialDepth, depthAfterPop, "Stack depth should return to initial after calling pop list");
// Cleanup
GLStateManager.glDeleteLists(matrixPushList, 1);
GLStateManager.glDeleteLists(matrixPopList, 1);
}
}
@@ -1,322 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.joml.Matrix4f;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Stress tests for display list system.
* Verifies system stability under high load conditions.
*
* <p>Note: Tests that require actual geometry capture via Tessellator
* need the full Minecraft environment. These tests focus on matrix
* operations and display list lifecycle which work with raw GL calls.</p>
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_Stress_Test {
private final List<Integer> testLists = new ArrayList<>();
@AfterEach
void cleanup() {
for (int list : testLists) {
if (list > 0) {
GLStateManager.glDeleteLists(list, 1);
}
}
testLists.clear();
GLStateManager.glLoadIdentity();
}
private int createAndTrackList() {
int list = GL11.glGenLists(1);
testLists.add(list);
return list;
}
@Test
void testManyDisplayListsWithTransforms() {
// Create and compile many display lists with transforms
final int numLists = 500;
for (int i = 0; i < numLists; i++) {
int list = createAndTrackList();
GLStateManager.glNewList(list, GL11.GL_COMPILE);
// Each list has a unique transform
GLStateManager.glTranslatef(i * 0.1f, 0, 0);
GLStateManager.glEndList();
// Verify each list was compiled
assertTrue(DisplayListManager.displayListExists(list),
"Display list " + list + " should exist after compilation");
}
// Verify all lists still exist
for (int list : testLists) {
assertTrue(DisplayListManager.displayListExists(list),
"All " + numLists + " display lists should exist");
}
}
@Test
void testManyTransformsInSingleList() {
// Create a single display list with many transform operations
final int numTransforms = 1000;
int list = createAndTrackList();
GLStateManager.glNewList(list, GL11.GL_COMPILE);
// Many push/pop pairs with transforms
for (int i = 0; i < numTransforms; i++) {
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(i * 0.001f, 0, 0);
GLStateManager.glRotatef(i * 0.36f, 0, 1, 0);
GLStateManager.glPopMatrix();
}
// Final transform that should be the result
GLStateManager.glTranslatef(42.0f, 0, 0);
GLStateManager.glEndList();
// Execute and verify final transform
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(list);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// All push/pop pairs cancel out, only final translate remains
assertEquals(42.0f, actualBuf.get(12), 0.0001f,
"After many push/pop pairs, only final transform should remain");
GLStateManager.glPopMatrix();
}
@Test
void testRapidCompileDeleteCycle() {
// Rapidly create and delete display lists to test resource management
final int cycles = 100;
for (int cycle = 0; cycle < cycles; cycle++) {
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glTranslatef(cycle, 0, 0);
GLStateManager.glEndList();
// Immediately delete
GLStateManager.glDeleteLists(list, 1);
// Verify it's gone
assertFalse(DisplayListManager.displayListExists(list),
"Display list should be deleted after glDeleteLists");
}
}
@Test
void testDeepNestingChain() {
// Create a chain of display lists that call each other
final int chainLength = 50;
int[] chain = new int[chainLength];
// Create from innermost to outermost
for (int i = 0; i < chainLength; i++) {
chain[i] = createAndTrackList();
GLStateManager.glNewList(chain[i], GL11.GL_COMPILE);
// Each list translates by 1 and calls the previous list (if any)
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
if (i > 0) {
GLStateManager.glCallList(chain[i - 1]);
}
GLStateManager.glEndList();
}
// Execute the outermost list
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(chain[chainLength - 1]);
// Final matrix should have translation = chainLength (each list adds 1)
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
Matrix4f expected = new Matrix4f().translate(chainLength, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch for chain of %d lists", i, chainLength));
}
GLStateManager.glPopMatrix();
}
@Test
void testManyPushPopOperations() {
// Stress test push/pop stack operations
int list = createAndTrackList();
GLStateManager.glNewList(list, GL11.GL_COMPILE);
// Go deep into the stack
final int stackDepth = 30; // GL minimum is 32
for (int i = 0; i < stackDepth; i++) {
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
}
// Pop all the way back
for (int i = 0; i < stackDepth; i++) {
GLStateManager.glPopMatrix();
}
// Add final known transform
GLStateManager.glTranslatef(99.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Execute and verify
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(list);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// All pushes and pops cancel out, only final 99 translate remains
assertEquals(99.0f, actualBuf.get(12), 0.0001f,
"After balanced push/pop, only final transform should remain");
GLStateManager.glPopMatrix();
}
@Test
void testRapidListSwitching() {
// Create multiple lists and rapidly switch between them
final int numLists = 20;
int[] lists = new int[numLists];
// Create all lists with unique transforms
for (int i = 0; i < numLists; i++) {
lists[i] = createAndTrackList();
GLStateManager.glNewList(lists[i], GL11.GL_COMPILE);
GLStateManager.glTranslatef(i + 1, 0, 0); // List i translates by (i+1)
GLStateManager.glEndList();
}
// Rapidly switch between calling different lists
for (int iteration = 0; iteration < 100; iteration++) {
for (int i = 0; i < numLists; i++) {
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(lists[i]);
// Verify correct transform was applied
FloatBuffer buf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf);
assertEquals(i + 1, buf.get(12), 0.0001f,
"List " + i + " should translate by " + (i + 1));
GLStateManager.glPopMatrix();
}
}
}
@Test
void testRecompileSameId() {
// Test recompiling a display list with the same ID
int list = createAndTrackList();
// First compilation
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify first compilation
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(list);
FloatBuffer buf1 = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf1);
assertEquals(5.0f, buf1.get(12), 0.0001f, "First compilation should translate by 5");
GLStateManager.glPopMatrix();
// Recompile with different transform
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify recompilation
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(list);
FloatBuffer buf2 = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf2);
assertEquals(10.0f, buf2.get(12), 0.0001f, "Recompilation should translate by 10");
GLStateManager.glPopMatrix();
}
@Test
void testComplexTransformSequence() {
// Test a complex sequence of transforms that could expose numerical issues
int list = createAndTrackList();
GLStateManager.glNewList(list, GL11.GL_COMPILE);
// Apply transforms that together should result in a known value
GLStateManager.glTranslatef(100.0f, 0.0f, 0.0f);
GLStateManager.glRotatef(90.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glTranslatef(50.0f, 0.0f, 0.0f); // This goes in Y direction after rotate
GLStateManager.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); // Cancel the rotation
GLStateManager.glTranslatef(25.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(list);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Build expected with JOML
Matrix4f expected = new Matrix4f()
.translate(100.0f, 0.0f, 0.0f)
.rotate((float) Math.toRadians(90.0f), 0.0f, 0.0f, 1.0f)
.translate(50.0f, 0.0f, 0.0f)
.rotate((float) Math.toRadians(-90.0f), 0.0f, 0.0f, 1.0f)
.translate(25.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.001f,
String.format("Matrix[%d] mismatch in complex transform", i));
}
GLStateManager.glPopMatrix();
}
}
@@ -1,960 +0,0 @@
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;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Tests for transform collapsing optimization in display lists. */
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_TransformCollapsing_Test {
private int testList = -1;
private int nestedList = -1;
@AfterEach
void cleanup() {
if (testList > 0) {
GLStateManager.glDeleteLists(testList, 1);
testList = -1;
}
if (nestedList > 0) {
GLStateManager.glDeleteLists(nestedList, 1);
nestedList = -1;
}
GLStateManager.glLoadIdentity();
}
// ==================== Transform Collapsing Tests ====================
@Test
void testConsecutiveTransformsCollapseToSingleMultMatrix() {
// Multiple consecutive transforms should collapse to one MultMatrix in optimized list
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// 5 consecutive transforms
GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f);
GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glTranslatef(-0.5f, -0.5f, -0.5f);
GLStateManager.glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify optimization: should have collapsed to 1 MultMatrix
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
int individualTransformCount = counts.getOrDefault(GLCommand.TRANSLATE, 0)
+ counts.getOrDefault(GLCommand.ROTATE, 0)
+ counts.getOrDefault(GLCommand.SCALE, 0);
assertEquals(1, multMatrixCount,
"5 consecutive transforms should collapse to 1 MultMatrix");
assertEquals(0, individualTransformCount,
"No individual transform commands should remain in optimized list");
// Verify behavioral correctness: matrix state should match expected
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
Matrix4f expected = new Matrix4f()
.translate(1.0f, 2.0f, 3.0f)
.rotate((float) Math.toRadians(45.0f), 0.0f, 1.0f, 0.0f)
.scale(2.0f, 2.0f, 2.0f)
.translate(-0.5f, -0.5f, -0.5f)
.rotate((float) Math.toRadians(30.0f), 1.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch after collapsed transforms", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testPushPopPreservesStackSemantics() {
// Push/Pop should maintain proper stack semantics with collapsed transforms
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Outer translate
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); // Inner translate (isolated)
GLStateManager.glRotatef(90.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glPopMatrix();
GLStateManager.glTranslatef(0.0f, 3.0f, 0.0f); // After pop
GLStateManager.glEndList();
// Verify optimization: should have Push, Pop, and collapsed MultMatrix commands
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Int2IntMap counts = compiled.getCommandCounts();
int pushCount = counts.getOrDefault(GLCommand.PUSH_MATRIX, 0);
int popCount = counts.getOrDefault(GLCommand.POP_MATRIX, 0);
assertEquals(1, pushCount, "Should have exactly 1 PushMatrix");
assertEquals(1, popCount, "Should have exactly 1 PopMatrix");
// Verify behavioral correctness
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: translate(10,0,0) then translate(0,3,0) = translate(10,3,0)
// The inner push/pop isolates the (5,0,0) translate and rotation
Matrix4f expected = new Matrix4f()
.translate(10.0f, 0.0f, 0.0f)
.translate(0.0f, 3.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch - push/pop should isolate inner transforms", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testNestedPushPopWithTransforms() {
// Nested push/pop with transforms at each level
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); // Level 0
GLStateManager.glPushMatrix(); // Enter level 1
GLStateManager.glTranslatef(2.0f, 0.0f, 0.0f);
GLStateManager.glPushMatrix(); // Enter level 2
GLStateManager.glTranslatef(3.0f, 0.0f, 0.0f);
GLStateManager.glPopMatrix(); // Back to level 1
GLStateManager.glTranslatef(4.0f, 0.0f, 0.0f); // At level 1
GLStateManager.glPopMatrix(); // Back to level 0
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); // At level 0
GLStateManager.glEndList();
// Verify behavioral correctness
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Final state: translate(1,0,0) + translate(5,0,0) = translate(6,0,0)
// Level 1 and 2 transforms are isolated by push/pop
Matrix4f expected = new Matrix4f()
.translate(1.0f, 0.0f, 0.0f)
.translate(5.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
assertEquals(expectedBuf.get(12), actualBuf.get(12), 0.0001f,
"X translation should be 6.0 (1+5, inner transforms isolated)");
GLStateManager.glPopMatrix(); // Balance the push from line 185
}
@Test
void testCallListFlushesTransform() {
// Create a nested display list
nestedList = GL11.glGenLists(1);
GLStateManager.glNewList(nestedList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(100.0f, 0.0f, 0.0f); // Large translate to verify it's applied
GLStateManager.glEndList();
// Create parent list that transforms then calls nested list
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f); // Before CallList
GLStateManager.glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glCallList(nestedList); // Barrier - should flush transforms
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); // After CallList
GLStateManager.glEndList();
// Verify optimization: MultMatrix should be emitted before CallList
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
IntList opcodes = compiled.getCommandOpcodes();
// Find positions of MultMatrix and CallList
int multMatrixIndex = opcodes.indexOf(GLCommand.MULT_MATRIX);
int callListIndex = opcodes.indexOf(GLCommand.CALL_LIST);
assertTrue(multMatrixIndex >= 0, "Should have MultMatrix command");
assertTrue(callListIndex >= 0, "Should have CallList command");
assertTrue(multMatrixIndex < callListIndex,
"MultMatrix should be emitted BEFORE CallList (transform flush at barrier)");
// Verify behavioral correctness
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Build expected: translate(10,0,0) * rotate(90,Y) * translate(100,0,0) * translate(1,0,0)
// After 90-degree Y rotation, X axis points into -Z, so nested translate goes along -Z
Matrix4f expected = new Matrix4f()
.translate(10.0f, 0.0f, 0.0f)
.rotate((float) Math.toRadians(90.0f), 0.0f, 1.0f, 0.0f)
.translate(100.0f, 0.0f, 0.0f)
.translate(1.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch - nested list should see parent's transformed state", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testIdentityTransformNotEmitted() {
// A display list with only identity-equivalent transforms should not emit MultMatrix
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// These cancel out to identity
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glTranslatef(-5.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
// If compiled is null, the list is empty (correct - no commands needed)
// If compiled exists, verify no MultMatrix commands
int multMatrixCount = 0;
if (compiled != null) {
Int2IntMap counts = compiled.getCommandCounts();
multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
}
assertEquals(0, multMatrixCount,
"Identity-equivalent transforms should not emit MultMatrix");
}
@Test
void testTransformBetweenDrawsCreatesSeparateBatches() {
// This test verifies that draws with different transforms are not batched together
// Note: Without actual Tessellator integration, we can only verify command structure
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// Simulate: Transform A, Draw, Transform B, Draw
// The draws should NOT be in the same batch
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
// (Would have a draw here in real usage)
GLStateManager.glTranslatef(2.0f, 0.0f, 0.0f);
// (Would have another draw here)
GLStateManager.glEndList();
// Verify the transforms are accumulated correctly
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Total translation should be 3.0 (1+2)
assertEquals(3.0f, actualBuf.get(12), 0.0001f,
"Consecutive translates should accumulate");
GLStateManager.glPopMatrix();
}
@Test
void testLoadIdentityResetsAccumulation() {
// LoadIdentity should reset accumulated transforms
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(100.0f, 100.0f, 100.0f); // Big translate
GLStateManager.glLoadIdentity(); // Reset
GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f); // New translate
GLStateManager.glEndList();
// Verify: final state should only have the second translate
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
assertEquals(1.0f, actualBuf.get(12), 0.0001f, "X should be 1.0 (LoadIdentity reset)");
assertEquals(2.0f, actualBuf.get(13), 0.0001f, "Y should be 2.0 (LoadIdentity reset)");
assertEquals(3.0f, actualBuf.get(14), 0.0001f, "Z should be 3.0 (LoadIdentity reset)");
GLStateManager.glPopMatrix();
}
@Test
void testMultMatrixAccumulation() {
// MultMatrix should be accumulated like other transforms
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
// Create a rotation matrix and multiply
Matrix4f rotMatrix = new Matrix4f().rotate((float) Math.toRadians(90.0f), 0.0f, 1.0f, 0.0f);
FloatBuffer rotBuf = BufferUtils.createFloatBuffer(16);
rotMatrix.get(rotBuf);
rotBuf.rewind();
GLStateManager.glMultMatrix(rotBuf);
GLStateManager.glTranslatef(2.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify optimization: should collapse to 1 MultMatrix
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
assertEquals(1, multMatrixCount,
"Translate + MultMatrix + Translate should collapse to 1 MultMatrix");
// Verify behavioral correctness
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
Matrix4f expected = new Matrix4f()
.translate(1.0f, 0.0f, 0.0f)
.rotate((float) Math.toRadians(90.0f), 0.0f, 1.0f, 0.0f)
.translate(2.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] mismatch for MultMatrix accumulation", i));
}
GLStateManager.glPopMatrix();
}
// ==================== Batcher Flush Ordering Tests ====================
@Test
void testDrawsBeforePushMatrixAreEmittedBeforePush() {
// This test verifies that draws occurring before a PushMatrix are flushed
// before the PushMatrix command, not delayed until later.
// This was a bug where the batcher wasn't flushed at PushMatrix.
// Create a list with: Transform, (implicit draw would go here), PushMatrix, Transform, PopMatrix
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// Outer transform
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
// Note: If there was a draw here, it should be emitted BEFORE PushMatrix
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); // Inner transform
GLStateManager.glPopMatrix();
// Final transform after pop
GLStateManager.glTranslatef(2.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify the command structure
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
IntList opcodes = compiled.getCommandOpcodes();
// Find indices of key commands
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX);
// Count MultMatrix commands before first PushMatrix
int multMatrixBeforePushCount = 0;
for (int i = 0; i < opcodes.size() && i < pushIndex; i++) {
if (opcodes.get(i) == GLCommand.MULT_MATRIX) {
multMatrixBeforePushCount++;
}
}
assertTrue(pushIndex >= 0, "Should have PushMatrix command");
assertTrue(popIndex >= 0, "Should have PopMatrix command");
assertTrue(pushIndex < popIndex, "PushMatrix should come before PopMatrix");
// The outer translate(1,0,0) should be emitted as MultMatrix before PushMatrix
assertTrue(multMatrixBeforePushCount >= 1,
"Transform before PushMatrix should be emitted before the Push");
// Verify behavioral correctness: final state should be translate(1,0,0) + translate(2,0,0) = translate(3,0,0)
// The inner translate(5,0,0) is isolated by push/pop
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
assertEquals(3.0f, actualBuf.get(12), 0.0001f,
"X translation should be 3.0 (1+2, inner transform isolated by push/pop)");
GLStateManager.glPopMatrix();
}
@Test
void testDrawsBeforePopMatrixAreEmittedBeforePop() {
// Verify draws inside a push/pop block are emitted before the pop
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f);
// Draws here should be emitted before PopMatrix
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
IntList opcodes = compiled.getCommandOpcodes();
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX);
assertTrue(pushIndex >= 0, "Should have PushMatrix");
assertTrue(popIndex >= 0, "Should have PopMatrix");
assertTrue(pushIndex < popIndex, "Push should come before Pop");
// The inner translate should be emitted between push and pop (or collapsed to residual)
// At minimum, the structure should be valid
assertTrue(popIndex > pushIndex, "PopMatrix should follow PushMatrix");
}
// ==================== LoadMatrix Tests ====================
@Test
void testLoadMatrixSetsAbsoluteTransform() {
// LoadMatrix should set an absolute matrix, not multiply
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// First, apply a large transform
GLStateManager.glTranslatef(100.0f, 200.0f, 300.0f);
// Then load a specific matrix (should replace, not multiply)
Matrix4f loadedMatrix = new Matrix4f()
.translate(1.0f, 2.0f, 3.0f)
.rotate((float) Math.toRadians(45.0f), 0.0f, 1.0f, 0.0f);
FloatBuffer loadBuf = BufferUtils.createFloatBuffer(16);
loadedMatrix.get(loadBuf);
loadBuf.rewind();
GLStateManager.glLoadMatrix(loadBuf);
GLStateManager.glEndList();
// Verify the LOAD_MATRIX command is present
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
Int2IntMap counts = compiled.getCommandCounts();
int loadMatrixCount = counts.getOrDefault(GLCommand.LOAD_MATRIX, 0);
assertEquals(1, loadMatrixCount,
"Should have exactly 1 LoadMatrix command (can't be absorbed)");
// Verify behavioral correctness: matrix should equal the loaded matrix
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
loadedMatrix.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] should match loaded matrix (not multiplied)", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testLoadMatrixResetsRelativeTransform() {
// After LoadMatrix, subsequent transforms should be relative to the loaded matrix
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// Load a rotation matrix
Matrix4f loadedMatrix = new Matrix4f()
.rotate((float) Math.toRadians(90.0f), 0.0f, 1.0f, 0.0f);
FloatBuffer loadBuf = BufferUtils.createFloatBuffer(16);
loadedMatrix.get(loadBuf);
loadBuf.rewind();
GLStateManager.glLoadMatrix(loadBuf);
// Then translate - this should be relative to the loaded matrix
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f);
GLStateManager.glEndList();
// Verify behavioral correctness
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Expected: loadedMatrix * translate(10,0,0)
Matrix4f expected = new Matrix4f(loadedMatrix).translate(10.0f, 0.0f, 0.0f);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
expected.get(expectedBuf);
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d] - transform after LoadMatrix should be relative to loaded matrix", i));
}
GLStateManager.glPopMatrix();
}
@Test
void testLoadMatrixThenLoadIdentity() {
// LoadMatrix followed by LoadIdentity should result in identity
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// Load a complex matrix
Matrix4f loadedMatrix = new Matrix4f()
.translate(50.0f, 60.0f, 70.0f)
.rotate((float) Math.toRadians(45.0f), 1.0f, 1.0f, 0.0f);
FloatBuffer loadBuf = BufferUtils.createFloatBuffer(16);
loadedMatrix.get(loadBuf);
loadBuf.rewind();
GLStateManager.glLoadMatrix(loadBuf);
// Then reset to identity
GLStateManager.glLoadIdentity();
// Then apply a simple translate
GLStateManager.glTranslatef(1.0f, 2.0f, 3.0f);
GLStateManager.glEndList();
// Verify: final state should just be translate(1,2,3)
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
assertEquals(1.0f, actualBuf.get(12), 0.0001f, "X should be 1.0");
assertEquals(2.0f, actualBuf.get(13), 0.0001f, "Y should be 2.0");
assertEquals(3.0f, actualBuf.get(14), 0.0001f, "Z should be 3.0");
GLStateManager.glPopMatrix();
}
@Test
void testMultipleLoadMatrixCalls() {
// Multiple LoadMatrix calls should each be recorded
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// First load
Matrix4f matrix1 = new Matrix4f().translate(10.0f, 0.0f, 0.0f);
FloatBuffer buf1 = BufferUtils.createFloatBuffer(16);
matrix1.get(buf1);
buf1.rewind();
GLStateManager.glLoadMatrix(buf1);
// Second load (replaces first)
Matrix4f matrix2 = new Matrix4f().translate(0.0f, 20.0f, 0.0f);
FloatBuffer buf2 = BufferUtils.createFloatBuffer(16);
matrix2.get(buf2);
buf2.rewind();
GLStateManager.glLoadMatrix(buf2);
GLStateManager.glEndList();
// Verify: final state should be matrix2
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
assertEquals(0.0f, actualBuf.get(12), 0.0001f, "X should be 0.0 (from second LoadMatrix)");
assertEquals(20.0f, actualBuf.get(13), 0.0001f, "Y should be 20.0 (from second LoadMatrix)");
GLStateManager.glPopMatrix();
}
// ==================== Immediate Mode with Transforms Tests ====================
@Test
void testImmediateModeDrawCommandStructure() {
// Verifies MultMatrix emitted before DrawRange, push/pop ordering correct
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glScalef(0.25f, 0.25f, 0.25f);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(2.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(2.0f, 2.0f, 0.0f);
GLStateManager.glVertex3f(0.0f, 2.0f, 0.0f);
GLStateManager.glEnd();
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled);
IntList opcodes = compiled.getCommandOpcodes();
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX);
int multMatrixIndex = opcodes.indexOf(GLCommand.MULT_MATRIX);
int drawRangeIndex = opcodes.indexOf(GLCommand.DRAW_RANGE);
assertTrue(pushIndex < multMatrixIndex, "Push before MultMatrix");
assertTrue(multMatrixIndex < drawRangeIndex, "MultMatrix before DrawRange");
assertTrue(drawRangeIndex < popIndex, "DrawRange before Pop");
}
@Test
void testImmediateModeDrawMatrixValues() {
// Verifies matrix values correct after playback with translate + scale
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(100.0f, 50.0f, 0.0f);
GLStateManager.glScalef(0.5f, 0.5f, 1.0f);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(16.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(16.0f, 16.0f, 0.0f);
GLStateManager.glVertex3f(0.0f, 16.0f, 0.0f);
GLStateManager.glEnd();
GLStateManager.glEndList();
// Verify transforms collapsed
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Int2IntMap counts = compiled.getCommandCounts();
assertEquals(1, counts.getOrDefault(GLCommand.MULT_MATRIX, 0), "Translate+Scale -> 1 MultMatrix");
assertEquals(0, counts.getOrDefault(GLCommand.TRANSLATE, 0), "No individual Translate");
assertEquals(0, counts.getOrDefault(GLCommand.SCALE, 0), "No individual Scale");
// Verify matrix values after playback
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf);
assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X");
assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y");
assertEquals(1.0f, matrixBuf.get(10), 0.0001f, "Scale Z");
assertEquals(100.0f, matrixBuf.get(12), 0.0001f, "Translate X");
assertEquals(50.0f, matrixBuf.get(13), 0.0001f, "Translate Y");
GLStateManager.glPopMatrix();
}
// ==================== Cross-Mode Transform Collapsing Tests ====================
@Test
void testTransformsAcrossMatrixModeSwitch() {
// Transforms must not leak across matrix mode boundaries
// Compute expected results via GLSM (same path as display list playback)
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glTranslatef(3.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
FloatBuffer expectedMV = BufferUtils.createFloatBuffer(16);
FloatBuffer expectedProj = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedMV);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, expectedProj);
// Reset and test via display list
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f);
GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glTranslatef(3.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glEndList();
GLStateManager.glCallList(testList);
FloatBuffer actualMV = BufferUtils.createFloatBuffer(16);
FloatBuffer actualProj = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualMV);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, actualProj);
for (int i = 0; i < 16; i++) {
assertEquals(expectedMV.get(i), actualMV.get(i), 0.0001f, "MODELVIEW[" + i + "]");
assertEquals(expectedProj.get(i), actualProj.get(i), 0.0001f, "PROJECTION[" + i + "]");
}
// Cleanup
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void testBarrierCommandsBetweenScaleAndDraw() {
// State commands between transform and draw must not break transform capture
for (int mode : new int[]{GL11.GL_COMPILE, GL11.GL_COMPILE_AND_EXECUTE}) {
if (testList > 0) {
GLStateManager.glDeleteLists(testList, 1);
}
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, mode);
GLStateManager.glScalef(0.5f, 0.5f, 1.0f);
// Barrier commands between scale and draw
GLStateManager.glDepthMask(true);
GLStateManager.disableLighting();
GLStateManager.enableTexture();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(1.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(1.0f, 1.0f, 0.0f);
GLStateManager.glVertex3f(0.0f, 1.0f, 0.0f);
GLStateManager.glEnd();
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled);
Int2IntMap counts = compiled.getCommandCounts();
assertEquals(1, counts.getOrDefault(GLCommand.MULT_MATRIX, 0), "1 MultMatrix for mode " + mode);
assertEquals(1, counts.getOrDefault(GLCommand.DRAW_RANGE, 0), "1 DrawRange for mode " + mode);
IntList opcodes = compiled.getCommandOpcodes();
assertTrue(opcodes.indexOf(GLCommand.MULT_MATRIX) < opcodes.indexOf(GLCommand.DRAW_RANGE),
"MultMatrix before DrawRange for mode " + mode);
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf);
assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X for mode " + mode);
assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y for mode " + mode);
GLStateManager.glPopMatrix();
}
}
// ==================== Optimizer Push/Pop Reset Tests ====================
@Test
void testOptimizerResetsAfterPushMatrix() {
// Optimizer must reset after PUSH_MATRIX to avoid spurious inverse transform emission
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
// T1: transforms before push (collapsed)
GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glPushMatrix();
// T2: transforms after push (collapsed separately)
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f);
GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glBegin(GL11.GL_QUADS);
GLStateManager.glVertex3f(0.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(1.0f, 0.0f, 0.0f);
GLStateManager.glVertex3f(1.0f, 1.0f, 0.0f);
GLStateManager.glVertex3f(0.0f, 1.0f, 0.0f);
GLStateManager.glEnd();
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled);
Int2IntMap counts = compiled.getCommandCounts();
IntList opcodes = compiled.getCommandOpcodes();
// Should have exactly 2 MULT_MATRIX (T1 before push, T2 after push)
// Bug would produce 3 (T1, T2, spurious T1^-1)
assertEquals(2, counts.getOrDefault(GLCommand.MULT_MATRIX, 0),
"2 MULT_MATRIX expected (T1 before push, T2 after push)");
// Verify ordering
int firstMultMatrix = opcodes.indexOf(GLCommand.MULT_MATRIX);
int pushIndex = opcodes.indexOf(GLCommand.PUSH_MATRIX);
int drawIndex = opcodes.indexOf(GLCommand.DRAW_RANGE);
int popIndex = opcodes.indexOf(GLCommand.POP_MATRIX);
assertTrue(firstMultMatrix < pushIndex, "T1 before PUSH");
assertTrue(pushIndex < drawIndex, "PUSH before DRAW");
assertTrue(drawIndex < popIndex, "DRAW before POP");
// Verify final matrix after pop = T1
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
GLStateManager.glCallList(testList);
FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf);
assertEquals(2.0f, matrixBuf.get(0), 0.0001f, "Scale X after pop");
assertEquals(2.0f, matrixBuf.get(5), 0.0001f, "Scale Y after pop");
assertEquals(5.0f, matrixBuf.get(12), 0.0001f, "Translate X after pop");
GLStateManager.glPopMatrix();
}
@Test
void testTransformCollapsingEquivalence() {
// Core equivalence test: verify that collapsed transforms produce
// the exact same result as executing transforms sequentially.
//
// This tests the fundamental invariant of the optimization.
// Use axis-aligned rotations to minimize float/double precision differences.
// Transform sequence: translate, rotate around Y, scale, rotate around X, translate
final float tx1 = 5.0f, ty1 = 3.0f, tz1 = -2.0f;
final float angle1 = 45.0f;
final float sx = 1.5f, sy = 0.8f, sz = 2.0f;
final float angle2 = 30.0f;
final float tx2 = -1.0f, ty2 = 4.0f, tz2 = 0.5f;
// Execute directly via GLSM
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glTranslatef(tx1, ty1, tz1);
GLStateManager.glRotatef(angle1, 0.0f, 1.0f, 0.0f); // Y-axis rotation
GLStateManager.glScalef(sx, sy, sz);
GLStateManager.glRotatef(angle2, 1.0f, 0.0f, 0.0f); // X-axis rotation
GLStateManager.glTranslatef(tx2, ty2, tz2);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedBuf);
// Reset and execute via display list
GLStateManager.glLoadIdentity();
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glTranslatef(tx1, ty1, tz1);
GLStateManager.glRotatef(angle1, 0.0f, 1.0f, 0.0f);
GLStateManager.glScalef(sx, sy, sz);
GLStateManager.glRotatef(angle2, 1.0f, 0.0f, 0.0f);
GLStateManager.glTranslatef(tx2, ty2, tz2);
GLStateManager.glEndList();
GLStateManager.glCallList(testList);
FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16);
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf);
// Verify equivalence
for (int i = 0; i < 16; i++) {
assertEquals(expectedBuf.get(i), actualBuf.get(i), 0.0001f,
String.format("Matrix[%d]: collapsed transform must equal sequential execution", i));
}
GLStateManager.glLoadIdentity();
}
}
@@ -1,313 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_UnitTest {
@Test
void testDisplayListCompileCall() {
verifyState(GL11.GL_LIGHTING, false, "GL_LIGHTING Initial State");
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glEnable(GL11.GL_LIGHTING);
GLStateManager.glEndList();
verifyState(GL11.GL_LIGHTING, false, "GL_LIGHTING Post Display List Compile");
GLStateManager.glCallList(list);
verifyState(GL11.GL_LIGHTING, true, "GL_LIGHTING Post Display List Call");
// Reset state that we changed during test
GLStateManager.glDisable(GL11.GL_LIGHTING);
}
@Test
void testDisplayListCompileExecute() {
verifyState(GL11.GL_LIGHTING, false, "GL_LIGHTING Initial State");
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glEnable(GL11.GL_LIGHTING);
GLStateManager.glEndList();
verifyState(GL11.GL_LIGHTING, true, "GL_LIGHTING Post Display List Compile and Execute");
// Reset state that we changed during test
GLStateManager.glDisable(GL11.GL_LIGHTING);
}
// ==================== CullFace Tests ====================
@Test
void testCullFaceInDisplayList() {
// Get initial cull face mode
int initialMode = GL11.glGetInteger(GL11.GL_CULL_FACE_MODE);
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glCullFace(GL11.GL_FRONT);
GLStateManager.glEndList();
// After compile, mode should be unchanged
assertEquals(initialMode, GL11.glGetInteger(GL11.GL_CULL_FACE_MODE), "CullFace mode should be unchanged after GL_COMPILE");
// Call the display list
GLStateManager.glCallList(list);
// Now mode should be GL_FRONT
assertEquals(GL11.GL_FRONT, GL11.glGetInteger(GL11.GL_CULL_FACE_MODE), "CullFace mode should be GL_FRONT after calling display list");
// Cleanup
GLStateManager.glCullFace(GL11.GL_BACK); // Reset to default
GLStateManager.glDeleteLists(list, 1);
}
@Test
void testCullFaceCompileAndExecute() {
// Get initial cull face mode
int initialMode = GL11.glGetInteger(GL11.GL_CULL_FACE_MODE);
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glCullFace(GL11.GL_FRONT_AND_BACK);
GLStateManager.glEndList();
// After compile and execute, mode should be changed
assertEquals(GL11.GL_FRONT_AND_BACK, GL11.glGetInteger(GL11.GL_CULL_FACE_MODE), "CullFace mode should be GL_FRONT_AND_BACK after GL_COMPILE_AND_EXECUTE");
// Cleanup
GLStateManager.glCullFace(GL11.GL_BACK);
GLStateManager.glDeleteLists(list, 1);
}
// ==================== LogicOp Tests ====================
@Test
void testLogicOpInDisplayList() {
// Get initial logic op
int initialOp = GL11.glGetInteger(GL11.GL_LOGIC_OP_MODE);
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glLogicOp(GL11.GL_XOR);
GLStateManager.glEndList();
// After compile, op should be unchanged
assertEquals(initialOp, GL11.glGetInteger(GL11.GL_LOGIC_OP_MODE), "LogicOp should be unchanged after GL_COMPILE");
// Call the display list
GLStateManager.glCallList(list);
// Now op should be GL_XOR
assertEquals(GL11.GL_XOR, GL11.glGetInteger(GL11.GL_LOGIC_OP_MODE), "LogicOp should be GL_XOR after calling display list");
// Cleanup
GLStateManager.glLogicOp(GL11.GL_COPY); // Reset to default
GLStateManager.glDeleteLists(list, 1);
}
@Test
void testLogicOpCompileAndExecute() {
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE_AND_EXECUTE);
GLStateManager.glLogicOp(GL11.GL_INVERT);
GLStateManager.glEndList();
// After compile and execute, op should be changed
assertEquals(GL11.GL_INVERT, GL11.glGetInteger(GL11.GL_LOGIC_OP_MODE), "LogicOp should be GL_INVERT after GL_COMPILE_AND_EXECUTE");
// Cleanup
GLStateManager.glLogicOp(GL11.GL_COPY);
GLStateManager.glDeleteLists(list, 1);
}
@Test
void testMultipleStateChangesInDisplayList() {
// Test that multiple state commands work together
int list = GL11.glGenLists(1);
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glCullFace(GL11.GL_FRONT);
GLStateManager.glLogicOp(GL11.GL_AND);
GLStateManager.glEnable(GL11.GL_LIGHTING);
GLStateManager.glEndList();
// Call the list
GLStateManager.glCallList(list);
// Verify all states changed
assertEquals(GL11.GL_FRONT, GL11.glGetInteger(GL11.GL_CULL_FACE_MODE), "CullFace should be GL_FRONT");
assertEquals(GL11.GL_AND, GL11.glGetInteger(GL11.GL_LOGIC_OP_MODE), "LogicOp should be GL_AND");
verifyState(GL11.GL_LIGHTING, true, "GL_LIGHTING should be enabled");
// Cleanup
GLStateManager.glCullFace(GL11.GL_BACK);
GLStateManager.glLogicOp(GL11.GL_COPY);
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);
}
}
@@ -1,208 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.joml.Matrix4f;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests that GLStateManager's GLU implementations produce the same matrices as the equivalent JOML operations.
*/
@ExtendWith(AngelicaExtension.class)
public class GLSM_GLU_UnitTest {
private static final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
private Matrix4f getModelviewMatrix() {
buffer.clear();
GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buffer);
return new Matrix4f(buffer);
}
private Matrix4f getProjectionMatrix() {
buffer.clear();
GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, buffer);
return new Matrix4f(buffer);
}
private void assertMatrixEquals(Matrix4f expected, Matrix4f actual, String message) {
assertTrue(expected.equals(actual, 0.001f), () -> message + "\nExpected:\n" + expected + "\nActual:\n" + actual);
}
@Test
void gluPerspective_matchesJOML() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.gluPerspective(60.0f, 1.5f, 0.1f, 1000.0f);
Matrix4f expected = new Matrix4f().perspective((float) Math.toRadians(60.0f), 1.5f, 0.1f, 1000.0f);
assertMatrixEquals(expected, getProjectionMatrix(), "gluPerspective standard");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void gluPerspective_accumulates() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glScalef(2.0f, 1.0f, 1.0f);
GLStateManager.gluPerspective(90.0f, 1.0f, 1.0f, 100.0f);
Matrix4f expected = new Matrix4f()
.scale(2.0f, 1.0f, 1.0f)
.perspective((float) Math.toRadians(90.0f), 1.0f, 1.0f, 100.0f);
assertMatrixEquals(expected, getProjectionMatrix(), "gluPerspective after scale");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void gluLookAt_matchesJOML() {
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.gluLookAt(
0.0f, 0.0f, 5.0f, // eye
0.0f, 0.0f, 0.0f, // center
0.0f, 1.0f, 0.0f); // up
Matrix4f expected = new Matrix4f().lookAt(
0.0f, 0.0f, 5.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
assertMatrixEquals(expected, getModelviewMatrix(), "gluLookAt simple");
}
@Test
void gluLookAt_offAxis() {
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.gluLookAt(
3.0f, 4.0f, 5.0f,
1.0f, 2.0f, 0.0f,
0.0f, 1.0f, 0.0f);
Matrix4f expected = new Matrix4f().lookAt(
3.0f, 4.0f, 5.0f,
1.0f, 2.0f, 0.0f,
0.0f, 1.0f, 0.0f);
assertMatrixEquals(expected, getModelviewMatrix(), "gluLookAt off-axis");
}
@Test
void gluLookAt_accumulates() {
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glTranslatef(10.0f, 0.0f, 0.0f);
GLStateManager.gluLookAt(
0.0f, 0.0f, 5.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
Matrix4f expected = new Matrix4f()
.translate(10.0f, 0.0f, 0.0f)
.lookAt(0.0f, 0.0f, 5.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
assertMatrixEquals(expected, getModelviewMatrix(), "gluLookAt after translate");
}
@Test
void gluOrtho2D_matchesJOML() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.gluOrtho2D(0.0f, 800.0f, 0.0f, 600.0f);
Matrix4f expected = new Matrix4f().ortho(0.0f, 800.0f, 0.0f, 600.0f, -1.0f, 1.0f);
assertMatrixEquals(expected, getProjectionMatrix(), "gluOrtho2D");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void gluPickMatrix_matchesManual() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
IntBuffer viewport = BufferUtils.createIntBuffer(4);
viewport.put(0, 0); // x
viewport.put(1, 0); // y
viewport.put(2, 800); // width
viewport.put(3, 600); // height
float x = 400.0f, y = 300.0f, deltaX = 5.0f, deltaY = 5.0f;
GLStateManager.gluPickMatrix(x, y, deltaX, deltaY, viewport);
// Reproduce the expected result: translate then scale
Matrix4f expected = new Matrix4f()
.translate(
(800 - 2 * (x - 0)) / deltaX,
(600 - 2 * (y - 0)) / deltaY,
0.0f)
.scale(
800.0f / deltaX,
600.0f / deltaY,
1.0f);
assertMatrixEquals(expected, getProjectionMatrix(), "gluPickMatrix center");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void gluPickMatrix_offCenter() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
IntBuffer viewport = BufferUtils.createIntBuffer(4);
viewport.put(0, 100);
viewport.put(1, 50);
viewport.put(2, 640);
viewport.put(3, 480);
float x = 200.0f, y = 150.0f, deltaX = 10.0f, deltaY = 10.0f;
GLStateManager.gluPickMatrix(x, y, deltaX, deltaY, viewport);
Matrix4f expected = new Matrix4f()
.translate(
(640 - 2 * (x - 100)) / deltaX,
(480 - 2 * (y - 50)) / deltaY,
0.0f)
.scale(
640.0f / deltaX,
480.0f / deltaY,
1.0f);
assertMatrixEquals(expected, getProjectionMatrix(), "gluPickMatrix off-center viewport");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
@Test
void gluPickMatrix_zeroSize_noOp() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
IntBuffer viewport = BufferUtils.createIntBuffer(4);
viewport.put(0, 0).put(1, 0).put(2, 800).put(3, 600);
GLStateManager.gluPickMatrix(400.0f, 300.0f, 0.0f, 5.0f, viewport);
// deltaX <= 0 should be a no-op, matrix stays identity
assertMatrixEquals(new Matrix4f(), getProjectionMatrix(), "gluPickMatrix zero deltaX is no-op");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
}
@@ -1,319 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyMaterialState;
@ExtendWith(AngelicaExtension.class)
public class GLSM_Lighting_UnitTest {
static final FloatBuffer f4b = ByteBuffer.allocateDirect(4 << 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
static final FloatBuffer f3b = ByteBuffer.allocateDirect(3 << 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
@Test
void testLightEnablement() {
verifyState(GL11.GL_LIGHT0, false, "GL_LIGHT0 Initial State");
GLStateManager.glEnable(GL11.GL_LIGHT0);
verifyState(GL11.GL_LIGHT0, true, "GL_LIGHT0 Enabled");
verifyState(GL11.GL_LIGHT1, false, "GL_LIGHT1 Initial State");
GLStateManager.glEnable(GL11.GL_LIGHT1);
verifyState(GL11.GL_LIGHT1, true, "GL_LIGHT1 Enabled State");
GLStateManager.glDisable(GL11.GL_LIGHT0);
GLStateManager.glDisable(GL11.GL_LIGHT1);
}
@Test
void testLightValues() {
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, new float[]{0F, 0F, 0F, 1F}, "GL_LIGHT0 Initial Ambient");
verifyLightState(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, new float[]{1F, 1F, 1F, 1F}, "GL_LIGHT0 Initial Diffuse");
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPECULAR, new float[]{1F, 1F, 1F, 1F}, "GL_LIGHT0 Initial Specular");
verifyLightState(GL11.GL_LIGHT0, GL11.GL_POSITION, new float[]{0F, 0F, 1F, 0F}, "GL_LIGHT0 Initial Position");
verifyLightState(GL11.GL_LIGHT1, GL11.GL_AMBIENT, new float[]{0F, 0F, 0F, 1F}, "GL_LIGHT1 Initial Ambient");
verifyLightState(GL11.GL_LIGHT1, GL11.GL_DIFFUSE, new float[]{0F, 0F, 0F, 1F}, "GL_LIGHT1 Initial Diffuse");
verifyLightState(GL11.GL_LIGHT1, GL11.GL_SPECULAR, new float[]{0F, 0F, 0F, 1F}, "GL_LIGHT1 Initial Specular");
verifyLightState(GL11.GL_LIGHT1, GL11.GL_POSITION, new float[]{0F, 0F, 1F, 0F}, "GL_LIGHT1 Initial Position");
newf4b(0.25F, 0.5F, 0.25F, 0.5F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_AMBIENT, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 Ambient Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.3F, 0.4F, 0.5F, 0.6F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_AMBIENT, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, new float[]{0.3F, 0.4F, 0.5F, 0.6F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 attrib pop state check");
// The position is stored in eye coordinates, so we're moving around the modelview matrix before changing them
// That way we can test that the client side transformation of them via GLSM is working and matches the OpenGL
// transformation. This doesn't seem like float precision should break this test, but it may be possible for it
// to need tweaked a bit more.
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(25.0F, 25.0F, 25.0F);
GLStateManager.glRotatef(35.0F, 10.0F, 15.0F, 20.0F);
newf4b(0.25F, 0.5F, 0.25F, 0.0F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_POSITION, new float[]{0.1090F, 0.5189F, 0.3062F, 0.0F}, "GL_LIGHT0 Position Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.3F, 0.4F, 0.5F, 0.0F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_POSITION, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_POSITION, new float[]{0.2824F, 0.4200F, 0.4937F, 0.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_POSITION, new float[]{0.1090F, 0.5189F, 0.3062F, 0.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glPopMatrix();
newf4b(0.25F, 0.5F, 0.25F, 0.5F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 Diffuse Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.3F, 0.4F, 0.5F, 0.6F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, new float[]{0.3F, 0.4F, 0.5F, 0.6F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 attrib pop state check");
newf4b(0.25F, 0.5F, 0.25F, 0.5F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPECULAR, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 Specular Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.3F, 0.4F, 0.5F, 0.6F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPECULAR, new float[]{0.3F, 0.4F, 0.5F, 0.6F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPECULAR, new float[]{0.25F, 0.5F, 0.25F, 0.5F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
GLStateManager.glTranslatef(25.0F, 25.0F, 25.0F);
GLStateManager.glRotatef(35.0F, 10.0F, 15.0F, 20.0F);
newf4b(0.25F, 0.5F, 0.25F, 0.0F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, new float[]{0.1090F, 0.5189F, 0.3062F}, "GL_LIGHT0 Spot Direction Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.3F, 0.4F, 0.5F, 0.0F);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, f4b);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, new float[]{0.2824F, 0.4200F, 0.4937F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_DIRECTION, new float[]{0.1090F, 0.5189F, 0.3062F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glPopMatrix();
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_SPOT_EXPONENT, 1.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_EXPONENT, new float[]{1.0F}, "GL_LIGHT0 Spot Exponent Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_SPOT_EXPONENT, 2.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_EXPONENT, new float[]{2.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_EXPONENT, new float[]{1.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_SPOT_CUTOFF, 20.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_CUTOFF, new float[]{20.0F}, "GL_LIGHT0 Spot Cutoff Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_SPOT_CUTOFF, 40.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_CUTOFF, new float[]{40.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_SPOT_CUTOFF, new float[]{20.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 10.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 Constant Attenuation Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, 20.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, new float[]{20.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_CONSTANT_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_LINEAR_ATTENUATION, 10.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_LINEAR_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 Linear Attenuation Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_LINEAR_ATTENUATION, 20.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_LINEAR_ATTENUATION, new float[]{20.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_LINEAR_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_QUADRATIC_ATTENUATION, 10.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_QUADRATIC_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 Quadratic Attenuation Changed State");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightf(GL11.GL_LIGHT0, GL11.GL_QUADRATIC_ATTENUATION, 20.0F);
verifyLightState(GL11.GL_LIGHT0, GL11.GL_QUADRATIC_ATTENUATION, new float[]{20.0F}, "GL_LIGHT0 attrib push state changed check");
GLStateManager.glPopAttrib();
verifyLightState(GL11.GL_LIGHT0, GL11.GL_QUADRATIC_ATTENUATION, new float[]{10.0F}, "GL_LIGHT0 attrib pop state check");
GLStateManager.glPopAttrib();
}
@Test
void testLightModel() {
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "GL_LIGHT_MODEL_AMBIENT initial state");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, f4b);
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "GL_LIGHT_MODEL_AMBIENT changed state");
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F});
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SINGLE_COLOR);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SEPARATE_SPECULAR_COLOR);
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SEPARATE_SPECULAR_COLOR);
GLStateManager.glPopAttrib();
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SINGLE_COLOR);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModelf(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 0.8F);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModelf(GL11.GL_LIGHT_MODEL_TWO_SIDE, 0.8F);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL11.GL_LIGHT_MODEL_TWO_SIDE, 1);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
}
@Test
void testColorMaterial() {
verifyState(GL11.GL_COLOR_MATERIAL, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT | GL11.GL_CURRENT_BIT);
GLStateManager.glColor4f(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT);
GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyState(GL11.GL_COLOR_MATERIAL, false);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_COLOR_MATERIAL, false);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT_AND_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT_AND_DIFFUSE);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_SPECULAR);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_SPECULAR);
GLStateManager.glColorMaterial(GL11.GL_BACK, GL11.GL_DIFFUSE);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_DIFFUSE);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT_AND_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
}
@Test
void testMaterial() {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_BACK, GL11.GL_SPECULAR, f4b);
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_BACK, GL11.GL_EMISSION, f4b);
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{0.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, 5.5F);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{5.5F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{0.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.0F, 1.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.0F);
GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, f4b);
if (GLStateManager.vendorIsNVIDIA()) {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.4F, 0.6F}, "");
} else {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.6F, 0.4F}, "");
}
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.0F, 1.0F, 1.0F}, "");
}
static void newf4b(float x, float y, float z, float w) {
f4b.clear();
f4b.put(x).put(y).put(z).put(w);
f4b.flip();
}
static void newf3b(float x, float y, float z) {
f3b.clear();
f3b.put(x).put(y).put(z);
f3b.flip();
}
}
@@ -1,104 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(AngelicaExtension.class)
public class GLSM_MatrixStack_UnitTest {
final static FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
Matrix4f getMatrix(int matrix, boolean cached) {
buffer.clear();
if(cached) {
GLStateManager.glGetFloat(matrix, buffer);
} else {
GL11.glGetFloat(matrix, buffer);
}
return new Matrix4f(buffer);
}
boolean matrixEquals(Matrix4f expected, Matrix4f actual) {
if(expected.equals(actual, 0.0001f)) {
return true;
} else {
System.out.println("Expected: " + expected);
System.out.println("Actual: " + actual);
return false;
}
}
void assertMatrixEquals(Matrix4f expected, Matrix4f actual, String message) {
assertTrue(matrixEquals(expected, actual), message);
}
void validateMatrix(Matrix4f expected, int matrix, String message) {
// Matrix ops are FFP-only in core profile — verify GLSM cache only
assertMatrixEquals(expected, getMatrix(matrix, true), message + " - GLSM State Mismatch");
}
enum MatrixMode {
MODELVIEW(GL11.GL_MODELVIEW, GL11.GL_MODELVIEW_MATRIX, "Model"),
PROJECTION(GL11.GL_PROJECTION, GL11.GL_PROJECTION_MATRIX, "Projection"),
TEXTURE(GL11.GL_TEXTURE, GL11.GL_TEXTURE_MATRIX, "Texture");
protected final int mode;
protected final int getEnum;
protected final String name;
MatrixMode(int mode, int getEnum, String name) {
this.mode = mode;
this.getEnum = getEnum;
this.name = name;
}
}
@ParameterizedTest
@EnumSource(MatrixMode.class)
void validateMatrixOperations(MatrixMode matrix) {
GLStateManager.glMatrixMode(matrix.mode);
GLStateManager.glLoadIdentity();
GLStateManager.glPushMatrix();
Matrix4fStack testMatrix = new Matrix4fStack(2);
validateMatrix(testMatrix, matrix.getEnum, "Identity " + matrix.name + " Matrix");
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
testMatrix.scale(2.0f);
validateMatrix(testMatrix, matrix.getEnum, "Scaled " + matrix.name + " Matrix");
GLStateManager.glTranslatef(2.0f, 2.0f, 2.0f);
testMatrix.translate(2.0f, 2.0f, 2.0f);
validateMatrix(testMatrix, matrix.getEnum, "Translated " + matrix.name + " Matrix");
GLStateManager.glRotatef(180.0f, 0.0f, 0.0f, 1.0f);
testMatrix.rotate((float) Math.toRadians(180.0f), 0.0f, 0.0f, 1.0f);
validateMatrix(testMatrix, matrix.getEnum, "Rotated " + matrix.name + " Matrix");
GLStateManager.glOrtho(0, 800, 0, 600, -1, 1);
testMatrix.ortho(0, 800, 0, 600, -1, 1);
validateMatrix(testMatrix, matrix.getEnum, "Ortho " + matrix.name + " Matrix");
Matrix4f testLoad = new Matrix4f();
testLoad.m02(5f);
testLoad.m12(12f);
testLoad.get(buffer);
GLStateManager.glLoadMatrix(buffer);
validateMatrix(testLoad, matrix.getEnum, "Loaded " + matrix.name + " Matrix");
GLStateManager.glPopMatrix();
testMatrix.identity();
validateMatrix(testMatrix, matrix.getEnum, "Popped " + matrix.name + " Matrix");
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,480 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.SharedDrawable;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for server-side GL state synchronization between SharedDrawable and DrawableGL contexts.
*
* Server-side state (texture parameters, texture data) is shared across GL contexts and must
* be properly synchronized in the GLSM cache. Client-side state (texture bindings, active unit)
* is per-context and should NOT be shared.
*/
@ExtendWith(AngelicaExtension.class)
public class GLSM_ServerSideState_UnitTest {
private SharedDrawable sharedDrawable;
private Thread backgroundThread;
private CountDownLatch initLatch;
private CountDownLatch commandLatch;
private CountDownLatch completeLatch;
private CountDownLatch readyLatch;
private Runnable pendingCommand;
private Throwable backgroundError;
private volatile boolean shutdownRequested;
private boolean originalSplashComplete;
private static void setSplashComplete(boolean value) throws Exception {
final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete");
splashCompleteField.setAccessible(true);
splashCompleteField.setBoolean(null, value);
}
private static boolean getSplashComplete() throws Exception {
final Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete");
splashCompleteField.setAccessible(true);
return splashCompleteField.getBoolean(null);
}
@BeforeEach
void setupSharedDrawable() throws Exception {
originalSplashComplete = getSplashComplete();
// Reset splash state to simulate splash screen scenario
setSplashComplete(false);
sharedDrawable = new SharedDrawable(Display.getDrawable());
// Register the main display context (DrawableGL) so makeCurrent() can identify it
GLStateManager.setDrawableGL(Display.getDrawable());
// Switch to DrawableGL to enable caching for main thread
GLStateManager.makeCurrent(Display.getDrawable());
// Verify main thread has caching enabled
assertTrue(GLStateManager.isCachingEnabled(), "Main thread should have caching enabled (it holds DrawableGL)");
shutdownRequested = false;
backgroundError = null;
initLatch = new CountDownLatch(1);
commandLatch = new CountDownLatch(1);
completeLatch = new CountDownLatch(1);
readyLatch = new CountDownLatch(1);
backgroundThread = new Thread(() -> {
try {
GLStateManager.makeCurrent(sharedDrawable);
if (GLStateManager.isCachingEnabled()) {
throw new AssertionError("SharedDrawable thread should have caching DISABLED");
}
// Signal that initialization is complete
initLatch.countDown();
while (!shutdownRequested) {
// Signal ready for next command
readyLatch.countDown();
// Wait for a command
if (commandLatch.await(100, TimeUnit.MILLISECONDS)) {
if (pendingCommand != null && !shutdownRequested) {
try {
pendingCommand.run();
} catch (Throwable t) {
backgroundError = t;
}
pendingCommand = null;
completeLatch.countDown();
}
}
}
} catch (InterruptedException e) {
// Normal shutdown
} catch (LWJGLException e) {
backgroundError = e;
} finally {
try {
sharedDrawable.releaseContext();
} catch (LWJGLException e) {
// Ignore on cleanup
}
}
}, "SharedDrawable-Test-Thread");
backgroundThread.start();
// Wait for background thread to complete initialization
assertTrue(initLatch.await(5, TimeUnit.SECONDS), "Background thread failed to initialize");
}
@AfterEach
void teardownSharedDrawable() throws Exception {
shutdownRequested = true;
commandLatch.countDown(); // Wake up the thread if waiting
if (backgroundThread != null) {
backgroundThread.join(1000);
if (backgroundThread.isAlive()) {
backgroundThread.interrupt();
backgroundThread.join(1000);
}
}
if (sharedDrawable != null) {
sharedDrawable.destroy();
}
// Restore original state
GLStateManager.setDrawableGL(null);
setSplashComplete(originalSplashComplete);
if (originalSplashComplete) {
GLStateManager.markSplashComplete();
}
}
/**
* Execute a command on the SharedDrawable thread and wait for completion.
*/
private void executeOnSharedDrawable(Runnable command) throws InterruptedException {
// Wait for background thread to be ready for a command
assertTrue(readyLatch.await(5, TimeUnit.SECONDS), "Background thread not ready");
// Reset latches for this command cycle
readyLatch = new CountDownLatch(1);
commandLatch = new CountDownLatch(1);
completeLatch = new CountDownLatch(1);
// Set command and signal
pendingCommand = command;
commandLatch.countDown();
// Wait for completion
assertTrue(completeLatch.await(5, TimeUnit.SECONDS), "SharedDrawable command timed out");
if (backgroundError != null) {
fail("Background thread error: " + backgroundError.getMessage(), backgroundError);
}
}
/**
* Diagnostic test: Verify that SharedDrawable actually shares GL namespace with Display.
* This is a prerequisite for all other tests - if sharing doesn't work, texture params won't be shared.
*/
@Test
void testContextSharingVerification() throws InterruptedException {
int texMain = GL11.glGenTextures();
assertTrue(GLStateManager.isCachingEnabled(), "Main thread should have caching enabled (it holds DrawableGL)");
final int[] sharedResult = new int[1];
executeOnSharedDrawable(() -> {
GL11.glGetError();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texMain);
GL11.glGetError();
sharedResult[0] = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
});
assertEquals(texMain, sharedResult[0], "SharedDrawable should be able to bind texture created on main thread - contexts must share GL namespace");
final int[] texShared = new int[1];
executeOnSharedDrawable(() -> texShared[0] = GL11.glGenTextures());
GL11.glGetError();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texShared[0]);
GL11.glGetError();
int mainBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
assertEquals(texShared[0], mainBinding, "Main thread should be able to bind texture created on SharedDrawable - contexts must share GL namespace");
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL11.glDeleteTextures(texMain);
GL11.glDeleteTextures(texShared[0]);
}
/**
* Test: SharedDrawable sets texture MIN_FILTER, verify both GLSM and actual GL state are correct on both contexts.
*/
@Test
void testTexParameterFromSharedDrawable() throws InterruptedException {
int texId = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
int initialGLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR, initialGLSM, "Initial GLSM should be GL_LINEAR");
int initialGL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR, initialGL, "Initial GL should be GL_LINEAR");
// SharedDrawable: bind and change params to GL_NEAREST via GLSM
executeOnSharedDrawable(() -> {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
int boundTex = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
assertEquals(texId, boundTex, "SharedDrawable should have texId bound");
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
int glsmValue = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, glsmValue, "SharedDrawable GLSM should return GL_NEAREST");
int glValue = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, glValue, "SharedDrawable GL should be GL_NEAREST");
});
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
int mainGLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, mainGLSM, "Main thread GLSM should return GL_NEAREST");
int mainGL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, mainGL, "Main thread GL should be GL_NEAREST");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texId);
}
}
/**
* Test: SharedDrawable binds a DIFFERENT texture than main thread, then sets params.
*
* This verifies that when SharedDrawable sets params on texIdA while main thread has texIdB bound, the params go to the correct texture (texIdA).
*/
@Test
void testWrongTextureUpdatedFromSharedDrawable() throws InterruptedException {
int texIdA = GL11.glGenTextures();
int texIdB = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA);
int initialA_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
int initialA_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR, initialA_GLSM, "texIdA initial GLSM should be LINEAR");
assertEquals(GL11.GL_LINEAR, initialA_GL, "texIdA initial GL should be LINEAR");
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB);
int initialB_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
int initialB_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, initialB_GLSM, "texIdB initial GLSM should be LINEAR_MIPMAP_LINEAR");
assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, initialB_GL, "texIdB initial GL should be LINEAR_MIPMAP_LINEAR");
assertEquals(texIdB, GLStateManager.getBoundTextureForServerState(), "Main thread should have texIdB bound");
// SharedDrawable: bind texIdA and change its MIN_FILTER to NEAREST
// Main thread has texIdB bound, but SharedDrawable should correctly update texIdA's params, not texIdB's
executeOnSharedDrawable(() -> {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA);
int bound = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
assertEquals(texIdA, bound, "SharedDrawable should have texIdA bound");
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
int glsmValue = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, glsmValue, "SharedDrawable GLSM should return NEAREST for texIdA");
int glValue = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, glValue, "SharedDrawable GL should be NEAREST for texIdA");
});
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdA);
int finalA_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
int finalA_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_NEAREST, finalA_GLSM, "texIdA final GLSM should be NEAREST (SharedDrawable's update)");
assertEquals(GL11.GL_NEAREST, finalA_GL, "texIdA final GL should be NEAREST");
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texIdB);
int finalB_GLSM = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
int finalB_GL = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, finalB_GLSM, "texIdB should NOT be modified by SharedDrawable");
assertEquals(GL11.GL_LINEAR_MIPMAP_LINEAR, finalB_GL, "texIdB GL should NOT be modified");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texIdA);
GLStateManager.glDeleteTextures(texIdB);
}
}
/**
* Test that client-side state (texture binding) is correctly separate between contexts. Each context should have its own binding cache.
*/
@Test
void testClientStateSeparation() throws InterruptedException {
int texId1 = GL11.glGenTextures();
int texId2 = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId1);
assertEquals(texId1, GLStateManager.getBoundTextureForServerState(), "Main thread cache should show texId1 bound");
executeOnSharedDrawable(() -> GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId2));
assertEquals(texId1, GLStateManager.getBoundTextureForServerState(), "Main thread cache should still show texId1 (client-side state is per-context)");
int actualBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
assertEquals(texId1, actualBinding, "Main thread actual GL binding should still be texId1");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texId1);
GLStateManager.glDeleteTextures(texId2);
}
}
/**
* Test glTexParameterf (float parameters like LOD_BIAS).
*/
@Test
void testTexParameterfFromSharedDrawable() throws InterruptedException {
int texId = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0f);
float initialGLSM = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
float initialGL = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
assertEquals(0.0f, initialGLSM, 0.001f, "Initial GLSM LOD_BIAS should be 0.0");
assertEquals(0.0f, initialGL, 0.001f, "Initial GL LOD_BIAS should be 0.0");
// SharedDrawable: change LOD_BIAS
executeOnSharedDrawable(() -> {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
int bound = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
assertEquals(texId, bound, "SharedDrawable should have texId bound");
GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 1.5f);
float glsmValue = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
assertEquals(1.5f, glsmValue, 0.001f, "SharedDrawable GLSM should return 1.5");
float glValue = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
assertEquals(1.5f, glValue, 0.001f, "SharedDrawable GL should be 1.5");
});
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
float finalGLSM = GLStateManager.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
float finalGL = GL11.glGetTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS);
assertEquals(1.5f, finalGLSM, 0.001f, "Main thread GLSM should return 1.5");
assertEquals(1.5f, finalGL, 0.001f, "Main thread GL should be 1.5");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texId);
}
}
/**
* Test glTexImage2D: SharedDrawable uploads texture data, verify dimensions cached correctly.
*/
@Test
void testTexImage2DFromSharedDrawable() throws InterruptedException {
int texId = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
int initialWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int initialHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
assertEquals(64, initialWidth, "Initial width should be 64");
assertEquals(64, initialHeight, "Initial height should be 64");
// SharedDrawable: re-upload with different dimensions
executeOnSharedDrawable(() -> {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 128, 256, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
int sharedWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int sharedHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
assertEquals(128, sharedWidth, "SharedDrawable GLSM width should be 128");
assertEquals(256, sharedHeight, "SharedDrawable GLSM height should be 256");
int glWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int glHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
assertEquals(128, glWidth, "SharedDrawable GL width should be 128");
assertEquals(256, glHeight, "SharedDrawable GL height should be 256");
});
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
int finalWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int finalHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
assertEquals(128, finalWidth, "Main thread GLSM width should be 128");
assertEquals(256, finalHeight, "Main thread GLSM height should be 256");
int glWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int glHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
assertEquals(128, glWidth, "Main thread GL width should be 128");
assertEquals(256, glHeight, "Main thread GL height should be 256");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texId);
}
}
/**
* Test glDeleteTextures: SharedDrawable deletes texture, verify cache cleared.
*/
@Test
void testDeleteTexturesFromSharedDrawable() throws InterruptedException {
int texId = GL11.glGenTextures();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 32, 32, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
int cachedFilter = GLStateManager.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
assertEquals(GL11.GL_LINEAR, cachedFilter, "Cache should have LINEAR before delete");
assertTrue(GL11.glIsTexture(texId), "Texture should exist before delete");
// SharedDrawable: delete the texture (deferred — name stays valid)
executeOnSharedDrawable(() -> {
GLStateManager.glDeleteTextures(texId);
assertTrue(GL11.glIsTexture(texId), "Texture name should still be valid (deferred delete)");
});
assertTrue(GL11.glIsTexture(texId), "Texture name should still be valid on main thread (deferred delete)");
// glGenTextures flushes deferred deletes
int newTexId = GLStateManager.glGenTextures();
assertFalse(GL11.glIsTexture(texId), "Texture should be gone after flush via glGenTextures");
GL11.glDeleteTextures(newTexId);
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
if (GL11.glIsTexture(texId)) {
GL11.glDeleteTextures(texId);
}
}
}
}
@@ -1,55 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(AngelicaExtension.class)
public class GLSM_TextureInfoCache_UnitTest {
/**
* Texture deletion is server-side; cache must be invalidated regardless of client caching state.
*/
@Test
void testCacheRemovedOnDeleteWhenCachingDisabled() throws Exception {
int texId = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId);
ByteBuffer pixels = BufferUtils.createByteBuffer(4 * 4 * 4);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 4, 4, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);
TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texId);
assertNotNull(info);
// Disable caching (simulate SharedDrawable context)
Field splashCompleteField = GLStateManager.class.getDeclaredField("splashComplete");
splashCompleteField.setAccessible(true);
boolean originalSplash = splashCompleteField.getBoolean(null);
Thread originalHolder = GLStateManager.getDrawableGLHolder();
try {
splashCompleteField.setBoolean(null, false);
GLStateManager.setDrawableGLHolder(null); // Current thread != null, so caching disabled
assertFalse(GLStateManager.isCachingEnabled());
GLStateManager.glDeleteTextures(texId);
splashCompleteField.setBoolean(null, true);
// Cache entry should be gone - we should get a fresh object
assertNotSame(info, TextureInfoCache.INSTANCE.getInfo(texId));
} finally {
splashCompleteField.setBoolean(null, originalSplash);
GLStateManager.setDrawableGLHolder(originalHolder);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
}
}
}
@@ -1,137 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.util.GLSMUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
@ExtendWith(AngelicaExtension.class)
public class GLSM_VAO_UnitTest {
@Test
void testDefaultStates() {
verifyState(GL30.GL_VERTEX_ARRAY_BINDING, 0, "GL_VERTEX_ARRAY_BINDING Initial State");
verifyState(GL13.GL_CLIENT_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "GL_CLIENT_ACTIVE_TEXTURE Initial State");
testClientStates();
}
@Test
void testVAOPreservesStates() {
// Stride = vertexSize * byte size of the type (= 4 for both GL_FLOAT and GL_INT)
final boolean defaultVertexEnabled = false;
final int defaultVertexSize = 2;
final int defaultVertexType = GL11.GL_FLOAT;
final int defaultVertexStride = defaultVertexSize * 4;
final boolean vaoVertexEnabled = true;
final int vaoVertexSize = 4;
final int vaoVertexType = GL11.GL_INT;
final int vaoVertexStride = vaoVertexSize * 4;
GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL13.GL_CLIENT_ACTIVE_TEXTURE, GL13.GL_TEXTURE1, "GL_CLIENT_ACTIVE_TEXTURE - Setup");
// Set the vertex attrib to a defined state
int vbo = GL15.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL11.glVertexPointer(defaultVertexSize, defaultVertexType, defaultVertexStride, 0);
GLSMUtil.setClientState(GL11.GL_NORMAL_ARRAY, true);
verifyState(GL11.GL_NORMAL_ARRAY, true, "GL_NORMAL_ARRAY - Enabled");
verifyState(GL11.GL_VERTEX_ARRAY_SIZE, defaultVertexSize, "GL_VERTEX_ARRAY_SIZE - Setup");
verifyState(GL11.GL_VERTEX_ARRAY_TYPE, defaultVertexType, "GL_VERTEX_ARRAY_TYPE - Setup");
verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, defaultVertexStride, "GL_VERTEX_ARRAY_STRIDE - Setup");
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
// Verify VAO & VBO creation
int vao = UniversalVAO.genVertexArrays();
Assertions.assertTrue(vao > 0, "GL_VERTEX_ARRAY_BINDING - VAO Created");
glBindVertexArray(vao);
verifyState(GL30.GL_VERTEX_ARRAY_BINDING, vao, "GL_VERTEX_ARRAY_BINDING - Bound");
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
verifyState(GL15.GL_ARRAY_BUFFER_BINDING, vbo, "GL_ARRAY_BUFFER_BINDING - Bound");
verifyState(GL13.GL_CLIENT_ACTIVE_TEXTURE, GL13.GL_TEXTURE1, "GL_CLIENT_ACTIVE_TEXTURE - Preserved");
// Set & Verify the VAO states
// VAO's have every client state back to its default state, so GL_NORMAL_ARRAY should be false now
testClientStates();
GLSMUtil.setClientState(GL11.GL_VERTEX_ARRAY, vaoVertexEnabled);
verifyState(GL11.GL_VERTEX_ARRAY, vaoVertexEnabled, "GL_VERTEX_ARRAY - Enabled");
GL11.glVertexPointer(vaoVertexSize, vaoVertexType, vaoVertexStride, 0);
verifyState(GL11.GL_VERTEX_ARRAY_SIZE, vaoVertexSize, "GL_VERTEX_ARRAY_SIZE - Set");
verifyState(GL11.GL_VERTEX_ARRAY_TYPE, vaoVertexType, "GL_VERTEX_ARRAY_TYPE - Set");
verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, vaoVertexStride, "GL_VERTEX_ARRAY_STRIDE - Set");
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
// Check if everything got reset to default
glBindVertexArray(0);
verifyState(GL30.GL_VERTEX_ARRAY_BINDING, 0, "GL_VERTEX_ARRAY_BINDING - Unbound");
verifyState(GL15.GL_ARRAY_BUFFER_BINDING, 0, "GL_ARRAY_BUFFER_BINDING - Unbound");
verifyState(GL11.GL_VERTEX_ARRAY, defaultVertexEnabled, "GL_VERTEX_ARRAY - Reset");
verifyState(GL11.GL_VERTEX_ARRAY_SIZE, defaultVertexSize, "GL_VERTEX_ARRAY_SIZE - Reset");
verifyState(GL11.GL_VERTEX_ARRAY_TYPE, defaultVertexType, "GL_VERTEX_ARRAY_TYPE - Reset");
verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, defaultVertexStride, "GL_VERTEX_ARRAY_STRIDE - Reset");
verifyState(GL11.GL_NORMAL_ARRAY, true, "GL_NORMAL_ARRAY - Reset");
// Check if the VAO states are still valid after re-binding it
glBindVertexArray(vao);
verifyState(GL11.GL_VERTEX_ARRAY, vaoVertexEnabled, "GL_VERTEX_ARRAY - Preserved");
verifyState(GL11.GL_VERTEX_ARRAY_SIZE, vaoVertexSize, "GL_VERTEX_ARRAY_SIZE - Preserved");
verifyState(GL11.GL_VERTEX_ARRAY_TYPE, vaoVertexType, "GL_VERTEX_ARRAY_TYPE - Preserved");
verifyState(GL11.GL_VERTEX_ARRAY_STRIDE, vaoVertexStride, "GL_VERTEX_ARRAY_STRIDE - Preserved");
glBindVertexArray(0);
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
glBindVertexArray(vao);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GLStateManager.glPopAttrib();
verifyState(GL30.GL_VERTEX_ARRAY_BINDING, vao, "GL_VERTEX_ARRAY_BINDING - Not affected by glPushAttrib");
verifyState(GL15.GL_ARRAY_BUFFER_BINDING, vbo, "GL_ARRAY_BUFFER_BINDING - Not affected by glPushAttrib");
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
GL15.glDeleteBuffers(vbo);
UniversalVAO.deleteVertexArrays(vao);
}
private static void testClientStates() {
verifyState(GL11.GL_VERTEX_ARRAY, false, "GL_VERTEX_ARRAY Default State");
verifyState(GL11.GL_TEXTURE_COORD_ARRAY, false, "GL_TEXTURE_COORD_ARRAY Default State");
verifyState(GL11.GL_NORMAL_ARRAY, false, "GL_NORMAL_ARRAY Default State");
verifyState(GL11.GL_COLOR_ARRAY, false, "GL_COLOR_ARRAY Default State");
verifyState(GL11.GL_INDEX_ARRAY, false, "GL_INDEX_ARRAY Default State");
}
private static void glBindVertexArray(int array) {
GLStateManager.boundVAO = array;
UniversalVAO.bindVertexArray(array);
}
}
@@ -1,110 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(AngelicaExtension.class)
class VertexAttribDefaultBridgeTest {
private static final int COLOR_ATTRIB = 1; // VertexFormatElement.Usage.COLOR
private static final int PRIMARY_UV_ATTRIB = 2; // VertexFormatElement.Usage.PRIMARY_UV
private static final int SECONDARY_UV_ATTRIB = 3; // VertexFormatElement.Usage.SECONDARY_UV
private static final int NORMAL_ATTRIB = 4; // VertexFormatElement.Usage.NORMAL
private static final float EPSILON = 1e-5f;
private float[] getVertexAttrib4f(int index) {
FloatBuffer buf = BufferUtils.createFloatBuffer(4);
GL20.glGetVertexAttrib(index, GL20.GL_CURRENT_VERTEX_ATTRIB, buf);
return new float[] { buf.get(0), buf.get(1), buf.get(2), buf.get(3) };
}
@Test
void testGlColor4fSetsVertexAttrib() {
GLStateManager.glColor4f(0.5f, 0.25f, 0.75f, 0.8f);
GLStateManager.flushDeferredVertexAttribs();
float[] color = getVertexAttrib4f(COLOR_ATTRIB);
assertEquals(0.5f, color[0], EPSILON, "color.r");
assertEquals(0.25f, color[1], EPSILON, "color.g");
assertEquals(0.75f, color[2], EPSILON, "color.b");
assertEquals(0.8f, color[3], EPSILON, "color.a");
}
@Test
void testGlNormal3fSetsVertexAttrib() {
GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f);
GLStateManager.flushDeferredVertexAttribs();
float[] normal = getVertexAttrib4f(NORMAL_ATTRIB);
assertEquals(0.0f, normal[0], EPSILON, "normal.x");
assertEquals(1.0f, normal[1], EPSILON, "normal.y");
assertEquals(0.0f, normal[2], EPSILON, "normal.z");
}
@Test
void testSetLightmapTextureCoordsOnUnit1SetsVertexAttrib() {
GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, 240.0f, 128.0f);
GLStateManager.flushDeferredVertexAttribs();
float[] lm = getVertexAttrib4f(SECONDARY_UV_ATTRIB);
assertEquals(240.0f, lm[0], EPSILON, "lightmap.s");
assertEquals(128.0f, lm[1], EPSILON, "lightmap.t");
assertEquals(0.0f, lm[2], EPSILON, "lightmap.r");
assertEquals(1.0f, lm[3], EPSILON, "lightmap.q");
}
@Test
void testGlTexCoord2fSetsVertexAttrib() {
// glTexCoord2f outside recording → sets default vertex attrib 2 (PRIMARY_UV)
GLStateManager.glTexCoord2f(0.5f, 0.75f);
GLStateManager.flushDeferredVertexAttribs();
float[] uv = getVertexAttrib4f(PRIMARY_UV_ATTRIB);
assertEquals(0.5f, uv[0], EPSILON, "texcoord.s");
assertEquals(0.75f, uv[1], EPSILON, "texcoord.t");
}
@Test
void testCacheDedup_SameColorTwice_AttribStillCorrect() {
GLStateManager.glColor4f(0.3f, 0.6f, 0.9f, 1.0f);
// Second call is a cache hit — changeColor not called.
// Vertex attrib should still hold the correct value from the first call.
GLStateManager.glColor4f(0.3f, 0.6f, 0.9f, 1.0f);
GLStateManager.flushDeferredVertexAttribs();
float[] color = getVertexAttrib4f(COLOR_ATTRIB);
assertEquals(0.3f, color[0], EPSILON, "color.r after dedup");
assertEquals(0.6f, color[1], EPSILON, "color.g after dedup");
assertEquals(0.9f, color[2], EPSILON, "color.b after dedup");
assertEquals(1.0f, color[3], EPSILON, "color.a after dedup");
}
@Test
void testCompileMode_DoesNotSetVertexAttrib() {
GLStateManager.glColor4f(0.1f, 0.2f, 0.3f, 1.0f);
GLStateManager.flushDeferredVertexAttribs();
int listId = GLStateManager.glGenLists(1);
GLStateManager.glNewList(listId, org.lwjgl.opengl.GL11.GL_COMPILE);
// Color during COMPILE should NOT reach changeColor (early return)
GLStateManager.glColor4f(0.9f, 0.8f, 0.7f, 0.6f);
float[] color = getVertexAttrib4f(COLOR_ATTRIB);
assertEquals(0.1f, color[0], EPSILON, "color.r unchanged during COMPILE");
assertEquals(0.2f, color[1], EPSILON, "color.g unchanged during COMPILE");
assertEquals(0.3f, color[2], EPSILON, "color.b unchanged during COMPILE");
assertEquals(1.0f, color[3], EPSILON, "color.a unchanged during COMPILE");
GLStateManager.glEndList();
GLStateManager.glDeleteLists(listId, 1);
}
}
@@ -1,307 +0,0 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.TexEnvState;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for FFP TexEnv COMBINE / multi-unit features:
* TexEnvState tracking, FragmentKey packing, FragmentShaderGenerator COMBINE codegen, and glMultiTexCoord routing.
*/
@ExtendWith(AngelicaExtension.class)
class FFPCombineShaderTest {
private final List<Integer> shadersToDelete = new ArrayList<>();
private final List<Integer> programsToDelete = new ArrayList<>();
@AfterEach
void cleanup() {
// Delete GL resources
for (int p : programsToDelete) GL20.glDeleteProgram(p);
for (int s : shadersToDelete) GL20.glDeleteShader(s);
programsToDelete.clear();
shadersToDelete.clear();
// Reset texture units to defaults
for (int i = 3; i >= 0; i--) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
GLStateManager.getTextures().getTexEnvState(i).reset();
if (i > 0) {
GLStateManager.getTextures().getTextureUnitStates(i).disable();
}
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
@Test
void testTexEnvStateTracking() {
// Unit 0: COMBINE mode, SUBTRACT RGB, REPLACE alpha
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL13.GL_SUBTRACT);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_REPLACE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_RGB, GL13.GL_PRIMARY_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_RGB, GL11.GL_ONE_MINUS_SRC_COLOR);
TexEnvState env0 = GLStateManager.getTextures().getTexEnvState(0);
assertEquals(GL13.GL_COMBINE, env0.mode);
assertEquals(GL13.GL_SUBTRACT, env0.combineRgb);
assertEquals(GL11.GL_REPLACE, env0.combineAlpha);
assertEquals(GL11.GL_TEXTURE, env0.sourceRgb[0]);
assertEquals(GL11.GL_ONE_MINUS_SRC_ALPHA, env0.operandRgb[0]);
assertEquals(GL13.GL_PRIMARY_COLOR, env0.sourceRgb[1]);
assertEquals(GL11.GL_ONE_MINUS_SRC_COLOR, env0.operandRgb[1]);
// Unit 2: independent state
GLStateManager.glActiveTexture(GL13.GL_TEXTURE2);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL11.GL_ADD);
TexEnvState env2 = GLStateManager.getTextures().getTexEnvState(2);
assertEquals(GL13.GL_COMBINE, env2.mode);
assertEquals(GL11.GL_ADD, env2.combineRgb);
// Verify unit 0 unchanged
assertEquals(GL13.GL_SUBTRACT, env0.combineRgb, "Unit 0 should be independent of unit 2");
}
@Test
void testFragmentKeyMultiUnitCombine() {
setupXaeroState();
FragmentKey fk = FragmentKey.fromState();
assertEquals(4, fk.nrEnabledUnits(), "highestEnabled is unit 3 → nrEnabledUnits=4");
assertTrue(fk.unitEnabled(0));
assertFalse(fk.unitEnabled(1), "unit 1 should be disabled");
assertTrue(fk.unitEnabled(2));
assertTrue(fk.unitEnabled(3));
assertEquals(FragmentKey.TEX_ENV_COMBINE, fk.unitMode(0));
assertEquals(FragmentKey.COMBINE_SUBTRACT, fk.unitCombineRgb(0));
assertEquals(FragmentKey.TEX_ENV_COMBINE, fk.unitMode(2));
assertEquals(FragmentKey.COMBINE_ADD, fk.unitCombineRgb(2));
assertEquals(FragmentKey.TEX_ENV_MODULATE, fk.unitMode(3));
// Verify source/operand on unit 0
assertEquals(FragmentKey.SRC_TEXTURE, fk.unitSourceRgb(0, 0));
assertEquals(FragmentKey.OP_SRC_COLOR, fk.unitOperandRgb(0, 0));
assertEquals(FragmentKey.SRC_PRIMARY_COLOR, fk.unitSourceRgb(0, 1));
assertEquals(FragmentKey.OP_SRC_COLOR, fk.unitOperandRgb(0, 1));
}
@Test
void testSingleUnitCombineCompiles() {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL11.GL_MODULATE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_MODULATE);
FragmentKey fk = FragmentKey.fromState();
String fragSource = FragmentShaderGenerator.generate(fk);
int shader = compileShader(fragSource, GL20.GL_FRAGMENT_SHADER);
assertTrue(shader > 0, "Single-unit COMBINE fragment shader should compile");
}
@Test
void testXaeroMultiUnitCombineCompiles() {
setupXaeroState();
FragmentKey fk = FragmentKey.fromState();
VertexKey vk = VertexKey.fromState(true, false, true, false);
String fragSource = FragmentShaderGenerator.generate(fk);
String vertSource = VertexShaderGenerator.generate(vk);
int vs = compileShader(vertSource, GL20.GL_VERTEX_SHADER);
int fs = compileShader(fragSource, GL20.GL_FRAGMENT_SHADER);
int prog = GL20.glCreateProgram();
programsToDelete.add(prog);
GL20.glAttachShader(prog, vs);
GL20.glAttachShader(prog, fs);
GL20.glLinkProgram(prog);
int linkStatus = GL20.glGetProgrami(prog, GL20.GL_LINK_STATUS);
if (linkStatus == 0) {
String log = GL20.glGetProgramInfoLog(prog, 4096);
fail("Xaero multi-unit program link failed:\n" + log
+ "\n\n--- Vertex Shader ---\n" + vertSource
+ "\n\n--- Fragment Shader ---\n" + fragSource);
}
}
static Stream<Arguments> allCombineFunctions() {
return Stream.of(
Arguments.of("REPLACE", GL11.GL_REPLACE, 1),
Arguments.of("MODULATE", GL11.GL_MODULATE, 2),
Arguments.of("ADD", GL11.GL_ADD, 2),
Arguments.of("ADD_SIGNED", GL13.GL_ADD_SIGNED, 2),
Arguments.of("SUBTRACT", GL13.GL_SUBTRACT, 2),
Arguments.of("INTERPOLATE", GL13.GL_INTERPOLATE, 3),
Arguments.of("DOT3_RGB", GL13.GL_DOT3_RGB, 2),
Arguments.of("DOT3_RGBA", GL13.GL_DOT3_RGBA, 2)
);
}
@ParameterizedTest(name = "COMBINE function {0}")
@MethodSource("allCombineFunctions")
void testAllCombineFunctionsCompile(String name, int glFunc, int numArgs) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, glFunc);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_REPLACE);
// Set up appropriate sources
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_ALPHA, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_ALPHA, GL11.GL_SRC_ALPHA);
if (numArgs >= 2) {
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_RGB, GL13.GL_PRIMARY_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_ALPHA, GL13.GL_PREVIOUS);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_ALPHA, GL11.GL_SRC_ALPHA);
}
if (numArgs >= 3) {
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE2_RGB, GL13.GL_PREVIOUS);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND2_RGB, GL11.GL_SRC_ALPHA);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE2_ALPHA, GL13.GL_PREVIOUS);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND2_ALPHA, GL11.GL_SRC_ALPHA);
}
FragmentKey fk = FragmentKey.fromState();
String fragSource = FragmentShaderGenerator.generate(fk);
int shader = compileShader(fragSource, GL20.GL_FRAGMENT_SHADER);
assertTrue(shader > 0, "COMBINE function " + name + " should compile");
}
@Test
void testCombineScopeDeclaresColorOutsideBlock() {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL11.GL_MODULATE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_MODULATE);
FragmentKey fk = FragmentKey.fromState();
String src = FragmentShaderGenerator.generate(fk);
// Result variables declared outside the scope block
assertTrue(src.contains("vec3 combRgb0;"), "combRgb0 should be declared outside scope block");
assertTrue(src.contains("float combAlpha0;"), "combAlpha0 should be declared outside scope block");
// color assignment uses the result variables outside the block
assertTrue(src.contains("vec4(combRgb0, combAlpha0)"), "color should be assigned from combine results outside block");
// The scope block uses { } to contain arg declarations
assertTrue(src.contains(" {\n"), "Should have scope block for arg declarations");
// Bonus: verify it compiles
int shader = compileShader(src, GL20.GL_FRAGMENT_SHADER);
assertTrue(shader > 0, "Scope-correct COMBINE shader should compile");
}
// ---- Test 7: glMultiTexCoord2f routes to ShaderManager.currentTexCoord ----
@Test
void testMultiTexCoordRoutesToShaderManager() {
// Not in immediate mode or display list recording, so should go to ShaderManager.currentTexCoord
ShaderManager.setCurrentTexCoord(0.0f, 0.0f, 0.0f, 1.0f); // reset
GLStateManager.glMultiTexCoord2f(GL13.GL_TEXTURE0, 0.5f, 0.75f);
var texCoord = ShaderManager.getCurrentTexCoord();
assertEquals(0.5f, texCoord.x, 1e-6f, "s coordinate should be 0.5");
assertEquals(0.75f, texCoord.y, 1e-6f, "t coordinate should be 0.75");
}
@Test
void testMultiTexCoord2dDelegatesToFloat() {
ShaderManager.setCurrentTexCoord(0.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glMultiTexCoord2d(GL13.GL_TEXTURE0, 0.5, 0.75);
var texCoord = ShaderManager.getCurrentTexCoord();
assertEquals(0.5f, texCoord.x, 1e-6f, "double 0.5 should arrive as float 0.5");
assertEquals(0.75f, texCoord.y, 1e-6f, "double 0.75 should arrive as float 0.75");
}
/**
* Configure the 4-unit Xaero-like combine chain:
* Unit 0: COMBINE, RGB=SUBTRACT, SRC0=TEXTURE/SRC_COLOR, SRC1=PRIMARY_COLOR/SRC_COLOR
* Unit 1: disabled
* Unit 2: COMBINE, RGB=ADD, SRC0=TEXTURE/SRC_COLOR, SRC1=PREVIOUS/SRC_COLOR
* Unit 3: MODULATE (simple)
*/
private void setupXaeroState() {
// Unit 0: COMBINE / SUBTRACT
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL13.GL_SUBTRACT);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_REPLACE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_RGB, GL13.GL_PRIMARY_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_ALPHA, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_ALPHA, GL11.GL_SRC_ALPHA);
// Unit 1: disabled (skip — default is disabled)
// Unit 2: COMBINE / ADD
GLStateManager.glActiveTexture(GL13.GL_TEXTURE2);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL13.GL_COMBINE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL11.GL_ADD);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_REPLACE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_RGB, GL13.GL_PREVIOUS);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_RGB, GL11.GL_SRC_COLOR);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_ALPHA, GL11.GL_TEXTURE);
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_ALPHA, GL11.GL_SRC_ALPHA);
// Unit 3: simple MODULATE
GLStateManager.glActiveTexture(GL13.GL_TEXTURE3);
GLStateManager.enableTexture();
GLStateManager.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
// Restore active unit
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private int compileShader(String source, int type) {
int shader = GL20.glCreateShader(type);
shadersToDelete.add(shader);
GL20.glShaderSource(shader, source);
GL20.glCompileShader(shader);
int status = GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS);
if (status == 0) {
String log = GL20.glGetShaderInfoLog(shader, 4096);
fail("Shader compilation failed:\n" + log + "\n\n--- Source ---\n" + source);
}
return shader;
}
}
@@ -1,105 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.junit.jupiter.api.AfterEach;
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 static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for display list recording data structures.
*/
@ExtendWith(AngelicaExtension.class)
class RecordingDataStructuresTest {
private int testList = -1;
@AfterEach
void cleanup() {
if (testList > 0) {
GLStateManager.glDeleteLists(testList, 1);
testList = -1;
}
}
@Test
void testCompiledDisplayListCreation() {
// Create a display list with PushMatrix, Scale, PopMatrix
testList = GL11.glGenLists(1);
GLStateManager.glNewList(testList, GL11.GL_COMPILE);
GLStateManager.glPushMatrix();
GLStateManager.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glPopMatrix();
GLStateManager.glEndList();
// Verify the compiled display list
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
assertNotNull(compiled.getCommandBuffer(), "Command buffer should not be null");
// Get command counts to verify structure
Int2IntMap counts = compiled.getCommandCounts();
// Should have PushMatrix and PopMatrix
assertEquals(1, counts.getOrDefault(GLCommand.PUSH_MATRIX, 0), "Should have 1 PushMatrix");
assertEquals(1, counts.getOrDefault(GLCommand.POP_MATRIX, 0), "Should have 1 PopMatrix");
// Scale should be collapsed into a MultMatrix (optimizer collapses transforms)
// Or if in debug mode, might have individual commands - just check we have some transforms
int transformCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0)
+ counts.getOrDefault(GLCommand.SCALE, 0);
assertTrue(transformCount >= 0, "Should have transform commands");
}
@Test
void testImmediateModeRecorder() {
DirectTessellator recorder = ImmediateModeRecorder.getInternalTessellator();
// Record a single quad using immediate mode
recorder.startDrawing(GL11.GL_QUADS);
recorder.setTextureUV(0, 0);
recorder.addVertex(0, 0, 0);
recorder.setTextureUV(1, 0);
recorder.addVertex(1, 0, 0);
recorder.setTextureUV(1, 1);
recorder.addVertex(1, 1, 0);
recorder.setTextureUV(0, 1);
recorder.addVertex(0, 1, 0);
// end() now returns quads immediately (for correct command interleaving)
DirectTessellator result = ImmediateModeRecorder.end();
assertNotNull(result);
assertTrue(ImmediateModeRecorder.hasGeometry());
assertEquals(4, result.getVertexCount());
assertEquals(GL11.GL_QUADS, result.getDrawMode());
assertTrue(result.hasTexture); // We called setTexCoord
assertFalse(result.hasNormals);
assertFalse(result.hasColor);
assertFalse(result.hasBrightness);
assertEquals(DefaultVertexFormat.POSITION_TEXTURE, result.getVertexFormat());
result.reset();
assertFalse(ImmediateModeRecorder.hasGeometry());
assertEquals(0, result.getVertexCount());
assertFalse(result.hasTexture);
assertFalse(result.hasNormals);
assertFalse(result.hasColor);
assertFalse(result.hasBrightness);
assertNull(result.getVertexFormat());
}
}
@@ -1,199 +0,0 @@
package com.gtnewhorizons.angelica.glsm.streaming;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader.UploadStrategy;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(AngelicaExtension.class)
class StreamingBufferTest {
@ParameterizedTest
@EnumSource(UploadStrategy.class)
void orphan_dataIntegrity(UploadStrategy strategy) {
OrphanStreamingBuffer buf = new OrphanStreamingBuffer();
try {
ByteBuffer data = memAlloc(64);
ByteBuffer readBack = null;
try {
for (int i = 0; i < 64; i++) data.put((byte) i);
data.flip();
buf.upload(strategy, data);
// Read back via glGetBufferSubData
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buf.getBufferId());
readBack = memAlloc(64);
GL15.glGetBufferSubData(GL15.GL_ARRAY_BUFFER, 0, readBack);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
for (int i = 0; i < 64; i++) {
assertEquals((byte) i, readBack.get(i), "Mismatch at byte " + i);
}
} finally {
memFree(data);
if (readBack != null) memFree(readBack);
}
} finally {
buf.destroy();
}
}
@Test
void persistent_uploadAlignment() {
Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required");
PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096);
try {
ByteBuffer data = memAlloc(128);
fillPattern(data);
data.flip();
int firstVertex = buf.upload(data, 32);
assertTrue(firstVertex >= 0, "Upload should succeed");
assertEquals(0, firstVertex % 4, "firstVertex must be quad-aligned");
memFree(data);
} finally {
buf.destroy();
}
}
@Test
void persistent_dataIntegrity() {
Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required");
PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096);
try {
ByteBuffer data = memAlloc(128);
for (int i = 0; i < 128; i++) data.put((byte) i);
data.flip();
int stride = 32;
int firstVertex = buf.upload(data, stride);
assertTrue(firstVertex >= 0);
// Read back from persistently mapped buffer (CPU-visible, no fence needed)
ByteBuffer mapped = buf.getMappedBuffer();
int byteOffset = firstVertex * stride;
for (int i = 0; i < 128; i++) {
assertEquals((byte) i, mapped.get(byteOffset + i), "Mismatch at byte " + i);
}
memFree(data);
} finally {
buf.destroy();
}
}
@Test
void persistent_ringWraparound() {
Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required");
// Small ring: 1024 bytes. stride=16, alignUnit=64.
PersistentStreamingBuffer buf = new PersistentStreamingBuffer(1024);
try {
int stride = 16;
// Fill most of the ring (768 bytes)
ByteBuffer data1 = memAlloc(768);
fillPattern(data1);
data1.flip();
int v1 = buf.upload(data1, stride);
assertTrue(v1 >= 0);
buf.postDraw();
memFree(data1);
// Wait for GPU to finish so fence is signaled
GL11.glFinish();
// Upload again — should wrap to start after reclaim
ByteBuffer data2 = memAlloc(512);
for (int i = 0; i < 512; i++) data2.put((byte) ((i + 100) & 0xFF));
data2.flip();
int v2 = buf.upload(data2, stride);
assertTrue(v2 >= 0, "Should succeed after reclaim/wrap");
// Verify data2 integrity
ByteBuffer mapped = buf.getMappedBuffer();
int offset2 = v2 * stride;
for (int i = 0; i < 512; i++) {
assertEquals((byte) ((i + 100) & 0xFF), mapped.get(offset2 + i), "Mismatch at byte " + i);
}
buf.postDraw();
memFree(data2);
} finally {
buf.destroy();
}
}
@Test
void persistent_fenceReclaim() {
Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required");
PersistentStreamingBuffer buf = new PersistentStreamingBuffer(4096);
try {
ByteBuffer data = memAlloc(1024);
fillPattern(data);
data.flip();
buf.upload(data, 32);
buf.postDraw();
int remainingAfterUpload = buf.getRemaining();
GL11.glFinish(); // ensure fence completion
// New upload triggers reclaim of first upload's bytes
data.position(0).limit(512);
buf.upload(data, 32);
// After reclaim, remaining should be higher than before reclaim (minus new upload)
assertTrue(buf.getRemaining() > remainingAfterUpload,
"Remaining should increase after fence reclaim (minus new upload cost)");
buf.postDraw();
memFree(data);
} finally {
buf.destroy();
}
}
@Test
void persistent_overflowReturnsNegative() {
Assumptions.assumeTrue(RenderSystem.supportsBufferStorage(), "GL4.4+ required");
// Tiny ring: 256 bytes
PersistentStreamingBuffer buf = new PersistentStreamingBuffer(256);
try {
ByteBuffer data = memAlloc(512);
fillPattern(data);
data.flip();
int result = buf.upload(data, 32);
assertEquals(-1, result, "Should return -1 when data exceeds total capacity");
memFree(data);
} finally {
buf.destroy();
}
}
// --- Utilities ---
private static void fillPattern(ByteBuffer buf) {
for (int i = 0; i < buf.capacity(); i++) {
buf.put((byte) (i & 0xFF));
}
}
}
@@ -1,41 +0,0 @@
package com.gtnewhorizons.angelica.util;
import java.util.Objects;
public final class GLBit {
private final int glEnum;
private final String name;
private final boolean initial;
public GLBit(int glEnum, String name, boolean initial) {
this.name = name;
this.glEnum = glEnum;
this.initial = initial;
}
public String name() {return name;}
public int glEnum() {return glEnum;}
public boolean initial() {return initial;}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
GLBit that = (GLBit) obj;
return Objects.equals(this.name, that.name) && this.glEnum == that.glEnum && this.initial == that.initial;
}
@Override
public int hashCode() {
return Objects.hash(name, glEnum, initial);
}
@Override
public String toString() {
return "GLBit[" + "name=" + name + ", " + "glEnum=" + glEnum + ", " + "initial=" + initial + ']';
}
}
@@ -1,373 +0,0 @@
package com.gtnewhorizons.angelica.util;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Set;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class GLSMUtil {
// Cached GL limits (queried once at class load time)
private static final int MAX_CLIP_PLANES = GL11.glGetInteger(GL11.GL_MAX_CLIP_PLANES);
private static final int MAX_LIGHTS = GL11.glGetInteger(GL11.GL_MAX_LIGHTS);
private static final int MAX_TEXTURE_UNITS = GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS);
// MAP1 evaluator constants for DRY loops
private static final int[] MAP1_STATES = {
GL11.GL_MAP1_COLOR_4, GL11.GL_MAP1_INDEX, GL11.GL_MAP1_NORMAL,
GL11.GL_MAP1_TEXTURE_COORD_1, GL11.GL_MAP1_TEXTURE_COORD_2,
GL11.GL_MAP1_TEXTURE_COORD_3, GL11.GL_MAP1_TEXTURE_COORD_4,
GL11.GL_MAP1_VERTEX_3, GL11.GL_MAP1_VERTEX_4
};
// MAP2 evaluator constants for DRY loops
private static final int[] MAP2_STATES = {
GL11.GL_MAP2_COLOR_4, GL11.GL_MAP2_INDEX, GL11.GL_MAP2_NORMAL,
GL11.GL_MAP2_TEXTURE_COORD_1, GL11.GL_MAP2_TEXTURE_COORD_2,
GL11.GL_MAP2_TEXTURE_COORD_3, GL11.GL_MAP2_TEXTURE_COORD_4,
GL11.GL_MAP2_VERTEX_3, GL11.GL_MAP2_VERTEX_4
};
private static final Set<Integer> FFP_ONLY_CAPS = Set.of(
// Enable/disable caps (BooleanState ffpStateOnly=true)
GL11.GL_FOG, GL11.GL_ALPHA_TEST, GL11.GL_LIGHTING,
GL12.GL_RESCALE_NORMAL, GL11.GL_NORMALIZE, GL11.GL_COLOR_MATERIAL,
GL11.GL_LIGHT0, GL11.GL_LIGHT1, GL11.GL_LIGHT2, GL11.GL_LIGHT3,
GL11.GL_LIGHT4, GL11.GL_LIGHT5, GL11.GL_LIGHT6, GL11.GL_LIGHT7,
// Texture enable/disable (TextureUnitBooleanStateStack ffpStateOnly=true)
GL11.GL_TEXTURE_1D, GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_3D,
GL11.GL_TEXTURE_GEN_S, GL11.GL_TEXTURE_GEN_T,
GL11.GL_TEXTURE_GEN_R, GL11.GL_TEXTURE_GEN_Q,
// Matrix state
GL11.GL_MATRIX_MODE, GL11.GL_MODELVIEW_MATRIX,
GL11.GL_PROJECTION_MATRIX, GL11.GL_TEXTURE_MATRIX,
// Current vertex state
GL11.GL_CURRENT_COLOR, GL11.GL_CURRENT_NORMAL, GL11.GL_CURRENT_TEXTURE_COORDS,
// Alpha test params
GL11.GL_ALPHA_TEST_FUNC, GL11.GL_ALPHA_TEST_REF,
// Shade model
GL11.GL_SHADE_MODEL,
// Color material params
GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_COLOR_MATERIAL_PARAMETER,
// Light model params
GL11.GL_LIGHT_MODEL_AMBIENT, GL11.GL_LIGHT_MODEL_LOCAL_VIEWER,
GL11.GL_LIGHT_MODEL_TWO_SIDE, GL12.GL_LIGHT_MODEL_COLOR_CONTROL,
// Line stipple params (removed from core profile)
GL11.GL_LINE_STIPPLE, GL11.GL_LINE_STIPPLE_PATTERN, GL11.GL_LINE_STIPPLE_REPEAT,
// Fog params
GL11.GL_FOG_COLOR, GL11.GL_FOG_DENSITY,
GL11.GL_FOG_START, GL11.GL_FOG_END,
GL11.GL_FOG_MODE, GL11.GL_FOG_INDEX
);
private static boolean isFFPOnly(int glCap) {
return FFP_ONLY_CAPS.contains(glCap);
}
public static void verifyIsEnabled(int glCap, boolean expected) {
verifyIsEnabled(glCap, expected, "Is Enabled Mismatch");
}
public static void verifyIsEnabled(int glCap, boolean expected, String message) {
if (isFFPOnly(glCap)) {
assertEquals(expected, GLStateManager.glIsEnabled(glCap), message + " - GLSM State Mismatch");
} else {
assertAll(message,
() -> assertEquals(expected, GL11.glIsEnabled(glCap), "GL State Mismatch"),
() -> assertEquals(expected, GLStateManager.glIsEnabled(glCap), "GLSM State Mismatch")
);
}
}
public static void verifyState(int glCap, boolean expected) {
verifyState(glCap, expected, "Boolean State Mismatch");
}
public static void verifyState(int glCap, boolean expected, String message) {
if (isFFPOnly(glCap)) {
assertEquals(expected, GLStateManager.glGetBoolean(glCap), message + " - GLSM State Mismatch");
} else {
assertAll(message,
() -> assertEquals(expected, GL11.glGetBoolean(glCap), "GL State Mismatch"),
() -> assertEquals(expected, GLStateManager.glGetBoolean(glCap), "GLSM State Mismatch")
);
}
}
public static void verifyState(int glCap, int expected) {
verifyState(glCap, expected, "Int State Mismatch");
}
public static void verifyState(int glCap, int expected, String message) {
if (isFFPOnly(glCap)) {
assertEquals(expected, GLStateManager.glGetInteger(glCap), message + " - GLSM State Mismatch");
} else {
assertAll(message,
() -> assertEquals(expected, GL11.glGetInteger(glCap), "GL State Mismatch"),
() -> assertEquals(expected, GLStateManager.glGetInteger(glCap), "GLSM State Mismatch")
);
}
}
public static void verifyState(int glCap, short expected, String message) {
if (isFFPOnly(glCap)) {
assertEquals(expected, (short) GLStateManager.glGetInteger(glCap), message + " - GLSM State Mismatch");
} else {
assertAll(message,
() -> assertEquals(expected, (short) GL11.glGetInteger(glCap), "GL State Mismatch"),
() -> assertEquals(expected, (short) GLStateManager.glGetInteger(glCap), "GLSM State Mismatch")
);
}
}
public static void verifyState(int glCap, float expected) {
verifyState(glCap, expected, "Float State Mismatch");
}
public static void verifyState(int glCap, float expected, String message) {
if (isFFPOnly(glCap)) {
assertEquals(expected, GLStateManager.glGetFloat(glCap), 0.0001f, message + " - GLSM State Mismatch");
} else {
assertAll(message,
() -> assertEquals(expected, GL11.glGetFloat(glCap), 0.0001f, "GL State Mismatch"),
() -> assertEquals(expected, GLStateManager.glGetFloat(glCap), 0.0001f, "GLSM State Mismatch")
);
}
}
public static void verifyState(int glCap, int[] expected) {
verifyState(glCap, expected, "Int State Mismatch");
}
static final IntBuffer glIntBuffer = BufferUtils.createIntBuffer(16);
static final IntBuffer glsmIntBuffer = BufferUtils.createIntBuffer(16);
public static void verifyState(int glCap, int[] expected, String message) {
if (isFFPOnly(glCap)) {
GLStateManager.glGetInteger(glCap, (IntBuffer) glsmIntBuffer.clear());
IntStream.range(0, expected.length).forEach(i ->
assertEquals(expected[i], glsmIntBuffer.get(i), message + " - GLSM State Mismatch: " + i)
);
} else {
GL11.glGetInteger(glCap, (IntBuffer) glIntBuffer.clear());
GLStateManager.glGetInteger(glCap, (IntBuffer) glsmIntBuffer.clear());
IntStream.range(0, expected.length).forEach(i -> assertAll(message,
() -> assertEquals(expected[i], glIntBuffer.get(i), "GL State Mismatch: " + i),
() -> assertEquals(expected[i], glsmIntBuffer.get(i), "GLSM State Mismatch: " + i)
));
}
}
public static void verifyState(int glCap, float[] expected) {
verifyState(glCap, expected, "Float State Mismatch");
}
static final FloatBuffer glFloatBuffer = BufferUtils.createFloatBuffer(16);
static final FloatBuffer glsmFloatBuffer = BufferUtils.createFloatBuffer(16);
public static void verifyState(int glCap, float[] expected, String message) {
if (isFFPOnly(glCap)) {
GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range(0, expected.length).forEach(i ->
assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i)
);
} else {
GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear());
GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range(0, expected.length).forEach(i -> assertAll(message,
() -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i),
() -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i)
));
}
}
public static void verifyNotDefaultState(int glCap, float[] expected, String message) {
if (isFFPOnly(glCap)) {
GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range(0, expected.length).forEach(i ->
assertNotEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i)
);
} else {
GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear());
GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range(0, expected.length).forEach(i -> assertAll(message,
() -> assertNotEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i),
() -> assertNotEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i)
));
}
}
public static void verifyState(int glCap, boolean[] expected) {
verifyState(glCap, expected, "Boolean State Mismatch");
}
static final ByteBuffer glByteBuffer = BufferUtils.createByteBuffer(16);
static final ByteBuffer glsmByteBuffer = BufferUtils.createByteBuffer(16);
public static void verifyState(int glCap, boolean[] expected, String message) {
if (isFFPOnly(glCap)) {
GLStateManager.glGetBoolean(glCap, (ByteBuffer) glsmByteBuffer.clear());
IntStream.range(0, expected.length).forEach(i ->
assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glsmByteBuffer.get(i), message + " - GLSM State Mismatch: " + i)
);
} else {
GL11.glGetBoolean(glCap, (ByteBuffer) glByteBuffer.clear());
GLStateManager.glGetBoolean(glCap, (ByteBuffer) glsmByteBuffer.clear());
IntStream.range(0, expected.length).forEach(i -> assertAll(message,
() -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glByteBuffer.get(i), "GL State Mismatch: " + i),
() -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glsmByteBuffer.get(i), "GLSM State Mismatch: " + i)
));
}
}
/** Light params are FFP-only — verify GLSM cache only. */
public static void verifyLightState(int glLight, int pname, float[] expected, String message) {
GLStateManager.glGetLight(glLight, pname, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range (0, expected.length).forEach(i ->
assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i)
);
}
/** Material params are FFP-only — verify GLSM cache only. */
public static void verifyMaterialState(int face, int pname, float[] expected, String message) {
GLStateManager.glGetMaterial(face, pname, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range (0, expected.length).forEach(i ->
assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i)
);
}
/**
* Reset all GL state to known defaults to prevent test contamination.
* This should be called at the end of tests that modify a lot of state.
*/
public static void resetGLState() {
// Disable all enable/disable states (except those with non-false defaults)
GLStateManager.disableAlphaTest();
GLStateManager.glDisable(GL11.GL_AUTO_NORMAL);
GLStateManager.disableBlend();
// Disable all clip planes (using cached MAX_CLIP_PLANES)
for(int i = 0; i < MAX_CLIP_PLANES; i++) {
GLStateManager.glDisable(GL11.GL_CLIP_PLANE0 + i);
}
GLStateManager.disableColorMaterial();
GLStateManager.glDisable(GL11.GL_COLOR_LOGIC_OP);
GLStateManager.disableCull();
GLStateManager.disableDepthTest();
// GL_DITHER defaults to true
GLStateManager.glEnable(GL11.GL_DITHER);
GLStateManager.disableFog();
GLStateManager.glDisable(GL11.GL_INDEX_LOGIC_OP);
GLStateManager.disableLighting();
// Disable all lights (using cached MAX_LIGHTS)
for(int i = 0; i < MAX_LIGHTS; i++) {
GLStateManager.disableLight(i);
}
GLStateManager.glDisable(GL11.GL_LINE_SMOOTH);
GLStateManager.glDisable(GL11.GL_LINE_STIPPLE);
// Disable all MAP1 evaluators (DRY loop)
for(int state : MAP1_STATES) {
GLStateManager.glDisable(state);
}
// Disable all MAP2 evaluators (DRY loop)
for(int state : MAP2_STATES) {
GLStateManager.glDisable(state);
}
// GL_MULTISAMPLE defaults to true (but may vary by driver)
// We'll query the actual default rather than assume
if(GL11.glIsEnabled(GL13.GL_MULTISAMPLE)) {
GLStateManager.glEnable(GL13.GL_MULTISAMPLE);
} else {
GLStateManager.glDisable(GL13.GL_MULTISAMPLE);
}
GLStateManager.glDisable(GL11.GL_NORMALIZE);
GLStateManager.glDisable(GL11.GL_POINT_SMOOTH);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_POINT);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_LINE);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glDisable(GL11.GL_POLYGON_SMOOTH);
GLStateManager.glDisable(GL11.GL_POLYGON_STIPPLE);
GLStateManager.disableRescaleNormal();
GLStateManager.glDisable(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE);
GLStateManager.glDisable(GL13.GL_SAMPLE_ALPHA_TO_ONE);
GLStateManager.glDisable(GL13.GL_SAMPLE_COVERAGE);
GLStateManager.disableScissorTest();
GLStateManager.glDisable(GL11.GL_STENCIL_TEST);
// Reset texture state for all units (using cached MAX_TEXTURE_UNITS)
for(int i = 0; i < MAX_TEXTURE_UNITS; i++) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
GLStateManager.glDisable(GL11.GL_TEXTURE_1D);
GLStateManager.disableTexture(); // GL_TEXTURE_2D
GLStateManager.glDisable(GL12.GL_TEXTURE_3D);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_S);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_T);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_R);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_Q);
}
// Reset to texture unit 0
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
// Reset matrix mode to default
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
// Reset color to white
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
// Reset material colors to defaults (fixes GL_COLOR_MATERIAL side effects)
FloatBuffer materialBuffer = BufferUtils.createFloatBuffer(4);
materialBuffer.put(0.2F).put(0.2F).put(0.2F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, materialBuffer);
materialBuffer.clear();
materialBuffer.put(0.8F).put(0.8F).put(0.8F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_DIFFUSE, materialBuffer);
// Reset draw buffer
GLStateManager.glDrawBuffer(GLStateManager.DEFAULT_DRAW_BUFFER);
// Reset line state
GLStateManager.glLineWidth(1.0f);
// Reset point state
GLStateManager.glPointSize(1.0f);
// Reset polygon state
GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
GLStateManager.glPolygonOffset(0.0f, 0.0f);
GLStateManager.glCullFace(GL11.GL_BACK);
GLStateManager.glFrontFace(GL11.GL_CCW);
// Reset stencil state
GLStateManager.glStencilFunc(GL11.GL_ALWAYS, 0, 0xFFFFFFFF);
GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP);
GLStateManager.glStencilMask(0xFFFFFFFF);
GLStateManager.glClearStencil(0);
}
public static void setClientState(int glCap, boolean state) {
if (state) {
GL11.glEnableClientState(glCap);
} else {
GL11.glDisableClientState(glCap);
}
}
}
@@ -1,8 +1,6 @@
package com.gtnewhorizons.angelica.utils;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.nio.FloatBuffer;
@@ -13,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for BufferUtil.
*/
@ExtendWith(AngelicaExtension.class)
class BufferUtilTest {
@Test
@@ -1,8 +1,11 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.taumc.glsl.ShaderParser;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -17,6 +20,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
class ShaderTransformerTest {
@BeforeAll
static void initShaderTransformer() throws Exception {
Field maxGlsl = RenderSystem.class.getDeclaredField("maxGlslVersion");
maxGlsl.setAccessible(true);
maxGlsl.setInt(null, 460);
ShaderTransformer.clearCache();
ShaderTransformer.init();
}
@Test
void transformIsDeterministicUnderConcurrency() throws ExecutionException, InterruptedException {
TransformPatcher.clearCache();