Compare commits

...
98 changed files with 5311 additions and 2111 deletions

No files matched your search

+15 -7
View File
@@ -60,7 +60,7 @@ dependencies {
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.8.21:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") {
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-25.g3a943bb") {
exclude module: "antlr4" // we only want to shadow the runtime module
}
shadowImplementation("org.antlr:antlr4-runtime:4.13.2")
@@ -109,12 +109,20 @@ dependencies {
// Better Crashes
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.0-GTNH:dev")
// Tests
testImplementation(platform('org.junit:junit-bom:5.11.4'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
testAnnotationProcessor("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1")
afterEvaluate {
dependencies {
testImplementation(platform('org.junit:junit-bom:5.14.1'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
// testAnnotationProcessor("com.github.GTNewHorizons:jabel-javac-plugin:1.0.2-GTNH") // Soon :tm:
testAnnotationProcessor("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1")
testImplementation('org.junit.platform:junit-platform-engine')
testImplementation('org.junit.platform:junit-platform-reporting')
testImplementation('org.junit.platform:junit-platform-launcher')
}
}
compileOnly("mega:fluidlogged-mc1.7.10:0.1.2")
}
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e1118b4c7c2858d28154d086dbff010e/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/59a9771cad43219260d9aac9a8ec4d6a/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/832229f0f6f0be60ed817c5a5e5848eb/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/b96cb7670c095245220e7d01d5927b58/redirect
toolchainVersion=25
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
+3 -3
View File
@@ -2,8 +2,8 @@ pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "https://nexus.gtnewhorizons.com/repository/public/"
name = "GTNH Maven"
url = uri("https://nexus.gtnewhorizons.com/repository/public/")
mavenContent {
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.48'
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.6")
}
@@ -37,7 +37,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getUStart(char chr) {
final float startColumnF = (float)(this.glyphWidth[chr] >>> 4);
final float startColumnF = (float)((this.glyphWidth[chr] >>> 4) & 15);
return ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f;
}
@@ -48,7 +48,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getXAdvance(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -57,7 +57,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getGlyphW(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -67,7 +67,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getUSize(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -55,8 +55,10 @@ public class BackhandReflectionCompat {
if (isLoaded && renderOffhandReturn != null) {
try {
renderOffhandReturn.invokeExact(partialTicks);
} catch (Throwable e) {
LOGGER.error("Failed to invoke Backhand renderOffhandReturn", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -66,8 +68,10 @@ public class BackhandReflectionCompat {
if (isLoaded && getOffhandItem != null) {
try {
return (ItemStack) getOffhandItem.invokeExact(player);
} catch (Throwable e) {
LOGGER.error("Failed to invoke Backhand getOffhandItem", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -75,8 +75,10 @@ public class HoloInventoryReflectionCompat {
} else {
renderEventMethod.invokeExact(event);
}
} catch (Throwable e) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -85,8 +87,10 @@ public class HoloInventoryReflectionCompat {
if (!isLoaded) return;
try {
angelicaOverrideSetter.invokeExact(value);
} catch (Throwable e) {
LOGGER.error("Failed to set HoloInventory angelicaOverride", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -2,12 +2,13 @@ package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor.BufferTransformOptimizer;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Comparator;
@@ -16,17 +17,16 @@ import java.util.Map;
/**
* Builds final command buffers from raw command buffers and compiled VBO data.
* Bridges the gap between VBO compilation (glsm types) and buffer processing (recording types).
* Transforms are already collapsed to MultMatrix during recording; the optimizer
* tracks transform state to emit deltas when draws need a different transform.
*/
public final class CommandBufferBuilder {
private static final Logger LOGGER = LogManager.getLogger("CommandBufferBuilder");
private CommandBufferBuilder() {}
/**
* Build commands with transform collapsing optimization.
* Accumulates MODELVIEW transforms and emits MultMatrix at barriers (draws, CallList).
* Uses mergedRanges where consecutive same-transform draws are combined.
*/
/** Build with transform delta optimization and merged draw ranges. */
public static void buildOptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
@@ -76,11 +76,7 @@ public final class CommandBufferBuilder {
}
}
/**
* Build commands without transform collapsing.
* Copies state commands directly (no transform optimization), but still uses
* merged draw ranges (draws already collapsed by format + transform in VBO compilation).
*/
/** Debug build: no optimizations, 1:1 draw commands. */
public static void buildUnoptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
@@ -96,8 +92,8 @@ public final class CommandBufferBuilder {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Collect per-draw ranges (no merging) sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRangesUnoptimized(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
rawBuffer.resetRead();
int cmdIndex = 0;
@@ -110,6 +106,7 @@ public final class CommandBufferBuilder {
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
@@ -124,17 +121,32 @@ public final class CommandBufferBuilder {
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
}
/**
* Collect all draw ranges from compiled buffers, sorted by command index.
*/
/** Collect merged draw ranges, sorted by command index. */
static List<DrawRangeWithBuffer> collectDrawRanges(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, true);
}
/** Collect unmerged draw ranges for debug mode. */
static List<DrawRangeWithBuffer> collectDrawRangesUnoptimized(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, false);
}
private static List<DrawRangeWithBuffer> collectDrawRangesInternal(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
boolean useMerged) {
final List<DrawRangeWithBuffer> allRanges = new ArrayList<>();
@@ -142,17 +154,21 @@ public final class CommandBufferBuilder {
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int b = 0; b < quadBufferArray.length; b++) {
final CompiledFormatBuffer compiledBuffer = quadBufferArray[b];
final DrawRange[] ranges = compiledBuffer.mergedRanges();
final DrawRange[] ranges = useMerged ? compiledBuffer.mergedRanges() : compiledBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags().hasBrightness));
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags(),
DrawRangeWithBuffer.DrawSource.TESSELLATOR_QUADS));
}
}
// Add immediate mode line ranges
// Lines use a minimal flags (color only, no texture/brightness/normals)
if (compiledLineBuffer != null) {
final DrawRange[] ranges = compiledLineBuffer.mergedRanges();
final CapturingTessellator.Flags lineFlags = new CapturingTessellator.Flags(false, false, true, false);
final DrawRange[] ranges = useMerged ? compiledLineBuffer.mergedRanges() : compiledLineBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), false));
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), lineFlags,
DrawRangeWithBuffer.DrawSource.IMMEDIATE_MODE_LINES));
}
}
@@ -161,21 +177,23 @@ public final class CommandBufferBuilder {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int p = 0; p < primBufferArray.length; p++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[p];
final boolean hasBrightness = primBuffers.flags().hasBrightness;
final CapturingTessellator.Flags primFlags = primBuffers.flags();
// Tessellator lines
if (primBuffers.hasLines()) {
final DrawRange[] ranges = primBuffers.lineMergedRanges();
final DrawRange[] ranges = useMerged ? primBuffers.lineMergedRanges() : primBuffers.linePerDrawRanges();
final VertexBuffer vbo = primBuffers.lineVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness));
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_LINES));
}
}
// Tessellator triangles
if (primBuffers.hasTriangles()) {
final DrawRange[] ranges = primBuffers.triangleMergedRanges();
final DrawRange[] ranges = useMerged ? primBuffers.triangleMergedRanges() : primBuffers.trianglePerDrawRanges();
final VertexBuffer vbo = primBuffers.triangleVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness));
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_TRIANGLES));
}
}
}
@@ -185,21 +203,36 @@ public final class CommandBufferBuilder {
return allRanges;
}
/**
* Emit a draw range to the output buffer, with transform if needed.
*/
/** Emit draw range with delta transform. Uses writeDrawRangeRestore for immediate mode. */
private static void emitDrawRangeToBuffer(
DrawRangeWithBuffer drb,
BufferTransformOptimizer opt,
CommandBuffer out,
Object2IntMap<VertexBuffer> vboIndexMap) {
// Emit transform to reach the draw's expected transform
opt.emitTransformTo(out, drb.range().transform());
// Write the draw range command
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
final var restoreData = drb.range().restoreData();
if (restoreData != null) {
// Immediate mode draw with attribute restoration
final var flags = drb.flags();
out.writeDrawRangeRestore(
vboIdx, drb.range().startVertex(), drb.range().vertexCount(),
drb.hasBrightness(), flags.hasColor, flags.hasNormals, flags.hasTexture,
restoreData.lastColorR(), restoreData.lastColorG(),
restoreData.lastColorB(), restoreData.lastColorA(),
restoreData.lastNormalX(), restoreData.lastNormalY(), restoreData.lastNormalZ(),
restoreData.lastTexCoordS(), restoreData.lastTexCoordT()
);
} else {
// Regular tessellator draw (no restoration needed)
out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
}
@@ -14,7 +14,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
* </ul>
*/
@Desugar
record CompiledLineBuffer(
public record CompiledLineBuffer(
VertexBuffer vbo,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
@@ -12,7 +12,7 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
* Similar to CompiledFormatBuffer but handles primitives instead of quads.
*/
@Desugar
record CompiledPrimitiveBuffers(
public record CompiledPrimitiveBuffers(
CapturingTessellator.Flags flags,
VertexBuffer lineVbo,
DrawRange[] lineMergedRanges,
File diff suppressed because it is too large. Load diff
@@ -1,11 +1,25 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
/**
* Represents a vertex range within a shared VBO, along with its transform.
* Used during format-based batching to track where each draw's vertices are stored.
*
* <p>The restoreData field holds last vertex attributes for GL state restoration
* after VBO rendering (immediate mode draws only). Null for tessellator draws.
*/
@Desugar
record DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {}
public record DrawRange(
int startVertex,
int vertexCount,
Matrix4f transform,
int commandIndex,
AccumulatedDraw.RestoreData restoreData
) {
DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {
this(startVertex, vertexCount, transform, commandIndex, null);
}
}
@@ -1,12 +1,43 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Helper record pairing a DrawRange with its VBO and brightness flag.
* Helper record pairing a DrawRange with its VBO and vertex format flags.
* Used for sorting ranges by command index while retaining VBO reference.
* Works for both quad ranges (from CompiledFormatBuffer) and line ranges (from CompiledLineBuffer).
*/
@Desugar
record DrawRangeWithBuffer(DrawRange range, VertexBuffer vbo, boolean hasBrightness) {}
record DrawRangeWithBuffer(
DrawRange range,
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawSource source
) {
boolean hasBrightness() {
return flags != null && flags.hasBrightness;
}
/**
* Source of a draw command for debug logging.
*/
enum DrawSource {
TESSELLATOR_QUADS("tessellator quads"),
TESSELLATOR_LINES("tessellator lines"),
TESSELLATOR_TRIANGLES("tessellator triangles"),
IMMEDIATE_MODE_LINES("immediate mode lines");
private final String description;
DrawSource(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
}
@@ -11,13 +11,7 @@ import java.util.List;
/**
* Accumulates geometry for a single vertex format during display list compilation.
* All draws with the same format are collected here, then compiled into a single VBO.
* <p>
* Tracks two types of ranges:
* <ul>
* <li><b>mergedRanges</b>: Consecutive same-transform draws merged for optimized path</li>
* <li><b>perDrawRanges</b>: One range per input draw for unoptimized path (1:1 with addDraw calls)</li>
* </ul>
* Tracks merged ranges (same-transform draws combined) and per-draw ranges (1:1).
*/
class FormatBuffer {
final CapturingTessellator.Flags flags;
@@ -36,25 +30,36 @@ class FormatBuffer {
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingGeneration = -1;
private int pendingStateGen = -1;
// Track last restore data for merged draws (uses the LAST draw's data)
private AccumulatedDraw.RestoreData pendingRestoreData = null;
FormatBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/**
* Add a draw to this format buffer.
* Tracks both merged (for optimized) and per-draw (for unoptimized) ranges.
*/
/** Add a draw, tracking both merged and per-draw ranges. */
void addDraw(AccumulatedDraw draw) {
int vertexCount = draw.quads.size() * 4; // 4 vertices per quad
final int vertexCount = draw.quads.size() * 4; // 4 vertices per quad
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Always track per-draw range for unoptimized path (includes restoreData)
perDrawRanges.add(new DrawRange(
currentVertexOffset, vertexCount, draw.transform, draw.commandIndex, draw.restoreData
));
// Merge logic for optimized path
if (pendingTransform != null && pendingTransform.equals(draw.transform)) {
// Merge logic for optimized path:
// - same matrixGeneration = same matrix transform context
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingGeneration != -1
&& pendingGeneration == draw.matrixGeneration
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
// Update restoreData to the LAST draw's data (used after merged draw completes)
pendingRestoreData = draw.restoreData;
} else {
// Flush pending range if any
flushPendingRange();
@@ -64,6 +69,9 @@ class FormatBuffer {
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingGeneration = draw.matrixGeneration;
pendingStateGen = draw.stateGeneration;
pendingRestoreData = draw.restoreData;
}
allQuads.addAll(draw.quads);
@@ -71,16 +79,18 @@ class FormatBuffer {
}
private void flushPendingRange() {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
if (pendingGeneration != -1) {
mergedRanges.add(new DrawRange(
pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex, pendingRestoreData
));
pendingTransform = null;
pendingGeneration = -1;
pendingStateGen = -1;
pendingRestoreData = null;
}
}
/**
* Compile all accumulated quads into a single VBO.
* @return The compiled buffer with VBO and both range types
*/
/** Compile accumulated quads into a VBO. */
CompiledFormatBuffer finish() {
// Flush any remaining pending range
flushPendingRange();
File diff suppressed because it is too large. Load diff
@@ -41,6 +41,7 @@ class LineBuffer {
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingStateGen = -1;
/**
* Add a line draw to this buffer.
@@ -52,8 +53,14 @@ class LineBuffer {
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingTransform != null && pendingTransform.equals(draw.transform)) {
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTransform != null
&& pendingTransform.equals(draw.transform)
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
} else {
@@ -65,6 +72,7 @@ class LineBuffer {
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingStateGen = draw.stateGeneration;
}
allVertices.addAll(draw.lines);
@@ -75,6 +83,7 @@ class LineBuffer {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
pendingTransform = null;
pendingStateGen = -1;
}
}
@@ -195,6 +195,10 @@ public class RenderSystem {
return dsaState.getTexParameteri(texture, target, pname);
}
public static int getTexLevelParameteri(int texture, int level, int pname) {
return dsaState.getTexLevelParameteri(texture, level, pname);
}
public static void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) {
if (GLStateManager.capabilities.OpenGL42) {
GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format);
@@ -40,6 +40,7 @@ class TessellatorPrimitiveBuffer {
private int pendingLineVertexCount = 0;
private Matrix4f pendingLineTransform = null;
private int pendingLineCommandIndex = -1;
private int pendingLineStateGen = -1;
// Ranges for triangles
final List<DrawRange> triangleMergedRanges = new ArrayList<>();
@@ -49,6 +50,7 @@ class TessellatorPrimitiveBuffer {
private int pendingTriangleVertexCount = 0;
private Matrix4f pendingTriangleTransform = null;
private int pendingTriangleCommandIndex = -1;
private int pendingTriangleStateGen = -1;
TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
@@ -81,8 +83,14 @@ class TessellatorPrimitiveBuffer {
final int lineVertexCount = lineCount * 2; // 2 vertices per line
linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingLineTransform != null && pendingLineTransform.equals(draw.transform)) {
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingLineTransform != null
&& pendingLineTransform.equals(draw.transform)
&& pendingLineStateGen == draw.stateGeneration;
if (canMerge) {
pendingLineVertexCount += lineVertexCount;
} else {
flushPendingLineRange();
@@ -90,6 +98,7 @@ class TessellatorPrimitiveBuffer {
pendingLineVertexCount = lineVertexCount;
pendingLineTransform = new Matrix4f(draw.transform);
pendingLineCommandIndex = draw.commandIndex;
pendingLineStateGen = draw.stateGeneration;
}
currentLineVertexOffset += lineVertexCount;
}
@@ -99,8 +108,14 @@ class TessellatorPrimitiveBuffer {
final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle
trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingTriangleTransform != null && pendingTriangleTransform.equals(draw.transform)) {
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTriangleTransform != null
&& pendingTriangleTransform.equals(draw.transform)
&& pendingTriangleStateGen == draw.stateGeneration;
if (canMerge) {
pendingTriangleVertexCount += triangleVertexCount;
} else {
flushPendingTriangleRange();
@@ -108,6 +123,7 @@ class TessellatorPrimitiveBuffer {
pendingTriangleVertexCount = triangleVertexCount;
pendingTriangleTransform = new Matrix4f(draw.transform);
pendingTriangleCommandIndex = draw.commandIndex;
pendingTriangleStateGen = draw.stateGeneration;
}
currentTriangleVertexOffset += triangleVertexCount;
}
@@ -117,6 +133,7 @@ class TessellatorPrimitiveBuffer {
if (pendingLineTransform != null) {
lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex));
pendingLineTransform = null;
pendingLineStateGen = -1;
}
}
@@ -124,6 +141,7 @@ class TessellatorPrimitiveBuffer {
if (pendingTriangleTransform != null) {
triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex));
pendingTriangleTransform = null;
pendingTriangleStateGen = -1;
}
}
@@ -5,14 +5,13 @@ import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Helper class for tracking and collapsing MODELVIEW transforms during optimization.
* Helper class for tracking and collapsing matrix transforms during optimization.
* Implements the transform accumulation and emission strategy:
* <ul>
* <li>accumulated: total relative transform (what GL matrix should be)</li>
@@ -100,11 +99,11 @@ class TransformOptimizer {
// But for simplicity, if lastEmitted is identity, just emit target
if (DisplayListManager.isIdentity(lastEmitted)) {
// Simple case: just emit target
output.add(MultMatrixCmd.create(target, GL11.GL_MODELVIEW));
output.add(MultMatrixCmd.create(target));
} else {
// Need to emit delta: inv(lastEmitted) * target
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
output.add(MultMatrixCmd.create(delta, GL11.GL_MODELVIEW));
output.add(MultMatrixCmd.create(delta));
}
lastEmitted.set(target);
}
@@ -126,7 +125,7 @@ class TransformOptimizer {
/**
* Check if the GL matrix is at an absolute value and clear the flag.
* Used by LoadIdentityCmd to determine if it needs to emit.
* Used to determine if LoadIdentity needs to emit.
* @return true if LoadMatrix was called and not yet reset by LoadIdentity
*/
boolean checkAndClearAbsoluteMatrix() {
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.glsm.debug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray;
import net.minecraft.client.Minecraft;
@@ -23,7 +24,9 @@ import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
// Adapted from https://github.com/makamys/CoreTweaks/blob/master/src/main/java/makamys/coretweaks/util/OpenGLDebugging.java;
@@ -34,6 +37,7 @@ public class OpenGLDebugging {
public static final Logger LOGGER = LogManager.getLogger("gldumper");
private static final Consumer<String> LINE_LOGGER = LOGGER::debug;
private static final Set<String> seenErrors = new HashSet<>();
public static final String GL_IS_ENABLED = "glIsEnabled()";
public static final String GL_GET_BOOLEANV = "glGetBooleanv()";
public static final String GL_GET_INTEGERV = "glGetIntegerv()";
@@ -455,49 +459,195 @@ public class OpenGLDebugging {
}
public static String getGLSMErrorLog() {
StringBuilder error = new StringBuilder();
return getGLSMErrorLog(null, false, false);
}
// Re-entrancy guard - getGLSMErrorLog calls glActiveTexture which could trigger checkGLSMOnce
private static boolean inCheck = false;
/**
* Enhanced GLSM error logging with context, stack trace, and first-occurrence filtering.
*
* @param context Optional context string to include in error messages (e.g., "During rendering")
* @param logStacktrace If true, includes the current stack trace in the error output
* @param onlyFirstOccurrence If true, only logs each unique error once
* @return Error log string if mismatches found, null otherwise
*/
public static String getGLSMErrorLog(String context, boolean logStacktrace, boolean onlyFirstOccurrence) {
if (inCheck) return null;
if (!GLStateManager.isCachingEnabled() || GLStateManager.isRecordingDisplayList()) {
return null;
}
inCheck = true;
try {
String group = "checkGLSM" + (context == null ? "" : " " + context);
GLDebug.pushGroup(group);
final StringBuilder error = new StringBuilder();
boolean mismatch = false;
if (context != null && !context.isEmpty()) {
error.append("[").append(context).append("] ");
}
for (int i = 0; i < instance.propertyList.length; ++i) {
final GLproperty gLProperty = instance.propertyList[i];
if (gLProperty.fetchCommand.equals(GL_GET_FLOATV) && gLProperty.name.endsWith("_MATRIX")) {
final Matrix4f cached = gLProperty.getAsMatrix4f(true);
final Matrix4f uncached = gLProperty.getAsMatrix4f(false);
// Some precision issues due to RAD vs degrees, and translated (vs f)
if (!cached.equals(uncached, 0.001f)) {
LOGGER.error("GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached);
mismatch = true;
// Skip comparison if either matrix is degenerate (contains NaN/Infinity) these represent invalid GL state from bad parameters, not cache bugs
if (isMatrixDegenerate(cached) || isMatrixDegenerate(uncached)) continue;
if (!matricesEquivalent(cached, uncached, 0.001f)) {
final String errorKey = "MATRIX:" + gLProperty.name;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
final String errorMsg = "GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached;
LOGGER.error(errorMsg);
error.append(errorMsg).append('\n');
mismatch = true;
}
}
} else {
final String cached = gLProperty.getAsString(true);
final String uncached = gLProperty.getAsString(false);
if (!cached.equals(uncached)) {
error.append("GLSM mismatch: " + gLProperty.name + " cached: " + cached + " uncached: " + uncached);
error.append('\n');
final String errorKey = "PROPERTY:" + gLProperty.name + ":" + cached + ":" + uncached;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: ").append(gLProperty.name).append(" cached: ").append(cached).append(" uncached: ").append(uncached);
error.append('\n');
mismatch = true;
}
}
}
}
final TextureUnitArray textureUnits = GLStateManager.getTextures();
final int currentActiveTexture = GLStateManager.getActiveTextureUnit();
// Check GL_ACTIVE_TEXTURE
final int glActiveUnit = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0;
if (glActiveUnit != currentActiveTexture) {
final String errorKey = "ACTIVE_TEXTURE:" + currentActiveTexture + ":" + glActiveUnit;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_ACTIVE_TEXTURE cached: ").append(currentActiveTexture)
.append(" uncached: ").append(glActiveUnit).append('\n');
mismatch = true;
}
}
// Check per-unit texture state
for (int i = 0; i < textureUnits.textureMatricies.length; i++) {
GL13.glActiveTexture(GL13.GL_TEXTURE0 + i);
// Check GL_TEXTURE_2D enabled
final boolean cachedEnabled = textureUnits.getTextureUnitStates(i).isEnabled();
final boolean uncachedEnabled = GL11.glIsEnabled(GL11.GL_TEXTURE_2D);
if (cachedEnabled != uncachedEnabled) {
final String errorKey = "TEXTURE_2D:" + i + ":" + cachedEnabled + ":" + uncachedEnabled;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_TEXTURE_2D cached: ").append(cachedEnabled)
.append(" uncached: ").append(uncachedEnabled)
.append(", texture unit: GL_TEXTURE").append(i).append('\n');
mismatch = true;
}
}
// Check GL_TEXTURE_BINDING_2D
final int cachedBinding = textureUnits.getTextureUnitBindings(i).getBinding();
final int uncachedBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
if (cachedBinding != uncachedBinding) {
final String errorKey = "TEXTURE_BINDING_2D:" + i + ":" + cachedBinding + ":" + uncachedBinding;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_TEXTURE_BINDING_2D cached: ").append(cachedBinding)
.append(" uncached: ").append(uncachedBinding)
.append(", texture unit: GL_TEXTURE").append(i).append('\n');
mismatch = true;
}
}
}
final TextureUnitArray textureUnits = GLStateManager.getTextures();
int currentActiveTexture = GLStateManager.getActiveTextureUnit();
for (int i = 0; i < textureUnits.textureMatricies.length; i++) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
final boolean cached = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean uncached = GL11.glIsEnabled(GL11.GL_TEXTURE_2D);
if (cached != uncached) {
error.append("GLSM mismatch: " + "GL_TEXTURE_2D" + " cached: " + cached + " uncached: " + uncached + ", texture unit: GL_TEXTURE" + i);
error.append('\n');
mismatch = true;
GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture);
// Add stack trace if requested
if (mismatch && logStacktrace) {
error.append("\nStack trace:\n");
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = 2; i < stackTrace.length; i++) {
error.append(" at ").append(stackTrace[i].toString()).append('\n');
}
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture);
if (!mismatch) {
return null;
GLDebug.popGroup();
return mismatch ? error.toString() : null;
} finally {
inCheck = false;
}
return error.toString();
}
public static boolean checkGLSMOnce(String context) {
final String output = getGLSMErrorLog(context, true, true);
if (output != null) {
// Only log on actual mismatch
LOGGER.error("[{}] MISMATCH thread={}\n{}", context, Thread.currentThread().getName(), output);
return false;
}
return true;
}
/**
* Check if a matrix contains any non-finite values (NaN or Infinity).
* Such matrices represent invalid/degenerate GL state (e.g., zero near/far in projection).
*/
private static boolean isMatrixDegenerate(Matrix4f matrix) {
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
if (!Float.isFinite(matrix.get(col, row))) {
return true;
}
}
}
return false;
}
/**
* Compare two matrices with tolerance for NaN/Infinity.
* Treats NaN == NaN and Infinity == Infinity as equal (both are degenerate states).
* For finite values, uses epsilon comparison.
*/
private static boolean matricesEquivalent(Matrix4f a, Matrix4f b, float epsilon) {
// Compare all 16 elements
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
final float aVal = a.get(col, row);
final float bVal = b.get(col, row);
// If both are non-finite (NaN or Infinity), consider them equal
if (!Float.isFinite(aVal) && !Float.isFinite(bVal)) {
// Both non-finite: check if both NaN or both same Infinity
if (Float.isNaN(aVal) && Float.isNaN(bVal)) continue;
if (Float.isInfinite(aVal) && Float.isInfinite(bVal)) {
// Check same sign of infinity
if ((aVal > 0) == (bVal > 0)) continue;
}
return false; // Different non-finite values
}
// If one is finite and other is not, they differ
if (Float.isFinite(aVal) != Float.isFinite(bVal)) {
return false;
}
// Both finite: use epsilon comparison
if (Math.abs(aVal - bVal) > epsilon) {
return false;
}
}
}
return true;
}
public static void checkGLSM() {
String output = getGLSMErrorLog();
final String output = getGLSMErrorLog();
if (output == null) {
LOGGER.info("GLSM state matches!");
@@ -507,7 +657,7 @@ public class OpenGLDebugging {
}
public static void copyTexture(ResourceLocation resource, File output) {
Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource);
final Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource);
if (object != null) {
copyTexture(((ITextureObject) object).getGlTextureId(), output);
@@ -72,6 +72,11 @@ public class DSAARB extends DSAUnsupported {
return GLStateManager.getTexParameterOrDefault(texture, pname, () -> ARBDirectStateAccess.glGetTextureParameteri(texture, pname));
}
@Override
public int getTexLevelParameteri(int texture, int level, int pname) {
return ARBDirectStateAccess.glGetTextureLevelParameteri(texture, level, pname);
}
@Override
public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
ARBDirectStateAccess.glCopyTextureSubImage2D(destTexture, i, i1, i2, i3, i4, width, height);
@@ -79,7 +84,7 @@ public class DSAARB extends DSAUnsupported {
@Override
public void bindTextureToUnit(int unit, int texture) {
if(GLStateManager.getBoundTexture(unit) == texture) return;
if(GLStateManager.getBoundTextureForServerState(unit) == texture) return;
if (texture == 0) {
super.bindTextureToUnit(unit, texture);
@@ -23,6 +23,8 @@ public interface DSAAccess {
int getTexParameteri(int texture, int target, int pname);
int getTexLevelParameteri(int texture, int level, int pname);
void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height);
void bindTextureToUnit(int unit, int texture);
@@ -24,7 +24,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) {
// Get what cache thinks is bound - we'll restore to this to keep cache/GL in sync
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glBindTexture(target, cachedBinding); // Restore to cache value
@@ -32,7 +32,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -40,7 +40,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -48,7 +48,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -90,9 +90,18 @@ public class DSAUnsupported implements DSAAccess {
return GLStateManager.glGetTexParameteri(target, pname);
}
@Override
public int getTexLevelParameteri(int texture, int level, int pname) {
final int previous = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
final int result = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, pname);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previous);
return result;
}
@Override
public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
final int previous = GLStateManager.getBoundTexture();
final int previous = GLStateManager.getBoundTextureForServerState();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, destTexture);
GL11.glCopyTexSubImage2D(target, i, i1, i2, i3, i4, width, height);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous);
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
@@ -17,19 +18,49 @@ public class AccumulatedDraw {
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex; // Position in command list for state tracking
public final int matrixGeneration; // For batching: same generation = same transform context
public final int stateGeneration; // Same value = no state commands between draws, can merge
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
/**
* Last vertex restoration data for immediate mode draws.
* Null for tessellator draws (no restoration needed).
*/
public final RestoreData restoreData;
/**
* Holds last vertex attribute values for GL state restoration after VBO draw.
* Used to sync GLSM cache with actual GL state after VBO rendering.
*/
@Desugar
public record RestoreData(
float lastColorR, float lastColorG, float lastColorB, float lastColorA,
float lastNormalX, float lastNormalY, float lastNormalZ,
float lastTexCoordS, float lastTexCoordT) {}
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) {
this(quads, transform, flags, commandIndex, matrixGeneration, 0, null);
}
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) {
this(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration, null);
}
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration, RestoreData restoreData) {
// Deep copy quads - pooled quads are reused after callback
this.quads = ModelQuadUtil.deepCopyQuads(quads);
this.transform = new Matrix4f(transform); // Snapshot for runtime application
this.flags = flags;
this.commandIndex = commandIndex;
this.matrixGeneration = matrixGeneration;
this.stateGeneration = stateGeneration;
this.restoreData = restoreData;
}
@Override
public String toString() {
return String.format("AccumulatedDraw[quads=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]",
quads.size(), commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
return String.format("AccumulatedDraw[quads=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, flags=C%dT%dL%dN%d, restore=%s]",
quads.size(), commandIndex, matrixGeneration, stateGeneration, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0,
restoreData != null ? "yes" : "no");
}
}
@@ -16,13 +16,19 @@ public class AccumulatedLineDraw {
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex; // Position in command list for state tracking
public final int stateGeneration; // Same value = no state commands between draws, can merge
public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
this(lines, transform, flags, commandIndex, 0);
}
public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int stateGeneration) {
// Copy lines - the source list may be cleared
this.lines = new ArrayList<>(lines);
this.transform = new Matrix4f(transform); // Snapshot for runtime application
this.flags = flags;
this.commandIndex = commandIndex;
this.stateGeneration = stateGeneration;
}
@Override
@@ -21,13 +21,21 @@ public class AccumulatedPrimitiveDraw {
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex;
public final int matrixGeneration; // For batching: same generation = same transform context
public final int stateGeneration; // Same value = no state commands between draws, can merge
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) {
this(primitives, transform, flags, commandIndex, matrixGeneration, 0);
}
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) {
// Deep copy primitives - pooled primitives are reused after callback
this.primitives = deepCopyPrimitives(primitives);
this.transform = new Matrix4f(transform);
this.flags = flags;
this.commandIndex = commandIndex;
this.matrixGeneration = matrixGeneration;
this.stateGeneration = stateGeneration;
}
/**
@@ -50,8 +58,8 @@ public class AccumulatedPrimitiveDraw {
@Override
public String toString() {
return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, mode=%d, flags=C%dT%dL%dN%d]",
primitives.size(), commandIndex, flags.drawMode,
return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, mode=%d, flags=C%dT%dL%dN%d]",
primitives.size(), commandIndex, matrixGeneration, stateGeneration, flags.drawMode,
flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0,
flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
}
@@ -14,6 +14,12 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
public final class CommandBuffer {
private static final int DEFAULT_CAPACITY = 4096; // Guess at typical display list size
// Flag bits for DRAW_RANGE_RESTORE command
public static final int FLAG_HAS_BRIGHTNESS = 1 << 0;
public static final int FLAG_HAS_COLOR = 1 << 1;
public static final int FLAG_HAS_NORMALS = 1 << 2;
public static final int FLAG_HAS_TEXTURE = 1 << 3;
private ByteBuffer buffer;
private long basePointer;
private long writePointer;
@@ -137,22 +143,19 @@ public final class CommandBuffer {
writeInt(0); // unused padding
}
public void writeLoadIdentity(int matrixMode) {
ensureCapacity(8);
public void writeLoadIdentity() {
ensureCapacity(4);
writeInt(GLCommand.LOAD_IDENTITY);
writeInt(matrixMode);
}
public void writePushMatrix(int matrixMode) {
ensureCapacity(8);
public void writePushMatrix() {
ensureCapacity(4);
writeInt(GLCommand.PUSH_MATRIX);
writeInt(matrixMode);
}
public void writePopMatrix(int matrixMode) {
ensureCapacity(8);
public void writePopMatrix() {
ensureCapacity(4);
writeInt(GLCommand.POP_MATRIX);
writeInt(matrixMode);
}
public void writeStencilMask(int mask) {
@@ -415,29 +418,26 @@ public final class CommandBuffer {
// === Double commands ===
public void writeTranslate(int matrixMode, double x, double y, double z) {
ensureCapacity(32);
public void writeTranslate(double x, double y, double z) {
ensureCapacity(28);
writeInt(GLCommand.TRANSLATE);
writeInt(matrixMode);
writeDouble(x);
writeDouble(y);
writeDouble(z);
}
public void writeRotate(int matrixMode, double angle, double x, double y, double z) {
ensureCapacity(40);
public void writeRotate(double angle, double x, double y, double z) {
ensureCapacity(36);
writeInt(GLCommand.ROTATE);
writeInt(matrixMode);
writeDouble(angle);
writeDouble(x);
writeDouble(y);
writeDouble(z);
}
public void writeScale(int matrixMode, double x, double y, double z) {
ensureCapacity(32);
public void writeScale(double x, double y, double z) {
ensureCapacity(28);
writeInt(GLCommand.SCALE);
writeInt(matrixMode);
writeDouble(x);
writeDouble(y);
writeDouble(z);
@@ -467,17 +467,15 @@ public final class CommandBuffer {
// === Matrix commands ===
public void writeMultMatrix(int matrixMode, Matrix4f matrix) {
ensureCapacity(72);
public void writeMultMatrix(Matrix4f matrix) {
ensureCapacity(68);
writeInt(GLCommand.MULT_MATRIX);
writeInt(matrixMode);
writeMatrix4f(matrix);
}
public void writeLoadMatrix(int matrixMode, Matrix4f matrix) {
ensureCapacity(72);
public void writeLoadMatrix(Matrix4f matrix) {
ensureCapacity(68);
writeInt(GLCommand.LOAD_MATRIX);
writeInt(matrixMode);
writeMatrix4f(matrix);
}
@@ -559,6 +557,58 @@ public final class CommandBuffer {
writeInt(hasBrightness ? 1 : 0);
}
/**
* Write a DRAW_RANGE_RESTORE command that draws a VBO range and restores GL current state after.
* Used for immediate mode VBOs to restore GL_CURRENT_COLOR, GL_CURRENT_NORMAL, GL_CURRENT_TEXTURE_COORDS.
*
* @param vboIndex Index into ownedVbos array
* @param startVertex First vertex to draw
* @param vertexCount Number of vertices to draw
* @param hasBrightness True if VBO has brightness/lightmap data
* @param hasColor True if color should be restored after draw
* @param hasNormals True if normal should be restored after draw
* @param hasTexture True if texcoord should be restored after draw
* @param lastColorR Last vertex's red color component
* @param lastColorG Last vertex's green color component
* @param lastColorB Last vertex's blue color component
* @param lastColorA Last vertex's alpha color component
* @param lastNormalX Last vertex's normal X
* @param lastNormalY Last vertex's normal Y
* @param lastNormalZ Last vertex's normal Z
* @param lastTexS Last vertex's texture S coordinate
* @param lastTexT Last vertex's texture T coordinate
*/
public void writeDrawRangeRestore(
int vboIndex, int startVertex, int vertexCount,
boolean hasBrightness, boolean hasColor, boolean hasNormals, boolean hasTexture,
float lastColorR, float lastColorG, float lastColorB, float lastColorA,
float lastNormalX, float lastNormalY, float lastNormalZ,
float lastTexS, float lastTexT
) {
ensureCapacity(56);
writeInt(GLCommand.DRAW_RANGE_RESTORE);
writeInt(vboIndex);
writeInt(startVertex);
writeInt(vertexCount);
int flags = (hasBrightness ? FLAG_HAS_BRIGHTNESS : 0)
| (hasColor ? FLAG_HAS_COLOR : 0)
| (hasNormals ? FLAG_HAS_NORMALS : 0)
| (hasTexture ? FLAG_HAS_TEXTURE : 0);
writeInt(flags);
// Last color (4 floats = 16 bytes)
writeFloat(lastColorR);
writeFloat(lastColorG);
writeFloat(lastColorB);
writeFloat(lastColorA);
// Last normal (3 floats = 12 bytes)
writeFloat(lastNormalX);
writeFloat(lastNormalY);
writeFloat(lastNormalZ);
// Last texcoord (2 floats = 8 bytes)
writeFloat(lastTexS);
writeFloat(lastTexT);
}
public void writeCallList(int listId) {
ensureCapacity(8);
writeInt(GLCommand.CALL_LIST);
@@ -11,6 +11,7 @@ import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import static com.gtnewhorizons.angelica.glsm.recording.CommandBuffer.*;
/**
* Executes commands from a CommandBuffer
@@ -96,28 +97,13 @@ public final class CommandBufferExecutor {
ptr += 4; // Skip unused padding
}
case GLCommand.LOAD_IDENTITY -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.PUSH_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glPushMatrix();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.POP_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glPopMatrix();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.STENCIL_MASK -> {
GLStateManager.glStencilMask(memGetInt(ptr));
@@ -346,38 +332,26 @@ public final class CommandBufferExecutor {
// === Double commands ===
case GLCommand.TRANSLATE -> {
final int mode = memGetInt(ptr);
final double x = memGetDouble(ptr + 4);
final double y = memGetDouble(ptr + 12);
final double z = memGetDouble(ptr + 20);
ptr += 28;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double x = memGetDouble(ptr);
final double y = memGetDouble(ptr + 8);
final double z = memGetDouble(ptr + 16);
ptr += 24;
GLStateManager.glTranslated(x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.ROTATE -> {
final int mode = memGetInt(ptr);
final double angle = memGetDouble(ptr + 4);
final double x = memGetDouble(ptr + 12);
final double y = memGetDouble(ptr + 20);
final double z = memGetDouble(ptr + 28);
ptr += 36;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double angle = memGetDouble(ptr);
final double x = memGetDouble(ptr + 8);
final double y = memGetDouble(ptr + 16);
final double z = memGetDouble(ptr + 24);
ptr += 32;
GLStateManager.glRotated(angle, x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.SCALE -> {
final int mode = memGetInt(ptr);
final double x = memGetDouble(ptr + 4);
final double y = memGetDouble(ptr + 12);
final double z = memGetDouble(ptr + 20);
ptr += 28;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double x = memGetDouble(ptr);
final double y = memGetDouble(ptr + 8);
final double z = memGetDouble(ptr + 16);
ptr += 24;
GLStateManager.glScaled(x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.ORTHO -> {
final double left = memGetDouble(ptr);
@@ -402,32 +376,23 @@ public final class CommandBufferExecutor {
// === Matrix commands ===
case GLCommand.MULT_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
// Mode-agnostic: just multiply current matrix
MATRIX_BUFFER.clear();
for (int i = 0; i < 16; i++) {
MATRIX_BUFFER.put(memGetFloat(ptr));
ptr += 4;
}
MATRIX_BUFFER.flip();
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glMultMatrix(MATRIX_BUFFER);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.LOAD_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
MATRIX_BUFFER.clear();
for (int i = 0; i < 16; i++) {
MATRIX_BUFFER.put(memGetFloat(ptr));
ptr += 4;
}
MATRIX_BUFFER.flip();
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glLoadMatrix(MATRIX_BUFFER);
GLStateManager.glMatrixMode(savedMode);
}
// === Buffer commands ===
@@ -494,6 +459,40 @@ public final class CommandBufferExecutor {
vbo.draw(start, count);
vbo.cleanupState();
}
case GLCommand.DRAW_RANGE_RESTORE -> {
// Draw VBO range then restore GL current state from last vertex attributes
final int vboIndex = memGetInt(ptr);
final int start = memGetInt(ptr + 4);
final int count = memGetInt(ptr + 8);
final int flags = memGetInt(ptr + 12);
// Draw the VBO
final VertexBuffer vbo = ownedVbos[vboIndex];
vbo.setupState();
vbo.draw(start, count);
vbo.cleanupState();
// Restore attributes based on flags
if ((flags & FLAG_HAS_COLOR) != 0) {
final float r = memGetFloat(ptr + 16);
final float g = memGetFloat(ptr + 20);
final float b = memGetFloat(ptr + 24);
final float a = memGetFloat(ptr + 28);
GLStateManager.glColor4f(r, g, b, a);
}
if ((flags & FLAG_HAS_NORMALS) != 0) {
final float nx = memGetFloat(ptr + 32);
final float ny = memGetFloat(ptr + 36);
final float nz = memGetFloat(ptr + 40);
GLStateManager.glNormal3f(nx, ny, nz);
}
if ((flags & FLAG_HAS_TEXTURE) != 0) {
final float s = memGetFloat(ptr + 44);
final float t = memGetFloat(ptr + 48);
GLStateManager.glTexCoord2f(s, t);
}
ptr += 52; // Skip full command size (56 - 4 for cmd already read)
}
case GLCommand.CALL_LIST -> {
final int listId = memGetInt(ptr);
ptr += 4;
@@ -19,92 +19,53 @@ public final class CommandBufferProcessor {
public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) {
switch (opcode) {
// === MODELVIEW matrix commands - accumulate instead of copying ===
case GLCommand.TRANSLATE -> {
final int mode = raw.readInt();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.translate(x, y, z);
} else {
out.writeTranslate(mode, x, y, z);
}
}
case GLCommand.ROTATE -> {
final int mode = raw.readInt();
final double angle = raw.readDouble();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.rotate(angle, x, y, z);
} else {
out.writeRotate(mode, angle, x, y, z);
}
}
case GLCommand.SCALE -> {
final int mode = raw.readInt();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.scale(x, y, z);
} else {
out.writeScale(mode, x, y, z);
}
}
// === MultMatrix - already collapsed transforms from flushMatrix() ===
case GLCommand.MULT_MATRIX -> {
final int mode = raw.readInt();
raw.readMatrix4f(tempMatrix);
if (mode == GL11.GL_MODELVIEW) {
opt.multMatrix(tempMatrix);
} else {
out.writeMultMatrix(mode, tempMatrix);
}
}
case GLCommand.LOAD_IDENTITY -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
if (opt.checkAndClearAbsoluteMatrix()) {
out.writeLoadIdentity(mode);
}
opt.loadIdentity();
} else {
out.writeLoadIdentity(mode);
}
}
case GLCommand.LOAD_MATRIX -> {
final int mode = raw.readInt();
raw.readMatrix4f(tempMatrix);
if (mode == GL11.GL_MODELVIEW) {
opt.emitPendingTransform(out);
out.writeLoadMatrix(mode, tempMatrix);
opt.loadIdentity();
opt.markAbsoluteMatrix();
} else {
out.writeLoadMatrix(mode, tempMatrix);
}
opt.multMatrix(tempMatrix); // accumulated = accumulated * tempMatrix
out.writeMultMatrix(tempMatrix); // Copy to output
opt.markLastEmittedAsAccumulated(); // lastEmitted = accumulated (what GL now has)
}
// === Stack operations - update optimizer state and copy ===
// === Load commands - flush pending, emit, reset accumulator ===
case GLCommand.LOAD_IDENTITY -> {
opt.emitPendingTransform(out); // Emit any pending transforms first
out.writeLoadIdentity(); // Always emit LoadIdentity
opt.loadIdentity(); // Reset accumulated to identity
opt.resetLastEmitted(); // Reset lastEmitted to identity
opt.checkAndClearAbsoluteMatrix(); // Clear the flag if set
}
case GLCommand.LOAD_MATRIX -> {
raw.readMatrix4f(tempMatrix);
opt.emitPendingTransform(out);
out.writeLoadMatrix(tempMatrix);
opt.loadIdentity();
opt.resetLastEmitted(); // Reset lastEmitted to identity
opt.markAbsoluteMatrix();
}
// === Stack operations - flush/update optimizer state and copy ===
case GLCommand.PUSH_MATRIX -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
opt.emitPendingTransform(out);
opt.push();
}
out.writePushMatrix(mode);
opt.emitPendingTransform(out);
opt.push();
// Reset accumulated/lastEmitted to identity after push.
opt.loadIdentity();
opt.resetLastEmitted();
out.writePushMatrix();
}
case GLCommand.POP_MATRIX -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
opt.pop();
}
out.writePopMatrix(mode);
opt.pop();
out.writePopMatrix();
}
// === Barriers - emit pending transform before copying ===
case GLCommand.MATRIX_MODE -> {
final int mode = raw.readInt();
opt.emitPendingTransform(out); // Pending transforms apply to OLD mode
out.writeMatrixMode(mode);
opt.loadIdentity(); // Reset accumulated for new mode
opt.resetLastEmitted(); // Reset lastEmitted for new mode
}
case GLCommand.CALL_LIST -> {
final int listId = raw.readInt();
opt.emitPendingTransform(out);
@@ -150,9 +111,9 @@ public final class CommandBufferProcessor {
case GLCommand.USE_PROGRAM -> out.writeUseProgram(raw.readInt());
case GLCommand.PUSH_ATTRIB -> out.writePushAttrib(raw.readInt());
case GLCommand.POP_ATTRIB -> { raw.readInt(); out.writePopAttrib(); }
case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity(raw.readInt());
case GLCommand.PUSH_MATRIX -> out.writePushMatrix(raw.readInt());
case GLCommand.POP_MATRIX -> out.writePopMatrix(raw.readInt());
case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity();
case GLCommand.PUSH_MATRIX -> out.writePushMatrix();
case GLCommand.POP_MATRIX -> out.writePopMatrix();
case GLCommand.STENCIL_MASK -> out.writeStencilMask(raw.readInt());
case GLCommand.DEPTH_MASK -> out.writeDepthMask(raw.readInt() != 0);
case GLCommand.FRONT_FACE -> out.writeFrontFace(raw.readInt());
@@ -202,15 +163,15 @@ public final class CommandBufferProcessor {
case GLCommand.TEX_PARAMETERF -> out.writeTexParameterf(raw.readInt(), raw.readInt(), raw.readFloat());
// Double commands
case GLCommand.TRANSLATE -> out.writeTranslate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ROTATE -> out.writeRotate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.SCALE -> out.writeScale(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.TRANSLATE -> out.writeTranslate(raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ROTATE -> out.writeRotate(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.SCALE -> out.writeScale(raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ORTHO -> out.writeOrtho(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.FRUSTUM -> out.writeFrustum(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
// Matrix commands
case GLCommand.MULT_MATRIX -> { int mode = raw.readInt(); out.writeMultMatrix(mode, raw.readMatrix4f(tempMatrix)); }
case GLCommand.LOAD_MATRIX -> { int mode = raw.readInt(); out.writeLoadMatrix(mode, raw.readMatrix4f(tempMatrix)); }
case GLCommand.MULT_MATRIX -> { out.writeMultMatrix(raw.readMatrix4f(tempMatrix)); }
case GLCommand.LOAD_MATRIX -> { out.writeLoadMatrix(raw.readMatrix4f(tempMatrix)); }
// FloatBuffer commands (inline 4 floats max)
case GLCommand.FOG -> {
@@ -265,11 +226,17 @@ public final class CommandBufferProcessor {
/**
* Lightweight transform optimizer for buffer-to-buffer processing.
* Tracks accumulated MODELVIEW transform and emits MultMatrix commands when needed.
* Tracks accumulated transform (mode-agnostic) and emits MultMatrix commands when needed.
*
* <p>This optimizer processes raw transform commands (TRANSLATE, ROTATE, SCALE) and
* collapses them into single MultMatrix commands at barriers. It must stay synchronized
* with the relativeTransform tracking in DisplayListManager - both systems must reset
* at the same barriers (MatrixMode, LoadIdentity, LoadMatrix, Push/Pop).</p>
*/
public static class BufferTransformOptimizer {
private final Matrix4f accumulated = new Matrix4f();
private final Matrix4f lastEmitted = new Matrix4f();
private final Matrix4f delta = new Matrix4f(); // Reused for delta computation
private final Deque<Matrix4f> stack = new ArrayDeque<>();
private boolean absoluteMatrixFlag = false;
@@ -278,18 +245,6 @@ public final class CommandBufferProcessor {
lastEmitted.identity();
}
public void translate(double x, double y, double z) {
accumulated.translate((float) x, (float) y, (float) z);
}
public void rotate(double angle, double x, double y, double z) {
accumulated.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z);
}
public void scale(double x, double y, double z) {
accumulated.scale((float) x, (float) y, (float) z);
}
public void multMatrix(Matrix4f m) {
accumulated.mul(m);
}
@@ -326,6 +281,18 @@ public final class CommandBufferProcessor {
return was;
}
public void resetLastEmitted() {
lastEmitted.identity();
}
public void setLastEmitted(Matrix4f m) {
lastEmitted.set(m);
}
public void markLastEmittedAsAccumulated() {
lastEmitted.set(accumulated);
}
public void emitPendingTransform(CommandBuffer out) {
if (!accumulated.equals(lastEmitted)) {
emitTransformTo(out, accumulated);
@@ -338,10 +305,10 @@ public final class CommandBufferProcessor {
}
if (DisplayListManager.isIdentity(lastEmitted)) {
out.writeMultMatrix(GL11.GL_MODELVIEW, target);
out.writeMultMatrix(target);
} else {
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
out.writeMultMatrix(GL11.GL_MODELVIEW, delta);
delta.set(lastEmitted).invert().mul(target);
out.writeMultMatrix(delta);
}
lastEmitted.set(target);
}
@@ -132,43 +132,28 @@ public class CommandRecorder {
commandCount++;
}
public void recordLoadIdentity(int matrixMode) {
buffer.writeLoadIdentity(matrixMode);
public void recordLoadIdentity() {
buffer.writeLoadIdentity();
commandCount++;
}
public void recordPushMatrix(int matrixMode) {
buffer.writePushMatrix(matrixMode);
public void recordPushMatrix() {
buffer.writePushMatrix();
commandCount++;
}
public void recordPopMatrix(int matrixMode) {
buffer.writePopMatrix(matrixMode);
public void recordPopMatrix() {
buffer.writePopMatrix();
commandCount++;
}
public void recordTranslate(int matrixMode, double x, double y, double z) {
buffer.writeTranslate(matrixMode, x, y, z);
public void recordMultMatrix(Matrix4f matrix) {
buffer.writeMultMatrix(matrix);
commandCount++;
}
public void recordRotate(int matrixMode, double angle, double x, double y, double z) {
buffer.writeRotate(matrixMode, angle, x, y, z);
commandCount++;
}
public void recordScale(int matrixMode, double x, double y, double z) {
buffer.writeScale(matrixMode, x, y, z);
commandCount++;
}
public void recordMultMatrix(int matrixMode, Matrix4f matrix) {
buffer.writeMultMatrix(matrixMode, matrix);
commandCount++;
}
public void recordLoadMatrix(int matrixMode, Matrix4f matrix) {
buffer.writeLoadMatrix(matrixMode, matrix);
public void recordLoadMatrix(Matrix4f matrix) {
buffer.writeLoadMatrix(matrix);
commandCount++;
}
@@ -22,6 +22,12 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
* <p>The ownedVbos array contains VBOs that are referenced by DrawRange commands.
*/
public final class CompiledDisplayList {
/**
* Empty display list singleton. Per OpenGL spec, an empty list is still valid.
* This instance does nothing when rendered and is never deleted (shared singleton).
*/
public static final CompiledDisplayList EMPTY = new CompiledDisplayList(null, null, null);
private final ByteBuffer commandBuffer; // Off-heap command storage, must be freed
private final Object[] complexObjects; // Complex commands (TexImage2D, etc.)
private final VertexBuffer[] ownedVbos; // GPU resources referenced by index
@@ -97,14 +103,14 @@ public final class CompiledDisplayList {
* Used for testing to verify optimization results.
*/
public Int2IntMap getCommandCounts() {
Int2IntMap counts = new Int2IntOpenHashMap();
final Int2IntMap counts = new Int2IntOpenHashMap();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return counts;
}
long ptr = memAddress(commandBuffer);
long end = ptr + commandBuffer.limit();
final long end = ptr + commandBuffer.limit();
while (ptr < end) {
int cmd = memGetInt(ptr);
final int cmd = memGetInt(ptr);
counts.mergeInt(cmd, 1, Integer::sum);
ptr += getCommandSize(cmd, ptr);
}
@@ -116,14 +122,14 @@ public final class CompiledDisplayList {
* Used for testing to verify command ordering.
*/
public IntList getCommandOpcodes() {
IntList opcodes = new IntArrayList();
final IntList opcodes = new IntArrayList();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return opcodes;
}
long ptr = memAddress(commandBuffer);
long end = ptr + commandBuffer.limit();
final long end = ptr + commandBuffer.limit();
while (ptr < end) {
int cmd = memGetInt(ptr);
final int cmd = memGetInt(ptr);
opcodes.add(cmd);
ptr += getCommandSize(cmd, ptr);
}
@@ -135,12 +141,14 @@ public final class CompiledDisplayList {
*/
private static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
// Opcode-only commands (4 bytes)
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
// Single int commands (8 bytes)
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.LOAD_IDENTITY,
GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.STENCIL_MASK,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8;
@@ -161,22 +169,32 @@ public final class CompiledDisplayList {
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR,
GLCommand.DRAW_RANGE -> 20;
// DRAW_RANGE_RESTORE: 56 bytes
// [cmd:4][vboIndex:4][start:4][count:4][flags:4][color:16f][normal:12f][texcoord:8f]
case GLCommand.DRAW_RANGE_RESTORE -> 56;
// DRAW_BUFFER: 8 bytes [cmd:4][mode:4]
case GLCommand.DRAW_BUFFER -> 8;
// DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8]
case GLCommand.DRAW_BUFFERS -> 40;
// Double commands
case GLCommand.TRANSLATE, GLCommand.SCALE -> 32; // cmd + mode + 3 doubles
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles
case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double
case GLCommand.ROTATE -> 40; // cmd + mode + 4 doubles
case GLCommand.ROTATE -> 36; // cmd + 4 doubles
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles
// Matrix commands (72 bytes)
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 72;
// Matrix commands
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats
// Buffer commands (variable, read count)
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
int count = memGetInt(ptr + 8); // pname at +4, count at +8
final int count = memGetInt(ptr + 8); // pname at +4, count at +8
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
yield 16 + count * 4;
}
@@ -92,6 +92,12 @@ public final class GLCommand {
public static final int CALL_LIST = 101; // [cmd:4][listId:4] = 8 bytes
public static final int DRAW_BUFFER = 102; // [cmd:4][mode:4] = 8 bytes
public static final int DRAW_BUFFERS = 103; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers)
/**
* Draw VBO range with attribute restoration after draw.
* Used for immediate mode VBOs to restore GL current state (color, normal, texcoord).
*/
public static final int DRAW_RANGE_RESTORE = 104; // [cmd:4][vboIndex:4][start:4][count:4][flags:4]
// [lastColor:16f][lastNormal:12f][lastTexCoord:8f] = 56 bytes
// === Complex object reference ===
public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes
@@ -165,6 +171,7 @@ public final class GLCommand {
case CALL_LIST -> "CALL_LIST";
case DRAW_BUFFER -> "DRAW_BUFFER";
case DRAW_BUFFERS -> "DRAW_BUFFERS";
case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE";
case COMPLEX_REF -> "COMPLEX_REF";
default -> "UNKNOWN(" + opcode + ")";
};
@@ -164,6 +164,31 @@ public class ImmediateModeRecorder {
throw new IllegalStateException("glEnd called without glBegin");
}
// Capture last vertex attributes BEFORE clearing currentVertices
// These will be used to restore GL current state after VBO playback
float lastColorR = 1.0f, lastColorG = 1.0f, lastColorB = 1.0f, lastColorA = 1.0f;
float lastNormalX = 0.0f, lastNormalY = 0.0f, lastNormalZ = 1.0f;
float lastTexS = 0.0f, lastTexT = 0.0f;
if (!currentVertices.isEmpty()) {
ImmediateVertex last = currentVertices.get(currentVertices.size() - 1);
// Unpack color from ABGR format
lastColorR = (last.color & 0xFF) / 255.0f;
lastColorG = ((last.color >> 8) & 0xFF) / 255.0f;
lastColorB = ((last.color >> 16) & 0xFF) / 255.0f;
lastColorA = ((last.color >> 24) & 0xFF) / 255.0f;
// Unpack normal from NormI8 format (signed bytes packed into int)
lastNormalX = NormI8.unpackX(last.normal);
lastNormalY = NormI8.unpackY(last.normal);
lastNormalZ = NormI8.unpackZ(last.normal);
// Texture coords are stored directly as floats
lastTexS = last.texU;
lastTexT = last.texV;
}
// Convert this primitive's vertices to quads or lines
convertPrimitiveToQuads();
this.currentVertices.clear();
@@ -188,7 +213,10 @@ public class ImmediateModeRecorder {
quads.clear();
lineVertices.clear();
return new Result(resultQuads, resultLines, flags);
return new Result(resultQuads, resultLines, flags,
lastColorR, lastColorG, lastColorB, lastColorA,
lastNormalX, lastNormalY, lastNormalZ,
lastTexS, lastTexT);
}
/**
@@ -520,14 +548,28 @@ public class ImmediateModeRecorder {
hasNormal = false;
// Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec
return new Result(resultQuads, resultLines, flags);
// For getQuadsAndClear, we don't have last vertex data (it was cleared in end())
// Use default values - this method is for edge cases/cleanup anyway
return new Result(resultQuads, resultLines, flags,
1.0f, 1.0f, 1.0f, 1.0f, // Default white color
0.0f, 0.0f, 1.0f, // Default +Z normal
0.0f, 0.0f); // Default (0,0) texcoord
}
/**
* Result of immediate mode recording: quads, lines, and their attribute flags.
* Result of immediate mode recording: quads, lines, attribute flags, and last vertex state.
* The last vertex state is used to restore GL_CURRENT_COLOR etc. after VBO playback.
*/
@com.github.bsideup.jabel.Desugar
public record Result(List<ModelQuadViewMutable> quads, List<LineVertex> lines, CapturingTessellator.Flags flags) {}
public record Result(
List<ModelQuadViewMutable> quads,
List<LineVertex> lines,
CapturingTessellator.Flags flags,
// Last vertex attributes for restoration after VBO draw
float lastColorR, float lastColorG, float lastColorB, float lastColorA,
float lastNormalX, float lastNormalY, float lastNormalZ,
float lastTexCoordS, float lastTexCoordT
) {}
/**
* Reset all state including current texcoord/normal.
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import org.joml.Matrix4f;
/**
* Interface for matrix commands that can be accumulated during transform optimization.
* Implemented by TranslateCmd, RotateCmd, ScaleCmd, and MultMatrixCmd.
*/
public interface AccumulableMatrixCommand extends DisplayListCommand {
boolean isModelView();
void applyTo(Matrix4f matrix);
@Override
default boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
applyTo(ctx.getAccumulatedTransform());
return false; // Accumulated, don't emit
}
return true; // Non-MODELVIEW, emit as-is
}
}
@@ -1,61 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
/**
* Command: Call another display list (glCallList)
* Records a reference to another display list to be executed during playback.
* Per OpenGL spec: the referenced list is NOT executed during compilation,
* only the reference is recorded.
*
*/
@Desugar
public record CallListCmd(int listId) implements DisplayListCommand {
private static final Logger LOGGER = LogManager.getLogger("CallListCmd");
@Override
public void execute() {
final CompiledDisplayList compiled = GLStateManager.getDisplayList(listId);
if (compiled != null) {
GLDebug.pushGroup("CallList(" + listId + ")");
try {
compiled.render();
} finally {
GLDebug.popGroup();
}
} else {
// Fallback if list not found (shouldn't happen in normal operation)
LOGGER.warn("[CallListCmd] List {} not found in cache, using fallback glCallList", listId);
GLStateManager.glCallList(listId);
}
}
@Override
public void delete() {
// No resources to free - we just hold a reference
}
@Override
public boolean needsTransformSync() {
return true; // Nested list uses current GL matrix state
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
// Nested list needs current GL matrix state
ctx.emitPendingTransform();
return true; // Emit this command
}
@Override
public @NotNull String toString() {
return "CallList(" + listId + ")";
}
}
@@ -18,23 +18,6 @@ public interface DisplayListCommand {
// Most commands don't hold resources
}
/**
* Returns true if this barrier command requires the MODELVIEW transform to be
* synchronized with the accumulated state before execution.
*
* <p>This should return true for commands where the GL matrix state matters,
* such as CallListCmd (nested lists use current GL state) or PushAttribCmd
* with GL_TRANSFORM_BIT (saves the current matrix).</p>
*
* <p>Commands like PushAttribCmd with only GL_COLOR_BUFFER_BIT don't need
* transform sync because they don't interact with the matrix stack.</p>
*
* @return true if transform must be synced to accumulated before this barrier
*/
default boolean needsTransformSync() {
return false;
}
/**
* Handle this command during display list optimization.
*
@@ -1,44 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glLoadIdentity()
* Replaces the current matrix with the identity matrix for the specified matrix mode.
*/
@Desugar
public record LoadIdentityCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glLoadIdentity();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
// Check if we're at an absolute matrix (after LoadMatrix)
// If so, we must emit LoadIdentity to actually reset GL state
if (ctx.checkAndClearAbsoluteMatrix()) {
ctx.emit(this);
ctx.loadIdentity();
return false; // Already emitted
}
ctx.loadIdentity();
return false; // Accumulated, don't emit
}
return true; // Non-MODELVIEW, emit as-is
}
@Override
public @NotNull String toString() {
return String.format("LoadIdentity(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,75 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
/**
* Command: glLoadMatrix(matrix)
* Replaces the current matrix with the specified matrix for the given matrix mode.
*
* <p>Unlike MultMatrixCmd which can be absorbed into the accumulated transform,
* LoadMatrixCmd must always be emitted because it sets an absolute value, not a relative one.
* After a LoadMatrix command, the accumulated transform is reset to identity since
* subsequent transforms are relative to the newly loaded matrix.</p>
*/
@Desugar
public record LoadMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements DisplayListCommand {
/**
* Create a LoadMatrixCmd with pre-allocated buffer.
*/
public static LoadMatrixCmd create(Matrix4f matrix, int matrixMode) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
matrix.get(buffer);
buffer.rewind();
return new LoadMatrixCmd(new Matrix4f(matrix), matrixMode, buffer);
}
/**
* Create a LoadMatrixCmd from a FloatBuffer (copies the data).
*/
public static LoadMatrixCmd create(FloatBuffer src, int matrixMode) {
final Matrix4f matrix = new Matrix4f().set(src);
src.rewind();
return create(matrix, matrixMode);
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void execute() {
// Buffer already populated at construction, just rewind and use
buffer.rewind();
GLStateManager.glLoadMatrix(buffer);
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
// LoadMatrix sets an absolute value - emit any pending relative transform first
ctx.emitPendingTransform();
// Emit this command
ctx.emit(this);
// Reset accumulated to identity - subsequent transforms are relative to the loaded matrix
ctx.loadIdentity();
// Mark that GL is at an absolute value - LoadIdentity must emit to reset
ctx.markAbsoluteMatrix();
return false; // Already emitted
}
return true; // Non-MODELVIEW, emit as-is
}
@Override
public @NotNull String toString() {
return String.format("LoadMatrix(%s, %s)", GLDebug.getMatrixModeName(matrixMode), matrix);
}
}
@@ -11,34 +11,23 @@ import java.nio.FloatBuffer;
/**
* Command: glMultMatrix(matrix)
* Multiplies the specified matrix mode by the specified matrix.
* Multiplies the current matrix by the specified matrix.
*/
@Desugar
public record MultMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements AccumulableMatrixCommand {
public record MultMatrixCmd(Matrix4f matrix, FloatBuffer buffer) implements DisplayListCommand {
/**
* Create a MultMatrixCmd with pre-allocated buffer.
*/
public static MultMatrixCmd create(Matrix4f matrix, int matrixMode) {
public static MultMatrixCmd create(Matrix4f matrix) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
matrix.get(buffer);
buffer.rewind();
return new MultMatrixCmd(new Matrix4f(matrix), matrixMode, buffer);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f target) {
target.mul(matrix);
return new MultMatrixCmd(new Matrix4f(matrix), buffer);
}
@Override
public void execute() {
// Buffer already populated at construction, just rewind and use
buffer.rewind();
GLStateManager.glMultMatrix(buffer);
}
@@ -1,33 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
/**
* Command: glPopAttrib()
* Pops the server attribute stack.
*/
@Desugar
public record PopAttribCmd() implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPopAttrib();
}
@Override
public boolean needsTransformSync() {
return true;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
ctx.emitPendingTransform();
return true;
}
@Override
public @NotNull String toString() {
return "PopAttrib()";
}
}
@@ -1,36 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPopMatrix()
* Pops the current matrix from the matrix stack for the specified matrix mode.
*/
@Desugar
public record PopMatrixCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPopMatrix();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
ctx.popTransform();
}
return true; // Always emit Pop
}
@Override
public @NotNull String toString() {
return String.format("PopMatrix(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,38 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPushAttrib(mask)
* Pushes the server attribute stack.
*/
@Desugar
public record PushAttribCmd(int mask) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPushAttrib(mask);
}
@Override
public boolean needsTransformSync() {
// Only need transform sync if we're pushing transform state.
// GL_TRANSFORM_BIT includes the matrix mode and matrix stacks.
return (mask & GL11.GL_TRANSFORM_BIT) != 0;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (needsTransformSync()) {
ctx.emitPendingTransform();
}
return true;
}
@Override
public @NotNull String toString() {
return String.format("PushAttrib(0x%08X)", mask);
}
}
@@ -1,37 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPushMatrix()
* Pushes the current matrix onto the matrix stack for the specified matrix mode.
*/
@Desugar
public record PushMatrixCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPushMatrix();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
ctx.emitPendingTransform();
ctx.pushTransform();
}
return true; // Always emit Push
}
@Override
public @NotNull String toString() {
return String.format("PushMatrix(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glRotatef() or glRotated()
* Stores as doubles for precision.
*/
@Desugar
public record RotateCmd(double angle, double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
GLStateManager.glRotated(angle, x, y, z);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Rotate(%.2f deg, %.2f, %.2f, %.2f, %s)", angle, x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glScalef() or glScaled()
* Stores as doubles for precision.
*/
@Desugar
public record ScaleCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
GLStateManager.glScaled(x, y, z);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.scale((float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Scale(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,43 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glTranslatef() or glTranslated()
* Stores as doubles for precision.
*/
@Desugar
public record TranslateCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
// Save current mode
final int savedMode = GLStateManager.getMatrixMode().getMode();
// Switch to the mode this was recorded with
GLStateManager.glMatrixMode(matrixMode);
GLStateManager.glTranslated(x, y, z);
// Restore mode
GLStateManager.glMatrixMode(savedMode);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.translate((float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Translate(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -0,0 +1,56 @@
package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
/**
* BooleanStateStack for per-texture-unit state.
* Switches to correct unit (raw GL) before enable/disable calls.
*/
public class TextureUnitBooleanStateStack extends BooleanStateStack {
private final int unitIndex;
public TextureUnitBooleanStateStack(int glCap, int unitIndex) {
super(glCap);
this.unitIndex = unitIndex;
}
public TextureUnitBooleanStateStack(int glCap, int unitIndex, boolean initialState) {
super(glCap, initialState);
this.unitIndex = unitIndex;
}
@Override
public void setEnabled(boolean enabled) {
beforeModify();
setEnabledWithUnitSwitch(enabled);
}
@Override
public TextureUnitBooleanStateStack popDepth() {
if (savedDepth > 0) {
final boolean oldValue = stack[--savedDepth];
setEnabledWithUnitSwitch(oldValue);
}
return this;
}
private void setEnabledWithUnitSwitch(boolean enabled) {
final boolean bypass = GLStateManager.shouldBypassCache();
if (bypass || enabled != this.enabled) {
if (!bypass) this.enabled = enabled;
int currentUnit = GLStateManager.getActiveTextureUnit();
boolean needsSwitch = currentUnit != unitIndex;
if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + unitIndex);
if (enabled) GL11.glEnable(glCap); else GL11.glDisable(glCap);
if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentUnit);
}
}
public int getUnitIndex() {
return unitIndex;
}
}
@@ -27,13 +27,11 @@ public class BooleanState implements ISettableState<BooleanState> {
if (!bypass) {
this.enabled = enabled;
}
// Skip actual GL calls during display list recording (state tracking only)
if (!GLStateManager.isRecordingDisplayList()) {
if (enabled) {
GL11.glEnable(this.glCap);
} else {
GL11.glDisable(this.glCap);
}
// Always call GL - the calling method controls whether we reach here based on recording mode
if (enabled) {
GL11.glEnable(this.glCap);
} else {
GL11.glDisable(this.glCap);
}
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.glsm.states;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack;
import lombok.Getter;
import org.joml.Matrix4fStack;
@@ -10,36 +10,36 @@ import org.lwjgl.opengl.GL12;
public class TextureUnitArray {
private final TextureBindingStack[] bindings;
private final BooleanStateStack[] states;
private final BooleanStateStack[] texture1DStates;
private final BooleanStateStack[] texture3DStates;
private final BooleanStateStack[] texGenSStates;
private final BooleanStateStack[] texGenTStates;
private final BooleanStateStack[] texGenRStates;
private final BooleanStateStack[] texGenQStates;
private final TextureUnitBooleanStateStack[] states;
private final TextureUnitBooleanStateStack[] texture1DStates;
private final TextureUnitBooleanStateStack[] texture3DStates;
private final TextureUnitBooleanStateStack[] texGenSStates;
private final TextureUnitBooleanStateStack[] texGenTStates;
private final TextureUnitBooleanStateStack[] texGenRStates;
private final TextureUnitBooleanStateStack[] texGenQStates;
@Getter
public final Matrix4fStack[] textureMatricies;
public TextureUnitArray() {
bindings = new TextureBindingStack[GLStateManager.MAX_TEXTURE_UNITS];
states = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture1DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture3DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenSStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenTStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenRStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenQStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
states = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture1DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture3DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenSStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenTStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenRStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenQStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
textureMatricies = new Matrix4fStack[GLStateManager.MAX_TEXTURE_UNITS];
for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
bindings[i] = new TextureBindingStack();
states[i] = new BooleanStateStack(GL11.GL_TEXTURE_2D);
texture1DStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_1D);
texture3DStates[i] = new BooleanStateStack(GL12.GL_TEXTURE_3D);
texGenSStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_S);
texGenTStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_T);
texGenRStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_R);
texGenQStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_Q);
states[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_2D, i);
texture1DStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_1D, i);
texture3DStates[i] = new TextureUnitBooleanStateStack(GL12.GL_TEXTURE_3D, i);
texGenSStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_S, i);
texGenTStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_T, i);
texGenRStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_R, i);
texGenQStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_Q, i);
textureMatricies[i] = new Matrix4fStack(GLStateManager.MAX_TEXTURE_STACK_DEPTH);
}
}
@@ -48,31 +48,31 @@ public class TextureUnitArray {
return bindings[index];
}
public BooleanStateStack getTextureUnitStates(int index) {
public TextureUnitBooleanStateStack getTextureUnitStates(int index) {
return states[index];
}
public BooleanStateStack getTexture1DStates(int index) {
public TextureUnitBooleanStateStack getTexture1DStates(int index) {
return texture1DStates[index];
}
public BooleanStateStack getTexture3DStates(int index) {
public TextureUnitBooleanStateStack getTexture3DStates(int index) {
return texture3DStates[index];
}
public BooleanStateStack getTexGenSStates(int index) {
public TextureUnitBooleanStateStack getTexGenSStates(int index) {
return texGenSStates[index];
}
public BooleanStateStack getTexGenTStates(int index) {
public TextureUnitBooleanStateStack getTexGenTStates(int index) {
return texGenTStates[index];
}
public BooleanStateStack getTexGenRStates(int index) {
public TextureUnitBooleanStateStack getTexGenRStates(int index) {
return texGenRStates[index];
}
public BooleanStateStack getTexGenQStates(int index) {
public TextureUnitBooleanStateStack getTexGenQStates(int index) {
return texGenQStates[index];
}
@@ -1,6 +1,6 @@
package com.gtnewhorizons.angelica.glsm.texture;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import lombok.Getter;
import lombok.Setter;
import org.lwjgl.opengl.GL11;
@@ -12,7 +12,7 @@ public class TextureInfo {
protected int width = -1;
protected int height = -1;
@Getter @Setter protected int minFilter = GL11.GL_LINEAR_MIPMAP_LINEAR;
@Getter @Setter protected int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR;
@Getter @Setter protected int magFilter = GL11.GL_LINEAR;
@Getter @Setter protected int wrapS = GL11.GL_REPEAT;
@Getter @Setter protected int wrapT = GL11.GL_REPEAT;
@@ -29,36 +29,22 @@ public class TextureInfo {
public int getInternalFormat() {
if (internalFormat == -1) {
internalFormat = fetchLevelParameter(GL11.GL_TEXTURE_INTERNAL_FORMAT);
internalFormat = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT);
}
return internalFormat;
}
public int getWidth() {
if (width == -1) {
width = fetchLevelParameter(GL11.GL_TEXTURE_WIDTH);
width = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_WIDTH);
}
return width;
}
public int getHeight() {
if (height == -1) {
height = fetchLevelParameter(GL11.GL_TEXTURE_HEIGHT);
height = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_HEIGHT);
}
return height;
}
private int fetchLevelParameter(int pname) {
// Keep track of what texture was bound before
final int previousTextureBinding = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
// Bind this texture and grab the parameter from it.
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, id);
final int parameter = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, pname);
// Make sure to re-bind the previous texture to avoid issues.
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previousTextureBinding);
return parameter;
}
}
@@ -7,45 +7,73 @@ import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import java.nio.Buffer;
import java.util.concurrent.locks.ReentrantLock;
public class TextureInfoCache {
/**
* Adapted from Iris for use in GLSM
* Adapted from Iris for use in GLSM.
*
* This cache stores server-side texture state (parameters, dimensions) that is shared across GL contexts.
* Locking is only used during splash when multiple contexts exist.
*/
public static final TextureInfoCache INSTANCE = new TextureInfoCache();
public static final TextureInfoCache INSTANCE = new TextureInfoCache();
private final Int2ObjectMap<TextureInfo> cache = new Int2ObjectOpenHashMap<>();
private final Int2ObjectMap<TextureInfo> cache = new Int2ObjectOpenHashMap<>();
private final ReentrantLock lock = new ReentrantLock();
private TextureInfoCache() {
}
private TextureInfoCache() {
}
public TextureInfo getInfo(int id) {
if(id < 0 || !GLStateManager.isCachingEnabled()) return null;
return cache.computeIfAbsent(id, TextureInfo::new);
}
public TextureInfo getInfo(int id) {
if (id < 0) return null;
if (GLStateManager.isSplashComplete()) {
return cache.computeIfAbsent(id, TextureInfo::new);
}
lock.lock();
try {
return cache.computeIfAbsent(id, TextureInfo::new);
} finally {
lock.unlock();
}
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState());
if (info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
}
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTexture());
if(info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
}
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTexture());
if(info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
}
}
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState());
if (info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
}
}
public void onDeleteTexture(int id) {
if(id >= 0 && GLStateManager.isCachingEnabled()) cache.remove(id);
}
public void onDeleteTexture(int id) {
if (id < 0) return;
if (GLStateManager.isSplashComplete()) {
cache.remove(id);
return;
}
// During splash: lock for thread safety
lock.lock();
try {
cache.remove(id);
} finally {
lock.unlock();
}
}
}
@@ -129,7 +129,7 @@ public class ColorizeBlock {
static {
try {
reset();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -46,7 +46,7 @@ public class ColorizeEntity {
static {
try {
reset();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -36,7 +36,7 @@ public class ColorizeItem {
static {
try {
reset();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -63,7 +63,7 @@ public class ColorizeWorld {
static {
try {
reset();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -35,7 +35,7 @@ public class Colorizer {
static {
try {
reset();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CUSTOM_COLORS, 2) {
@@ -77,7 +77,7 @@ class PotionReplacer {
i);
}
}
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -50,7 +50,7 @@ public class BlockFaceMatcher {
if (!matcher.isAll()) {
return matcher;
}
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -49,7 +49,7 @@ public class CTMUtils {
Class.forName(MCPatcherUtils.RENDER_PASS_CLASS)
.getMethod("finish")
.invoke(null);
} catch (Throwable ignore) {}
} catch (Exception ignore) {}
TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CONNECTED_TEXTURES, 3) {
@@ -61,9 +61,7 @@ public class CTMUtils {
RenderPassAPI.instance.clear();
try {
GlassPaneRenderer.clear();
} catch (NoClassDefFoundError e) {
// nothing
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
renderBlockState.clear();
@@ -87,7 +87,7 @@ public class CustomAnimation implements Comparable<CustomAnimation> {
if (!pending.isEmpty()) {
try {
checkPendingAnimations();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.error("%d remaining animations cleared", pending.size());
pending.clear();
@@ -219,7 +219,7 @@ public class FancyDial {
return instance;
}
instance.finish();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
return null;
@@ -410,7 +410,7 @@ public class FancyDial {
}
ImageIO.write(image, "png", path);
logger.info("wrote %dx%d %s", image.getWidth(), image.getHeight(), path.getPath());
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@@ -143,7 +143,7 @@ public class FontUtils {
boolean[] isOverride = new boolean[charWidth.length];
try {
getCharWidthOverrides(filename, charWidthf, isOverride);
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
}
if (!isOverride[32]) {
@@ -47,7 +47,7 @@ abstract public class NBTRule {
} else {
return new Exact(tag, value);
}
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}
@@ -204,7 +204,7 @@ abstract public class NBTRule {
if (result != null && cl.isAssignableFrom(result.getClass())) {
return cl.cast(result);
}
} catch (Throwable e) {}
} catch (Exception e) {}
return null;
}
@@ -104,7 +104,7 @@ public class ResourceList {
try {
zipFile = new ZipFile(jar);
scanZipFile(zipFile);
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
} finally {
MCPatcherUtils.close(zipFile);
@@ -55,7 +55,7 @@ abstract public class TexturePackChangeHandler implements Comparable<TexturePack
try {
logger.info("initializing %s...", handler.name);
handler.initialize();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.severe("%s initialization failed", handler.name);
}
@@ -72,7 +72,7 @@ abstract public class TexturePackChangeHandler implements Comparable<TexturePack
try {
logger.info("refreshing %s...", handler.name);
handler.refresh();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.severe("%s refresh failed", handler.name);
}
@@ -105,7 +105,7 @@ abstract public class TexturePackChangeHandler implements Comparable<TexturePack
try {
logger.info("refreshing %s (pre)...", handler.name);
handler.beforeChange();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.severe("%s.beforeChange failed", handler.name);
}
@@ -123,7 +123,7 @@ abstract public class TexturePackChangeHandler implements Comparable<TexturePack
try {
logger.info("refreshing %s (post)...", handler.name);
handler.afterChange();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.severe("%s.afterChange failed", handler.name);
}
@@ -133,7 +133,7 @@ abstract public class TexturePackChangeHandler implements Comparable<TexturePack
TexturePackChangeHandler handler = handlers.get(i);
try {
handler.afterChange2();
} catch (Throwable e) {
} catch (Exception e) {
e.printStackTrace();
logger.severe("%s.afterChange2 failed", handler.name);
}
@@ -114,7 +114,7 @@ public abstract class ChunkRenderShaderBackend<T extends ChunkGraphicsState> imp
private static String getShaderSource(String path) {
try {
InputStream in = ShaderLoader.class.getResourceAsStream(path);
Throwable throwable = null;
Exception throwable = null;
String res;
try {
@@ -123,7 +123,7 @@ public abstract class ChunkRenderShaderBackend<T extends ChunkGraphicsState> imp
}
res = IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (Throwable tr) {
} catch (Exception tr) {
throwable = tr;
throw tr;
} finally {
@@ -131,7 +131,7 @@ public abstract class ChunkRenderShaderBackend<T extends ChunkGraphicsState> imp
if (throwable != null) {
try {
in.close();
} catch (Throwable var12) {
} catch (Exception var12) {
throwable.addSuppressed(var12);
}
} else {
+193 -1
View File
@@ -16,6 +16,9 @@ import net.coderbot.iris.config.IrisConfig;
import net.coderbot.iris.gl.shader.StandardMacros;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.transform.ShaderTransformer;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline;
import net.coderbot.iris.pipeline.PipelineManager;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
@@ -54,8 +57,18 @@ import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.zip.ZipError;
import java.util.zip.ZipException;
@@ -82,6 +95,8 @@ public class Iris {
private static String currentPackName;
@Getter
private static boolean initialized;
@Getter
private static int shaderPackLoadId = 0;
private static PipelineManager pipelineManager;
@Getter
@@ -99,6 +114,175 @@ public class Iris {
@Getter
private static boolean fallback;
/**
* Lazy executor for parallelizing shader transformations during shader pack loading.
* Creates threads on demand and shuts down after a period of inactivity.
*/
public static final class ShaderTransformExecutor {
private static final long IDLE_TIMEOUT_SECONDS = 120;
private static final int THREAD_COUNT = Math.max(2, Math.min(12, Runtime.getRuntime().availableProcessors() / 2));
private static final Object lock = new Object();
private static ExecutorService executor;
private static ScheduledExecutorService scheduler;
private static volatile long lastActivityTime;
private static final AtomicInteger inFlight = new AtomicInteger(0);
private static boolean idleCheckScheduled;
private ShaderTransformExecutor() {}
private static void noteActivity() {
lastActivityTime = System.nanoTime();
}
public static ExecutorService get() {
synchronized (lock) {
noteActivity();
if (executor != null && !executor.isShutdown()) {
return executor;
}
executor = new ForkJoinPool(
THREAD_COUNT,
pool -> {
ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
t.setName("Shader-Transform-" + t.getPoolIndex());
t.setDaemon(true);
return t;
},
null, // UncaughtExceptionHandler
true // asyncMode - FIFO, better for independent tasks
);
logger.debug("Created shader transform executor with " + THREAD_COUNT + " threads");
if (scheduler == null || scheduler.isShutdown()) {
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "Shader-Transform-Scheduler");
t.setDaemon(true);
return t;
});
}
if (!idleCheckScheduled) {
idleCheckScheduled = true;
scheduleIdleCheck(IDLE_TIMEOUT_SECONDS);
}
return executor;
}
}
private static void scheduleIdleCheck(long delaySeconds) {
try {
scheduler.schedule(ShaderTransformExecutor::checkIdleShutdown, delaySeconds, TimeUnit.SECONDS);
} catch (Exception e) {
// If scheduling fails, reset the flag so a future get() can try again
idleCheckScheduled = false;
logger.warn("Failed to schedule idle check", e);
}
}
/**
* Ensures the executor exists and begins spinning up worker threads.
* Intended for UI entrypoints (eg. shader settings screen open).
*/
public static void prepare() {
// Submit empty tasks to warm up all worker threads without blocking the UI thread.
for (int i = 0; i < THREAD_COUNT; i++) {
submitTracked(() -> { });
}
}
/**
* Warm up the threadpool by running a representative shader transformation.
*/
public static void warmup() {
final String vertexShader = "#version 120\nvoid main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }";
final String fragmentShader = "#version 120\nvoid main() { gl_FragColor = vec4(1.0); }";
try {
submitTracked(() -> {
TransformPatcher.patchComposite(vertexShader, null, fragmentShader);
TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true));
}).get();
} catch (Exception e) {
logger.warn("Warmup failed", e);
}
}
public static <T> CompletableFuture<T> submitTracked(Supplier<T> supplier) {
Objects.requireNonNull(supplier);
noteActivity();
inFlight.incrementAndGet();
try {
return CompletableFuture.supplyAsync(() -> {
try {
return supplier.get();
} finally {
noteActivity();
inFlight.decrementAndGet();
}
}, get());
} catch (Exception e) {
inFlight.decrementAndGet();
throw e;
}
}
public static CompletableFuture<Void> submitTracked(Runnable runnable) {
Objects.requireNonNull(runnable);
noteActivity();
inFlight.incrementAndGet();
try {
return CompletableFuture.runAsync(() -> {
try {
runnable.run();
} finally {
noteActivity();
inFlight.decrementAndGet();
}
}, get());
} catch (Exception e) {
inFlight.decrementAndGet();
throw e;
}
}
private static void checkIdleShutdown() {
synchronized (lock) {
final ExecutorService current = executor;
if (current == null || current.isShutdown()) {
// Executor already gone, shut down scheduler
if (scheduler != null && !scheduler.isShutdown()) {
scheduler.shutdown();
scheduler = null;
}
idleCheckScheduled = false;
return;
}
final long idleNanos = System.nanoTime() - lastActivityTime;
final long idleSeconds = TimeUnit.NANOSECONDS.toSeconds(idleNanos);
if (idleSeconds >= IDLE_TIMEOUT_SECONDS && inFlight.get() == 0) {
logger.debug("Shutting down idle shader transform executor after " + idleSeconds + " seconds");
current.shutdown();
executor = null;
scheduler.shutdown();
scheduler = null;
idleCheckScheduled = false;
// Clear transformation caches - no longer needed after loading
TransformPatcher.clearCache();
ShaderTransformer.clearCache();
} else {
// Still active (or in-flight), schedule another check.
final long remainingSeconds = Math.max(1, IDLE_TIMEOUT_SECONDS - idleSeconds + 1);
scheduleIdleCheck(remainingSeconds);
}
}
}
}
private static KeyBinding reloadKeybind;
private static KeyBinding toggleShadersKeybind;
private static KeyBinding shaderpackScreenKeybind;
@@ -194,6 +378,9 @@ public class Iris {
return;
}
// Warm up the threadpool so shader transformations are faster when we need them
ShaderTransformExecutor.warmup();
PBRTextureManager.INSTANCE.init();
// Only load the shader pack when we can access OpenGL
@@ -575,7 +762,12 @@ public class Iris {
try {
return new DeferredWorldRenderingPipeline(programs);
shaderPackLoadId++;
long startTime = System.nanoTime();
WorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs);
long endTime = System.nanoTime();
logger.info("[Load #{}] Total shaderpack load time for '{}': {} ms", shaderPackLoadId, currentPackName, String.format("%.1f", (endTime - startTime) / 1_000_000.0));
return pipeline;
} catch (Exception e) {
logger.error("Failed to create shader rendering pipeline, disabling shaders!", e);
// TODO: This should be reverted if a dimension change causes shaders to compile again
@@ -47,7 +47,7 @@ public class ShaderPackSelectionList extends IrisGuiSlot {
try {
names = Iris.getShaderpacksDirectoryManager().enumerate();
} catch (Throwable e) {
} catch (Exception e) {
Iris.logger.error("Error reading files while constructing selection UI", e);
// Not translating this since it's going to be seen very rarely,
@@ -79,6 +79,9 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable {
this.parent = parent;
// Prime the shader transform executor so reloads from this screen don't pay thread spin-up costs.
Iris.ShaderTransformExecutor.prepare();
String irisName = Iris.MODNAME; // + " " + Iris.getVersion(); // TEMP
if (Iris.INSTANCE.isDevelopmentEnvironment) {
@@ -32,6 +32,7 @@ import net.coderbot.iris.postprocess.BufferFlipper;
import net.coderbot.iris.postprocess.CenterDepthSampler;
import net.coderbot.iris.postprocess.CompositeRenderer;
import net.coderbot.iris.postprocess.FinalPassRenderer;
import net.coderbot.iris.postprocess.ProgramBuildContext;
import net.coderbot.iris.rendertarget.IRenderTargetExt;
import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture;
import net.coderbot.iris.rendertarget.RenderTargets;
@@ -78,8 +79,10 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntFunction;
import java.util.function.Supplier;
@@ -127,6 +130,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final SodiumTerrainPipeline sodiumTerrainPipeline;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> attributeTransforms;
private final HorizonRenderer horizonRenderer = new HorizonRenderer();
private final float sunPathRotation;
@@ -159,6 +164,27 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
public DeferredWorldRenderingPipeline(ProgramSet programs) {
Objects.requireNonNull(programs);
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> prepareTransformFutures = submitCompositeTransforms(programs.getPrepare());
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> deferredTransformFutures = submitCompositeTransforms(programs.getDeferred());
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> compositeTransformFutures = submitCompositeTransforms(programs.getComposite());
final CompletableFuture<Map<PatchShaderType, String>> finalTransformFuture =
programs.getCompositeFinal()
.filter(ProgramSource::isValid)
.map(DeferredWorldRenderingPipeline::submitCompositeTransform)
.orElse(null);
final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver);
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
final Optional<ProgramSource> shadowSource = programs.getShadow();
final CompletableFuture<Map<PatchShaderType, String>> sodiumTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> sodiumTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> sodiumShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
this.cloudSetting = programs.getPackDirectives().getCloudSetting();
this.shouldRenderUnderwaterOverlay = programs.getPackDirectives().underwaterOverlay();
this.shouldRenderVignette = programs.getPackDirectives().vignette();
@@ -239,31 +265,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
PatchedShaderPrinter.resetPrintState();
this.prepareRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getPrepare(), programs.getPrepareCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE),
programs.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms);
final ProgramBuildContext prepareBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), customUniforms);
final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms);
final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms);
this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare");
flippedAfterPrepare = flipper.snapshot();
this.deferredRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getDeferred(), programs.getDeferredCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED),
programs.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms);
this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred");
flippedAfterTranslucent = flipper.snapshot();
this.compositeRenderer = new CompositeRenderer(programs.getPackDirectives(), programs.getComposite(), programs.getCompositeCompute(), renderTargets,
customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL),
programs.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms);
this.finalPassRenderer = new FinalPassRenderer(programs, renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, flipper.snapshot(),
centerDepthSampler, shadowTargetsSupplier,
customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL),
this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms);
this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite");
this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final");
// [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)]
ProgramId[] ids = new ProgramId[] {
final ProgramId[] ids = new ProgramId[] {
ProgramId.Basic, ProgramId.Textured, ProgramId.TexturedLit,
ProgramId.SkyBasic, ProgramId.SkyTextured, ProgramId.SkyTextured,
null, null, ProgramId.Terrain,
@@ -288,14 +305,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
throw new IllegalStateException("Program ID table length mismatch");
}
ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
this.attributeTransforms = new HashMap<>();
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : attributeTransformFutures.entrySet()) {
try {
this.attributeTransforms.put(entry.getKey(), entry.getValue().join());
} catch (Exception e) {
Iris.logger.error("Failed to transform shader: {}", entry.getKey().getLeft(), e);
throw new RuntimeException("Shader transformation failed for " + entry.getKey().getLeft(), e);
}
}
Map<Pair<ProgramId, InputAvailability>, Pass> cachedPasses = new HashMap<>();
final Map<Pair<ProgramId, InputAvailability>, Pass> cachedPasses = new HashMap<>();
this.shadowComputes = createShadowComputes(programs.getShadowCompute());
this.table = new ProgramTable<>((condition, availability) -> {
int idx;
final int idx;
if (availability.texture && availability.lightmap) {
idx = 2;
@@ -311,10 +336,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
id = ids[idx];
}
ProgramId finalId = id;
final ProgramId finalId = id;
return cachedPasses.computeIfAbsent(Pair.of(id, availability), p -> {
ProgramSource source = resolver.resolveNullable(p.getLeft());
final ProgramSource source = resolver.resolveNullable(p.getLeft());
if (condition == RenderCondition.SHADOW) {
if (!shadowDirectives.isShadowEnabled().orElse(shadowRenderTargets != null)) {
@@ -427,7 +452,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
};
this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers,
shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages,
shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms);
shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms,
terrainSource.map(ProgramSource::getName).orElse(null),
translucentSource.map(ProgramSource::getName).orElse(null),
shadowSource.map(ProgramSource::getName).orElse(null),
sodiumTerrainFuture, sodiumTranslucentFuture, sodiumShadowFuture);
}
private RenderTargets getRenderTargets() {
@@ -592,12 +621,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
private Pass createPass(ProgramSource source, InputAvailability availability, boolean shadow, ProgramId id) {
// TODO: Properly handle empty shaders?
Map<PatchShaderType, String> transformed = TransformPatcher.patchAttributes(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new),
availability);
// Use pre-computed transform if available, otherwise transform synchronously
Pair<String, InputAvailability> key = Pair.of(source.getName(), availability);
Map<PatchShaderType, String> transformed = attributeTransforms.get(key);
if (transformed == null) {
// Fallback to synchronous transform if not pre-computed
transformed = TransformPatcher.patchAttributes(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new),
availability);
}
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
@@ -1266,4 +1302,59 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
PBRTextureManager.notifyPBRTexturesChanged();
}
}
private static final InputAvailability INPUT_NONE = new InputAvailability(false, false);
private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false);
private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true);
private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP };
private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
}
private static Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> submitCompositeTransforms(ProgramSource[] sources) {
// Count valid sources for initial capacity
int count = 0;
for (ProgramSource source : sources) {
if (source != null && source.isValid()) count++;
}
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>(count);
for (int i = 0; i < sources.length; i++) {
if (sources[i] != null && sources[i].isValid()) {
futures.put(i, submitCompositeTransform(sources[i]));
}
}
return futures;
}
private static Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>
submitAttributeTransforms(ProgramFallbackResolver resolver) {
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>();
final Set<String> processedSourceNames = new HashSet<>();
for (ProgramId id : ProgramId.values()) {
ProgramSource source = resolver.resolveNullable(id);
if (source != null && !processedSourceNames.contains(source.getName())) {
processedSourceNames.add(source.getName());
for (InputAvailability avail : INPUT_AVAILABILITIES) {
Pair<String, InputAvailability> key = Pair.of(source.getName(), avail);
futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null), avail)));
}
}
}
return futures;
}
private static CompletableFuture<Map<PatchShaderType, String>> submitSodiumTerrainTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchSodiumTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
}
@SafeVarargs
private static <T> Optional<T> first(Optional<T>... candidates) {
for (Optional<T> candidate : candidates) {
if (candidate.isPresent()) {
return candidate;
}
}
return Optional.empty();
}
}
@@ -5,9 +5,7 @@ import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.ExternallyManagedUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
@@ -16,8 +14,11 @@ import net.coderbot.iris.uniforms.custom.CustomUniforms;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntFunction;
import net.coderbot.iris.Iris;
public class SodiumTerrainPipeline {
Optional<String> terrainVertex = Optional.empty();
Optional<String> terrainGeometry = Optional.empty();
@@ -46,55 +47,63 @@ public class SodiumTerrainPipeline {
ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers,
IntFunction<ProgramSamplers> createShadowSamplers,
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms) {
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms,
String terrainSourceName,
String translucentSourceName,
String shadowSourceName,
CompletableFuture<Map<PatchShaderType, String>> terrainFuture,
CompletableFuture<Map<PatchShaderType, String>> translucentFuture,
CompletableFuture<Map<PatchShaderType, String>> shadowFuture) {
this.parent = Objects.requireNonNull(parent);
Optional<ProgramSource> terrainSource = first(programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic());
Optional<ProgramSource> translucentSource = first(programSet.getGbuffersWater(), terrainSource);
Optional<ProgramSource> shadowSource = programSet.getShadow();
this.programSet = programSet;
this.customUniforms = customUniforms;
terrainSource.ifPresent(sources -> {
Map<PatchShaderType, String> result = TransformPatcher.patchSodiumTerrain(
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getFragmentSource().orElse(null));
terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
if (terrainFuture != null) {
try {
Map<PatchShaderType, String> result = terrainFuture.join();
terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium",
terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null));
});
PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_sodium",
terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform terrain shader: {}", terrainSourceName, e);
throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e);
}
}
translucentSource.ifPresent(sources -> {
Map<PatchShaderType, String> result = TransformPatcher.patchSodiumTerrain(
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getFragmentSource().orElse(null));
translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
if (translucentFuture != null) {
try {
Map<PatchShaderType, String> result = translucentFuture.join();
translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium",
translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null));
});
PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_sodium",
translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform translucent shader: {}", translucentSourceName, e);
throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e);
}
}
shadowSource.ifPresent(sources -> {
Map<PatchShaderType, String> result = TransformPatcher.patchSodiumTerrain(
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getFragmentSource().orElse(null));
shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
if (shadowFuture != null) {
try {
Map<PatchShaderType, String> result = shadowFuture.join();
shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(sources.getName() + "_sodium",
shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null));
});
PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_sodium",
shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform shadow shader: {}", shadowSourceName, e);
throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e);
}
}
this.createTerrainSamplers = createTerrainSamplers;
this.createShadowSamplers = createShadowSamplers;
@@ -177,15 +186,4 @@ public class SodiumTerrainPipeline {
public void unbindFramebuffer() {
GlStateManager.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
}*/
@SafeVarargs
private static <T> Optional<T> first(Optional<T>... candidates) {
for (Optional<T> candidate : candidates) {
if (candidate.isPresent()) {
return candidate;
}
}
return Optional.empty();
}
}
@@ -2,15 +2,17 @@ package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.grammar.GLSLParser;
import org.taumc.glsl.Util;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
/**
* Implements AttributeShaderTransformer using glsl-transformer AST
* transformation methods.
*/
class AttributeTransformer {
public static void transform(GLSLParser.Translation_unitContext translationUnit, AttributeParameters parameters, String profile, int version) {
public static void transform(Transformer transformer, AttributeParameters parameters, String profile, int version) {
boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility"));
if (isCore) {
if (parameters.type == PatchShaderType.VERTEX) {
@@ -23,22 +25,24 @@ class AttributeTransformer {
// lightmap texture coordinate.
// See https://github.com/IrisShaders/Iris/issues/1149
if (parameters.inputs.lightmap) {
Util.rename(translationUnit, "gl_MultiTexCoord2", "gl_MultiTexCoord1");
transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1");
}
Map<String, String> texCoordReplacements = new HashMap<>();
if (!parameters.inputs.lightmap) {
Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
}
if (!parameters.inputs.texture) {
Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
}
texCoordReplacements.forEach(transformer::replaceExpression);
patchTextureMatrices(translationUnit, parameters.inputs.lightmap);
patchTextureMatrices(transformer, parameters.inputs.lightmap);
if (parameters.type.glShaderType == ShaderType.VERTEX
&& Util.hasVariable(translationUnit, "gl_MultiTexCoord3")
&& !Util.hasVariable(translationUnit, "mc_midTexCoord")) {
&& transformer.hasVariable("gl_MultiTexCoord3")
&& !transformer.hasVariable("mc_midTexCoord")) {
// TODO: proper type conversion
// gl_MultiTexCoord3 is a super legacy alias of mc_midTexCoord. We don't do this
// replacement if we think mc_midTexCoord could be defined just we can't handle
@@ -46,13 +50,13 @@ class AttributeTransformer {
// to define mc_midTexCoord only if it's not defined, and if it is defined,
// figure out its type, then replace all occurrences of gl_MultiTexCoord3 with
// the correct conversion from mc_midTexCoord's declared type to vec4.
Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord");
Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;");
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
private static void patchTextureMatrices(GLSLParser.Translation_unitContext translationUnit, boolean hasLightmap) {
Util.rename(translationUnit, "gl_TextureMatrix", "iris_TextureMatrix");
private static void patchTextureMatrices(Transformer transformer, boolean hasLightmap) {
transformer.rename("gl_TextureMatrix", "iris_TextureMatrix");
// TODO: These were originally marked const, but that breaks things
// If these are marked const, then using them below in the iris_LightmapTextureMatrix creation
@@ -61,13 +65,13 @@ class AttributeTransformer {
// Not sure if it really matters if these are marked const or not. Alternatively they can be marked const
// and the values hardcoded within the places that use them here, that seems to work fine, but this probably
// stayed closer to the original way it worked.
Util.injectVariable(translationUnit, "float iris_ONE_OVER_256 = 0.00390625;");
Util.injectVariable(translationUnit, "float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;");
transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
if (hasLightmap) {
Util.injectVariable(translationUnit, "mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
} else {
Util.injectVariable(translationUnit, "mat4 iris_LightmapTextureMatrix =" +
transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" +
"mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," +
" 0.0, iris_ONE_OVER_256, 0.0, 0.0," +
" 0.0, 0.0, iris_ONE_OVER_256, 0.0," +
@@ -75,7 +79,7 @@ class AttributeTransformer {
}
// column major
Util.injectVariable(translationUnit, "mat4 iris_TextureMatrix[8] = mat4[8](" +
transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" +
"gl_TextureMatrix[0]," +
"iris_LightmapTextureMatrix," +
"mat4(1.0)," +
@@ -3,7 +3,7 @@ package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.antlr.v4.runtime.tree.ParseTree;
import org.taumc.glsl.Util;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
@@ -14,7 +14,7 @@ public class CompatibilityTransformer {
private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.GEOMETRY, ShaderType.FRAGMENT};
public static void transformEach(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
public static void transformEach(Transformer transformer, Parameters parameters) {
if (parameters.type == PatchShaderType.VERTEX) {
;
// TODO: sildur's jankness
@@ -22,7 +22,7 @@ public class CompatibilityTransformer {
// Why is this the GLSL transformation code in Iris, tell sildur to fix it and remove this?
// it's still there in current, modern Iris
// See https://github.com/IrisShaders/Iris/issues/509
Util.replaceExpression(translationUnit, "fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)");
transformer.replaceExpression("fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)");
}
/**
@@ -34,8 +34,8 @@ public class CompatibilityTransformer {
* identifiers from which the declaration was removed previously.
* See https://wiki.shaderlabs.org/wiki/Compiler_Behavior_Notes
*/
Util.removeUnusedFunctions(translationUnit);
Util.removeConstAssignment(translationUnit);
transformer.removeUnusedFunctions();
transformer.removeConstAssignment();
// TODO: glsl-transformation-lib doesn't have a way to identify empty declarations
// this transformation is not done in current versions of Iris, so not sure it's necessary
@@ -49,7 +49,7 @@ public class CompatibilityTransformer {
}
// does transformations that require cross-shader type data
public static void transformGrouped(Map<PatchShaderType, GLSLParser.Translation_unitContext> trees, Parameters parameters) {
public static void transformGrouped(Map<PatchShaderType, Transformer> trees, Parameters parameters) {
/**
* find attributes that are declared as "in" in geometry or fragment but not
* declared as "out" in the previous stage. The missing "out" declarations for
@@ -88,32 +88,32 @@ public class CompatibilityTransformer {
}
PatchShaderType prevPatchTypes = PatchShaderType.fromGlShaderType(prevType)[0];
GLSLParser.Translation_unitContext prevTree = trees.get(prevPatchTypes);
Transformer prevTransformer = trees.get(prevPatchTypes);
// find out declarations
Map<String, GLSLParser.Single_declarationContext> outDec = Util.findQualifiers(prevTree, GLSLLexer.OUT);
Map<String, GLSLParser.Single_declarationContext> outDec = prevTransformer.findQualifiers(GLSLLexer.OUT);
for (PatchShaderType currentType : patchTypes) {
GLSLParser.Translation_unitContext currentTree = trees.get(currentType);
Transformer currentTransformer = trees.get(currentType);
if (currentTree == null) {
if (currentTransformer == null) {
continue;
}
Map<String, GLSLParser.Single_declarationContext> inDec = Util.findQualifiers(currentTree, GLSLLexer.IN);
Map<String, GLSLParser.Single_declarationContext> inDec = currentTransformer.findQualifiers(GLSLLexer.IN);
for (String in : inDec.keySet()) {
if (in.startsWith("gl_")) {
continue;
}
if (!outDec.containsKey(in)) {
if (!Util.containsCall(currentTree, in)) {
if (!currentTransformer.containsCall(in)) {
continue;
}
Util.makeOutDeclaration(prevTree, inDec.get(in), in);
prevTransformer.makeOutDeclaration(inDec.get(in), in);
if (!Util.hasAssigment(prevTree, in)) {
Util.initialize(prevTree, inDec.get(in), in);
if (!prevTransformer.hasAssigment(in)) {
prevTransformer.initialize(inDec.get(in), in);
}
} else {
ParseTree outType = outDec.get(in).fully_specified_type().type_specifier().type_specifier_nonarray().children.get(0);
@@ -124,8 +124,8 @@ public class CompatibilityTransformer {
}
if (inType.getText().equals(outType.getText())) {
if (!Util.hasAssigment(prevTree, in)) {
Util.initialize(prevTree, inDec.get(in), in);
if (!prevTransformer.hasAssigment(in)) {
prevTransformer.initialize(inDec.get(in), in);
}
}
}
@@ -1,16 +1,15 @@
package net.coderbot.iris.pipeline.transform;
import org.taumc.glsl.Util;
import org.taumc.glsl.grammar.GLSLParser;
import org.taumc.glsl.Transformer;
class CompositeDepthTransformer {
public static void transform(GLSLParser.Translation_unitContext translationUnit) {
public static void transform(Transformer transformer) {
// replace original declaration
int type = Util.findType(translationUnit, "centerDepthSmooth");
int type = transformer.findType("centerDepthSmooth");
if (type != 0) {
Util.injectVariable(translationUnit, "uniform sampler2D iris_centerDepthSmooth;");
Util.replaceExpression(translationUnit, "centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;");
transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
}
}
}
@@ -6,18 +6,11 @@ import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ConsoleErrorListener;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.taumc.glsl.Util;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.ArrayList;
import java.util.Arrays;
@@ -30,8 +23,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShaderTransformer {
static String tab = "";
private static final Pattern versionPattern = Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?");
private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^\\s*(in|out)(\\s+)");
@@ -39,6 +30,12 @@ public class ShaderTransformer {
private static final Object2ObjectLinkedOpenHashMap<TransformKey<?>, Map<PatchShaderType, String>> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>();
private static final boolean useCache = true;
public static void clearCache() {
synchronized (shaderTransformationCache) {
shaderTransformationCache.clear();
}
}
/**
* These are words which need to be renamed by iris if a shader uses them, regardless o the GLSL version.
* The words will get caught and renamed to iris_renamed_$WORD
@@ -109,39 +106,36 @@ public class ShaderTransformer {
var key = new TransformKey<>(patchType, inputs, parameters);
result = shaderTransformationCache.getAndMoveToFirst(key);
synchronized (shaderTransformationCache) {
result = shaderTransformationCache.getAndMoveToLast(key);
}
if(result == null || !useCache) {
result = transformInternal(inputs, patchType, parameters);
// Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null;
if(shaderTransformationCache.size() >= CACHE_SIZE) {
shaderTransformationCache.removeLast();
synchronized (shaderTransformationCache) {
// Double-check in case another thread added it while we were transforming
Map<PatchShaderType, String> existing = shaderTransformationCache.getAndMoveToLast(key);
if (existing != null) {
return existing;
}
if(shaderTransformationCache.size() >= CACHE_SIZE) {
shaderTransformationCache.removeFirst();
}
shaderTransformationCache.putAndMoveToLast(key, result);
}
shaderTransformationCache.putAndMoveToLast(key, result);
}
return result;
}
}
private static void configureNoError(Parser parser) {
parser.setErrorHandler(new BailErrorStrategy());
parser.removeErrorListeners();
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
}
private static void configureError(Parser parser) {
parser.setErrorHandler(new DefaultErrorStrategy());
parser.addErrorListener(ConsoleErrorListener.INSTANCE);
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, GLSLParser.Translation_unitContext> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
List<GLSLParser.Translation_unitContext> textureLodExtensionPatches = new ArrayList<>();
List<GLSLParser.Translation_unitContext> hacky120Patches = new ArrayList<>();
List<Transformer> textureLodExtensionPatches = new ArrayList<>();
List<Transformer> hacky120Patches = new ArrayList<>();
Stopwatch watch = Stopwatch.createStarted();
@@ -190,37 +184,35 @@ public class ShaderTransformer {
}
}
GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(input));
GLSLParser parser = new GLSLParser(new CommonTokenStream(lexer));
parser.setBuildParseTree(true);
configureNoError(parser);
var parsedShader = ShaderParser.parseShader(input);
var transformer = new Transformer(parsedShader.full());
GLSLParser.Translation_unitContext translationUnit;
try {
translationUnit = doTransform(parser, patchType, parameters, profile, versionInt);
} catch (Exception e) {
lexer.reset();
parser.reset();
configureError(parser);
translationUnit = doTransform(parser, patchType, parameters, profile, versionInt);
}
doTransform(transformer, patchType, parameters, profile, versionInt);
// Check if we need to patch in texture LOD extension enabling
if (versionInt <= 120 && (Util.containsCall(translationUnit, "texture2DLod") || Util.containsCall(translationUnit, "texture3DLod") || Util.containsCall(translationUnit, "texture2DGradARB"))) {
textureLodExtensionPatches.add(translationUnit);
if (versionInt <= 120 && (transformer.containsCall("texture2DLod") || transformer.containsCall("texture3DLod") || transformer.containsCall("texture2DGradARB"))) {
textureLodExtensionPatches.add(transformer);
}
// Check if we need to patch in some hacky GLSL 120 compat
if (versionInt <= 120) {
hacky120Patches.add(translationUnit);
hacky120Patches.add(transformer);
}
types.put(type, translationUnit);
types.put(type, transformer);
prepatched.put(type, profileString);
}
CompatibilityTransformer.transformGrouped(types, parameters);
for (var entry : types.entrySet()) {
String formattedShader = getFormattedShader(entry.getValue(), prepatched.get(entry.getKey()));
final Transformer transformer = entry.getValue();
final String header = prepatched.get(entry.getKey());
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> {
formattedShaderBuilder.append(getFormattedShader(tree, header));
});
String formattedShader = formattedShaderBuilder.toString();
// Restore identifiers that were temporarily renamed to dodge GLSL reserved keywords.
formattedShader = formattedShader.replace("iris_renamed_texture", "texture");
@@ -229,13 +221,13 @@ public class ShaderTransformer {
// Please don't mind the entire rest of this loop basically, we're doing awful fragile regex on the transformed
// shader output to do things that I can't figure out with AST because I'm bad at it
if (textureLodExtensionPatches.contains(entry.getValue())) {
if (textureLodExtensionPatches.contains(transformer)) {
String[] parts = formattedShader.split("\n", 2);
parts[1] = "#extension GL_ARB_shader_texture_lod : require\n" + parts[1];
formattedShader = parts[0] + "\n" + parts[1];
}
if (hacky120Patches.contains(entry.getValue())) {
if (hacky120Patches.contains(transformer)) {
// Forcibly enable GL_EXT_gpu_shader4, it has a lot of compatibility backports with GLSL 130+
// and seems more or less universally supported by hardware/drivers
String[] parts = formattedShader.split("\n", 2);
@@ -252,99 +244,98 @@ public class ShaderTransformer {
result.put(entry.getKey(), formattedShader);
}
watch.stop();
Iris.logger.info("Transformed shader for {} in {}", patchType.name(), watch);
Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
return result;
}
private static GLSLParser.Translation_unitContext doTransform(GLSLParser parser, Patch patchType, Parameters parameters, String profile, int versionInt) {
GLSLParser.Translation_unitContext translationUnit = parser.translation_unit();
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) {
switch (patchType) {
case SODIUM_TERRAIN:
SodiumTransformer.transform(translationUnit, parameters);
SodiumTransformer.transform(transformer, parameters);
break;
case COMPOSITE:
CompositeDepthTransformer.transform(translationUnit);
CompositeDepthTransformer.transform(transformer);
break;
case ATTRIBUTES:
AttributeTransformer.transform(translationUnit, (AttributeParameters) parameters, profile, versionInt);
AttributeTransformer.transform(transformer, (AttributeParameters) parameters, profile, versionInt);
break;
default:
throw new IllegalStateException("Unknown patch type: " + patchType.name());
}
CompatibilityTransformer.transformEach(translationUnit, parameters);
return translationUnit;
CompatibilityTransformer.transformEach(transformer, parameters);
}
public static void applyIntelHd4000Workaround(GLSLParser.Translation_unitContext translationUnit) {
Util.renameFunctionCall(translationUnit, "ftransform", "iris_ftransform");
public static void applyIntelHd4000Workaround(Transformer transformer) {
transformer.renameFunctionCall("ftransform", "iris_ftransform");
}
public static void replaceGlMultiTexCoordBounded(GLSLParser.Translation_unitContext translationUnit, int min, int max) {
public static void replaceGlMultiTexCoordBounded(Transformer transformer, int min, int max) {
for (int i = min; i <= max; i++) {
Util.replaceExpression(translationUnit, "gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)");
transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)");
}
}
public static void patchMultiTexCoord3(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
if (parameters.type.glShaderType == ShaderType.VERTEX && Util.hasVariable(translationUnit, "gl_MultiTexCoord3") && !Util.hasVariable(translationUnit, "mc_midTexCoord")) {
Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord");
Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;");
public static void patchMultiTexCoord3(Transformer transformer, Parameters parameters) {
if (parameters.type.glShaderType == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
public static void replaceMidTexCoord(GLSLParser.Translation_unitContext translationUnit, float textureScale) {
int type = Util.findType(translationUnit, "mc_midTexCoord");
public static void replaceMidTexCoord(Transformer transformer, float textureScale) {
int type = transformer.findType("mc_midTexCoord");
if (type != 0) {
Util.removeVariable(translationUnit, "mc_midTexCoord");
transformer.removeVariable("mc_midTexCoord");
}
Util.replaceExpression(translationUnit, "mc_midTexCoord", "iris_MidTex");
transformer.replaceExpression("mc_midTexCoord", "iris_MidTex");
switch (type) {
case 0:
return;
case GLSLLexer.BOOL:
return;
case GLSLLexer.FLOAT:
Util.injectFunction(translationUnit, "float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed
transformer.injectFunction("float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed
break;
case GLSLLexer.VEC2:
Util.injectFunction(translationUnit, "vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;");
transformer.injectFunction("vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;");
break;
case GLSLLexer.VEC3:
Util.injectFunction(translationUnit, "vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);");
transformer.injectFunction("vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);");
break;
case GLSLLexer.VEC4:
Util.injectFunction(translationUnit, "vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);");
transformer.injectFunction("vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);");
break;
default:
}
Util.injectVariable(translationUnit, "in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly?
transformer.injectVariable("in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly?
}
public static void addIfNotExists(GLSLParser.Translation_unitContext translationUnit, String name, String code) {
if (!Util.hasVariable(translationUnit, name)) {
Util.injectVariable(translationUnit, code);
public static void addIfNotExists(Transformer transformer, String name, String code) {
if (!transformer.hasVariable(name)) {
transformer.injectVariable(code);
}
}
public static void addIfNotExistsType(GLSLParser.Translation_unitContext translationUnit, String name, String type) {
if (!Util.hasVariable(translationUnit, name)) {
Util.injectVariable(translationUnit, type + " " + name + ";");
public static void addIfNotExistsType(Transformer transformer, String name, String type) {
if (!transformer.hasVariable(name)) {
transformer.injectVariable(type + " " + name + ";");
}
}
public static String getFormattedShader(ParseTree tree, String string) {
StringBuilder sb = new StringBuilder(string + "\n");
getFormattedShader(tree, sb);
String[] tabHolder = {""};
getFormattedShader(tree, sb, tabHolder);
return sb.toString();
}
private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder) {
private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder) {
if (tree instanceof TerminalNode) {
String text = tree.getText();
final String text = tree.getText();
if (text.equals("<EOF>")) {
return;
}
@@ -355,20 +346,21 @@ public class ShaderTransformer {
stringBuilder.append(text);
if (text.equals("{")) {
stringBuilder.append(" \n\t");
tab = "\t";
tabHolder[0] = "\t";
}
if (text.equals("}")) {
stringBuilder.deleteCharAt(stringBuilder.length() - 2);
tab = "";
if (stringBuilder.length() >= 2) {
stringBuilder.deleteCharAt(stringBuilder.length() - 2);
}
tabHolder[0] = "";
}
stringBuilder.append(text.equals(";") ? " \n" + tab : " ");
stringBuilder.append(text.equals(";") ? " \n" + tabHolder[0] : " ");
} else {
for(int i = 0; i < tree.getChildCount(); ++i) {
getFormattedShader(tree.getChild(i), stringBuilder);
for (int i = 0; i < tree.getChildCount(); ++i) {
getFormattedShader(tree.getChild(i), stringBuilder, tabHolder);
}
}
}
}
@@ -1,19 +1,21 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Util;
import org.taumc.glsl.grammar.GLSLParser;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
class SodiumTransformer {
public static void transform(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
public static void transform(Transformer transformer, Parameters parameters) {
switch (parameters.type) {
// For Sodium patching, treat fragment and geometry the same
case FRAGMENT:
case GEOMETRY:
transformFragment(translationUnit, parameters);
transformFragment(transformer, parameters);
break;
case VERTEX:
transformVertex(translationUnit, parameters);
transformVertex(transformer, parameters);
break;
default:
throw new IllegalStateException("Unexpected Sodium terrain patching shader type: " + parameters.type);
@@ -23,53 +25,62 @@ class SodiumTransformer {
/**
* Transforms vertex shaders.
*/
public static void transformVertex(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
public static void transformVertex(Transformer transformer, Parameters parameters) {
transformer.injectVariable("attribute vec3 iris_Pos;");
transformer.injectVariable("attribute vec4 iris_Color;");
transformer.injectVariable("attribute vec2 iris_TexCoord;");
transformer.injectVariable("attribute vec2 iris_LightCoord;");
transformer.injectVariable("attribute vec3 iris_Normal;");
transformer.injectVariable("uniform vec3 u_ModelScale;");
transformer.injectVariable("uniform vec2 u_TextureScale;");
transformer.injectVariable("attribute vec4 iris_ModelOffset;");
Util.injectVariable(translationUnit, "attribute vec3 iris_Pos;");
Util.injectVariable(translationUnit, "attribute vec4 iris_Color;");
Util.injectVariable(translationUnit, "attribute vec2 iris_TexCoord;");
Util.injectVariable(translationUnit, "attribute vec2 iris_LightCoord;");
Util.injectVariable(translationUnit, "attribute vec3 iris_Normal;");
Util.injectVariable(translationUnit, "uniform vec3 u_ModelScale;");
Util.injectVariable(translationUnit, "uniform vec2 u_TextureScale;");
Util.injectVariable(translationUnit, "attribute vec4 iris_ModelOffset;");
Util.injectFunction(translationUnit, "vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);");
Util.injectFunction(translationUnit, "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }");
transformer.injectFunction("vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);");
transformer.injectFunction("vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }");
transformShared(translationUnit, parameters);
transformShared(transformer, parameters);
Util.replaceExpression(translationUnit, "gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)");
Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)");
Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "iris_LightTexCoord");
Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "iris_LightTexCoord");
Util.rename(translationUnit, "gl_Color", "iris_Color");
Util.rename(translationUnit, "gl_Normal", "iris_Normal");
Util.rename(translationUnit, "ftransform", "iris_ftransform");
Map<String, String> vertexReplacements = new HashMap<>();
vertexReplacements.put("gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)");
vertexReplacements.put("gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)");
vertexReplacements.put("gl_MultiTexCoord1", "iris_LightTexCoord");
vertexReplacements.put("gl_MultiTexCoord2", "iris_LightTexCoord");
vertexReplacements.forEach(transformer::replaceExpression);
Map<String, String> vertexRenames = new HashMap<>();
vertexRenames.put("gl_Color", "iris_Color");
vertexRenames.put("gl_Normal", "iris_Normal");
vertexRenames.put("ftransform", "iris_ftransform");
transformer.rename(vertexRenames);
}
/**
* Transforms fragment shaders. The fragment shader does only the shared things
* from the vertex shader.
*/
public static void transformFragment(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
public static void transformFragment(Transformer transformer, Parameters parameters) {
// interestingly there is nothing that isn't shared
transformShared(translationUnit, parameters);
transformShared(transformer, parameters);
}
/**
* Does the things that transformVertex and transformFragment have in common.
*/
private static void transformShared(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) {
Util.injectVariable(translationUnit, "uniform mat4 iris_ModelViewMatrix;");
Util.injectVariable(translationUnit, "uniform mat4 u_ModelViewProjectionMatrix;");
Util.injectVariable(translationUnit, "uniform mat4 iris_NormalMatrix;");
Util.injectVariable(translationUnit, "uniform mat4 iris_LightmapTextureMatrix;");
private static void transformShared(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 u_ModelViewProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_NormalMatrix;");
transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;");
Util.rename(translationUnit, "gl_ModelViewMatrix", "iris_ModelViewMatrix");
Util.rename(translationUnit, "gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix");
Util.replaceExpression(translationUnit, "gl_NormalMatrix", "mat3(iris_NormalMatrix)");
Map<String, String> renames = new HashMap<>();
renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix");
renames.put("gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix");
transformer.rename(renames);
Util.replaceExpression(translationUnit, "gl_TextureMatrix[0]", "mat4(1.0)");
Util.replaceExpression(translationUnit, "gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
Map<String, String> sharedReplacements = new HashMap<>();
sharedReplacements.put("gl_NormalMatrix", "mat3(iris_NormalMatrix)");
sharedReplacements.put("gl_TextureMatrix[0]", "mat4(1.0)");
sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
sharedReplacements.forEach(transformer::replaceExpression);
}
}
@@ -10,7 +10,12 @@ import java.util.Map;
public class TransformPatcher {
private static final int MAX_CACHE_ENTRIES = 400;
private static final Map<TransformPatcher.CacheKey, Map<PatchShaderType, String>> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true);
private static final Map<TransformPatcher.CacheKey, Map<PatchShaderType, String>> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<CacheKey, Map<PatchShaderType, String>> eldest) {
return size() > MAX_CACHE_ENTRIES;
}
};
private static final boolean useCache = true;
@@ -46,7 +51,7 @@ public class TransformPatcher {
return false;
if (getClass() != obj.getClass())
return false;
TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj;
final TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj;
if (fragment == null) {
if (other.fragment != null)
return false;
@@ -77,11 +82,11 @@ public class TransformPatcher {
}
// check if this has been cached
TransformPatcher.CacheKey key;
TransformPatcher.CacheKey key = null;
Map<PatchShaderType, String> result = null;
if (useCache) {
key = new TransformPatcher.CacheKey(parameters, vertex, geometry, fragment);
if (cache.containsKey(key)) {
synchronized (cache) {
result = cache.get(key);
}
}
@@ -90,7 +95,14 @@ public class TransformPatcher {
if (result == null) {
result = ShaderTransformer.transform(vertex, geometry, fragment, parameters);
if (useCache) {
cache.put(key, result);
synchronized (cache) {
// Double-check in case another thread added it while we were transforming
final Map<PatchShaderType, String> existing = cache.get(key);
if (existing != null) {
return existing;
}
cache.put(key, result);
}
}
}
@@ -108,4 +120,10 @@ public class TransformPatcher {
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE));
}
public static void clearCache() {
synchronized (cache) {
cache.clear();
}
}
}
@@ -5,7 +5,7 @@ import net.coderbot.iris.pipeline.transform.PatchShaderType;
public class Parameters implements JobParameters {
public final Patch patch;
public PatchShaderType type; // may only be set by TransformPatcher
public PatchShaderType type;
// WARNING: adding new fields requires updating hashCode and equals methods!
// name of the shader, this should not be part of hash/equals
@@ -39,6 +39,8 @@ import org.lwjgl.opengl.GL30;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
@@ -58,17 +60,25 @@ public class CompositeRenderer {
IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier,
CenterDepthSampler centerDepthSampler, BufferFlipper bufferFlipper,
Supplier<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips, CustomUniforms customUniforms) {
this.noiseTexture = noiseTexture;
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.renderTargets = renderTargets;
this.customTextureIds = customTextureIds;
this.customUniforms = customUniforms;
Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips,
CustomUniforms customUniforms,
Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures) {
this(sources, computes, bufferFlipper, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), explicitPreFlips, precomputedTransformFutures, "unknown");
}
public CompositeRenderer(ProgramSource[] sources, ComputeSource[][] computes, BufferFlipper bufferFlipper, ProgramBuildContext context, ImmutableMap<Integer, Boolean> explicitPreFlips, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures, String stageName) {
this.noiseTexture = context.noiseTexture();
this.updateNotifier = context.updateNotifier();
this.centerDepthSampler = context.centerDepthSampler();
this.renderTargets = context.renderTargets();
this.customTextureIds = context.customTextureIds();
this.customUniforms = context.customUniforms();
final ImmutableList.Builder<Pass> passes = ImmutableList.builder();
final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>();
Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures = precomputedTransformFutures;
explicitPreFlips.forEach((buffer, shouldFlip) -> {
if (shouldFlip) {
bufferFlipper.flip(buffer);
@@ -84,28 +94,29 @@ public class CompositeRenderer {
if (source == null || !source.isValid()) {
if (computes[i] != null) {
ComputeOnlyPass pass = new ComputeOnlyPass();
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier);
final ComputeOnlyPass pass = new ComputeOnlyPass();
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
passes.add(pass);
}
continue;
}
Pass pass = new Pass();
ProgramDirectives directives = source.getDirectives();
final Pass pass = new Pass();
final ProgramDirectives directives = source.getDirectives();
pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier);
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier);
int[] drawBuffers = directives.getDrawBuffers();
Map<PatchShaderType, String> transformed = getTransformed(source, transformFutures, i, stageName);
pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
final int[] drawBuffers = directives.getDrawBuffers();
GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers);
final GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers);
int passWidth = 0, passHeight = 0;
// Flip the buffers that this shader wrote to, and set pass width and height
ImmutableMap<Integer, Boolean> explicitFlips = directives.getExplicitFlips();
final ImmutableMap<Integer, Boolean> explicitFlips = directives.getExplicitFlips();
for (int buffer : drawBuffers) {
RenderTarget target = renderTargets.get(buffer);
final RenderTarget target = renderTargets.get(buffer);
if ((passWidth > 0 && passWidth != target.getWidth()) || (passHeight > 0 && passHeight != target.getHeight())) {
throw new IllegalStateException("Pass widths must match");
}
@@ -145,6 +156,25 @@ public class CompositeRenderer {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0);
}
private static Map<PatchShaderType, String> getTransformed(ProgramSource source, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures, int index, String stageName) {
if (transformFutures != null) {
final CompletableFuture<Map<PatchShaderType, String>> future = transformFutures.get(index);
if (future != null) {
try {
final Map<PatchShaderType, String> result = future.join();
if (result != null) {
return result;
}
} catch (CompletionException e) {
throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "' (pass " + index + ")", e.getCause() != null ? e.getCause() : e);
}
}
}
// Fallback: transform synchronously
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new));
}
public void recalculateSizes() {
for (Pass pass : passes) {
if (pass instanceof ComputeOnlyPass) {
@@ -291,13 +321,9 @@ public class CompositeRenderer {
}
// TODO: Don't just copy this from DeferredWorldRenderingPipeline
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed,
ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
@@ -40,6 +40,8 @@ import org.lwjgl.opengl.GL30;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
@@ -59,33 +61,38 @@ public class FinalPassRenderer {
private final Object2ObjectMap<String, IntSupplier> customTextureIds;
private final CustomUniforms customUniforms;
// TODO: The length of this argument list is getting a bit ridiculous
public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, IntSupplier noiseTexture,
FrameUpdateNotifier updateNotifier, ImmutableSet<Integer> flippedBuffers,
CenterDepthSampler centerDepthSampler,
Supplier<ShadowRenderTargets> shadowTargetsSupplier,
Object2ObjectMap<String, IntSupplier> customTextureIds,
ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms) {
this.updateNotifier = updateNotifier;
this.centerDepthSampler = centerDepthSampler;
this.customTextureIds = customTextureIds;
ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms,
CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture) {
this(pack, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), flippedBuffers, flippedAtLeastOnce, precomputedTransformFuture, "final");
}
this.noiseTexture = noiseTexture;
this.renderTargets = renderTargets;
this.customUniforms = customUniforms;
this.finalPass = pack.getCompositeFinal().map(source -> {
Pass pass = new Pass();
ProgramDirectives directives = source.getDirectives();
public FinalPassRenderer(ProgramSet pack, ProgramBuildContext context, ImmutableSet<Integer> flippedBuffers, ImmutableSet<Integer> flippedAtLeastOnce, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture, String stageName) {
this.updateNotifier = context.updateNotifier();
this.centerDepthSampler = context.centerDepthSampler();
this.customTextureIds = context.customTextureIds();
pass.program = createProgram(source, flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier);
pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier);
this.noiseTexture = context.noiseTexture();
this.renderTargets = context.renderTargets();
this.customUniforms = context.customUniforms();
this.finalPass = pack.getCompositeFinal().filter(ProgramSource::isValid).map(source -> {
final Pass pass = new Pass();
final ProgramDirectives directives = source.getDirectives();
final Map<PatchShaderType, String> transformed = getTransformed(source, precomputedTransformFuture, stageName);
pass.program = createProgramFromTransformed(source, transformed, flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier());
pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier());
pass.stageReadsFromAlt = flippedBuffers;
pass.mipmappedBuffers = directives.getMipmappedBuffers();
return pass;
}).orElse(null);
IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared();
final IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared();
// The name of this method might seem a bit odd here, but we want a framebuffer with color attachments that line
// up with whatever was written last (since we're reading from these framebuffers) instead of trying to create
@@ -128,6 +135,20 @@ public class FinalPassRenderer {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0);
}
private static Map<PatchShaderType, String> getTransformed(ProgramSource source, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture, String stageName) {
if (precomputedTransformFuture != null) {
try {
final Map<PatchShaderType, String> result = precomputedTransformFuture.join();
if (result != null) {
return result;
}
} catch (CompletionException e) {
throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "'", e.getCause() != null ? e.getCause() : e);
}
}
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new));
}
private static final class Pass {
Program program;
ComputeProgram[] computes;
@@ -314,13 +335,9 @@ public class FinalPassRenderer {
}
// TODO: Don't just copy this from DeferredWorldRenderingPipeline
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed,
ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
final String vertex = transformed.get(PatchShaderType.VERTEX);
final String geometry = transformed.get(PatchShaderType.GEOMETRY);
final String fragment = transformed.get(PatchShaderType.FRAGMENT);
@@ -0,0 +1,23 @@
package net.coderbot.iris.postprocess;
import com.github.bsideup.jabel.Desugar;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.jetbrains.annotations.NotNull;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
@Desugar
public record ProgramBuildContext(
@NotNull RenderTargets renderTargets,
@NotNull IntSupplier noiseTexture,
@NotNull FrameUpdateNotifier updateNotifier,
@NotNull CenterDepthSampler centerDepthSampler,
@NotNull Supplier<ShadowRenderTargets> shadowTargetsSupplier,
@NotNull Object2ObjectMap<String, IntSupplier> customTextureIds,
@NotNull CustomUniforms customUniforms
) {}
@@ -67,7 +67,7 @@ public class CommentDirectiveParser {
try {
actual = testCase.get();
} catch (Throwable e) {
} catch (Exception e) {
System.err.println("Test \"" + name + "\" failed with an exception:");
e.printStackTrace();
@@ -80,7 +80,7 @@ public class BlockEntry {
for (int index = statesStart; index < splitStates.length; index++) {
// Parse out one or more metadata ids
final String[] metaParts = splitStates[index].split(", ");
final String[] metaParts = splitStates[index].split(",");
for (String metaPart : metaParts) {
try {
@@ -67,8 +67,8 @@ public class PBRAtlasTexture extends AutoClosableAbstractTexture {
for (TextureAtlasSprite sprite : sprites.values()) {
try {
uploadSprite(sprite);
} catch (Throwable throwable) {
CrashReport crashReport = CrashReport.makeCrashReport(throwable, "Stitching texture atlas");
} catch (Exception e) {
CrashReport crashReport = CrashReport.makeCrashReport(e, "Stitching texture atlas");
CrashReportCategory crashReportCategory = crashReport.makeCategory("Texture being stitched together");
crashReportCategory.addCrashSection("Atlas path", id);
crashReportCategory.addCrashSection("Sprite", sprite);
@@ -97,7 +97,7 @@ public class PBRAtlasTexture extends AutoClosableAbstractTexture {
try {
upload(atlasWidth, atlasHeight, mipLevel, anisotropicFiltering);
return true;
} catch (Throwable t) {
} catch (Exception t) {
Iris.logger.error("Could not upload PBR texture", t);
return false;
}
@@ -72,7 +72,7 @@ public final class CommonUniforms {
// TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform,
// but we do. How will custom uniforms depending on atlasSize work?
uniforms.uniform2i("atlasSize", () -> {
final int glId = GLStateManager.getBoundTexture();
final int glId = GLStateManager.getBoundTextureForServerState();
final AbstractTexture texture = TextureTracker.INSTANCE.getTexture(glId);
if (texture instanceof TextureMap) {
@@ -84,7 +84,7 @@ public final class CommonUniforms {
}, StateUpdateNotifiers.bindTextureNotifier);
uniforms.uniform2i("gtextureSize", () -> {
final int glId = GLStateManager.getBoundTexture();
final int glId = GLStateManager.getBoundTextureForServerState();
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(glId);
return new Vector2i(info.getWidth(), info.getHeight());
@@ -8,7 +8,7 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(value=GuiIngameForge.class, remap = false)
@Mixin(GuiIngameForge.class)
public class MixinGuiIngameForge {
@Redirect(method = "renderHUDText", at = @At(value = "FIELD", target = "Lnet/minecraft/world/biome/BiomeGenBase;biomeName:Ljava/lang/String;"))
private String getModNameWithBiome(BiomeGenBase biome) {
@@ -21,7 +21,7 @@ public class MixinRenderGlobal_DestroyBlock {
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/Tessellator;startDrawingQuads()V")
)
private void iris$beginDrawBlockDamageTexture(Tessellator tessellator, EntityLivingBase entity, float partialTicks, CallbackInfo ci, @Share("lastMin") LocalIntRef lastMin, @Share("lastMag") LocalIntRef lastMag) {
TextureInfo info = TextureInfoCache.INSTANCE.getInfo(GLStateManager.getBoundTexture());
TextureInfo info = TextureInfoCache.INSTANCE.getInfo(GLStateManager.getBoundTextureForServerState());
lastMin.set(info.getMinFilter());
lastMag.set(info.getMagFilter());
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
@@ -0,0 +1,267 @@
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 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);
GL11.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);
GL11.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);
GL11.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);
GL11.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);
GL11.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);
GL11.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);
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");
GLStateManager.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 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);
GL11.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);
GL11.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);
GL11.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);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterMode);
assertNotEquals(0.0f, afterMode.get(12), "After MatrixMode: flushed to MODELVIEW");
FloatBuffer proj = BufferUtils.createFloatBuffer(16);
GL11.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);
GL11.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);
GL11.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);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop);
assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity (pushed state)");
GLStateManager.glEndList();
}
}
@@ -0,0 +1,261 @@
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();
}
}
@@ -92,7 +92,26 @@ public final class DisplayListTestHelper {
Matrix4f transform,
CapturingTessellator.Flags flags,
int commandIndex) {
return new AccumulatedDraw(quads, transform, flags, commandIndex);
return new AccumulatedDraw(quads, transform, flags, commandIndex, 0);
}
public static AccumulatedDraw createDraw(
List<ModelQuadViewMutable> quads,
Matrix4f transform,
CapturingTessellator.Flags flags,
int commandIndex,
int matrixGeneration) {
return new AccumulatedDraw(quads, transform, flags, commandIndex, matrixGeneration, 0);
}
public static AccumulatedDraw createDraw(
List<ModelQuadViewMutable> quads,
Matrix4f transform,
CapturingTessellator.Flags flags,
int commandIndex,
int matrixGeneration,
int stateGeneration) {
return new AccumulatedDraw(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration);
}
/**
@@ -110,12 +129,27 @@ public final class DisplayListTestHelper {
/**
* Create an AccumulatedDraw with specified transform.
*/
public static AccumulatedDraw createDrawWithTransform(Matrix4f transform, int commandIndex) {
public static AccumulatedDraw createDrawWithTransform(Matrix4f transform, int commandIndex, int matrixGeneration) {
return createDraw(
Collections.singletonList(createSimpleQuad()),
transform,
positionOnly(),
commandIndex
commandIndex,
matrixGeneration
);
}
/**
* Create an AccumulatedDraw with specified transform and stateGeneration.
*/
public static AccumulatedDraw createDrawWithTransformAndBatch(Matrix4f transform, int commandIndex, int matrixGeneration, int stateGeneration) {
return createDraw(
Collections.singletonList(createSimpleQuad()),
transform,
positionOnly(),
commandIndex,
matrixGeneration,
stateGeneration
);
}
@@ -333,7 +367,16 @@ public final class DisplayListTestHelper {
Matrix4f transform,
CapturingTessellator.Flags flags,
int commandIndex) {
return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex);
return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex, 0);
}
public static AccumulatedPrimitiveDraw createPrimitiveDraw(
List<ModelPrimitiveView> primitives,
Matrix4f transform,
CapturingTessellator.Flags flags,
int commandIndex,
int matrixGeneration) {
return new AccumulatedPrimitiveDraw(primitives, transform, flags, commandIndex, matrixGeneration);
}
/**
@@ -7,11 +7,9 @@ import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd;
import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd;
import com.gtnewhorizons.angelica.glsm.recording.commands.TranslateCmd;
import org.joml.Matrix4f;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.HashSet;
@@ -120,15 +118,11 @@ class GLSM_DisplayList_Batching_Test {
// Setup: draws with different transforms but same format
// With format-based batching, they share 1 VBO but produce separate DrawRangeCmds
List<AccumulatedDraw> draws = new ArrayList<>();
draws.add(createDrawWithTransform(new Matrix4f(), 0)); // Identity transform
draws.add(createDrawWithTransform(new Matrix4f().translate(1.0f, 0.0f, 0.0f), 2)); // After translate
draws.add(createDrawWithTransform(new Matrix4f().translate(3.0f, 0.0f, 0.0f), 4)); // After more translates
draws.add(createDrawWithTransform(new Matrix4f(), 0, 0)); // Identity transform, gen=0
draws.add(createDrawWithTransform(new Matrix4f().translate(1.0f, 0.0f, 0.0f), 1, 1)); // T(1), gen=1
draws.add(createDrawWithTransform(new Matrix4f().translate(3.0f, 0.0f, 0.0f), 2, 2)); // T(3), gen=2
List<DisplayListCommand> commands = new ArrayList<>();
commands.add(new TranslateCmd(1.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 0
commands.add(new TranslateCmd(2.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 1
commands.add(new TranslateCmd(3.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 2
commands.add(new TranslateCmd(4.0, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 3
// Execute
OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(commands, draws, null, 1);
@@ -145,9 +139,9 @@ class GLSM_DisplayList_Batching_Test {
Set<VertexBuffer> uniqueVBOs = getUniqueVBOs(optimized);
assertEquals(1, uniqueVBOs.size(), "All DrawRangeCmds should reference the same shared VBO");
// Should have MultMatrix commands for the transforms
// Should have MultMatrix commands for the transforms (2 for T(1) and T(3))
long matrixCount = countMultMatrixCmds(optimized);
assertTrue(matrixCount >= 2, "Should have MultMatrix commands for each unique transform");
assertEquals(2, matrixCount, "Should have MultMatrix commands for each unique transform");
}
@Test
@@ -196,52 +190,25 @@ class GLSM_DisplayList_Batching_Test {
assertEquals(1, drawCount, "Draws with different quad counts but same format and transform should produce 1 DrawRangeCmd");
}
@Test
void testEmptyDrawListProducesNoVBOs() {
// Setup: no draws
List<AccumulatedDraw> draws = new ArrayList<>();
List<DisplayListCommand> commands = new ArrayList<>();
commands.add(new TranslateCmd(1.0, 0.0, 0.0, GL11.GL_MODELVIEW));
// Execute
OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(
commands, draws, null, 1);
DisplayListCommand[] optimized = result.commands();
// Verify: no VBOs
assertEquals(0, result.ownedVbos().length, "No draws should produce no VBOs");
// Verify: no DrawRangeCmds
long drawCount = countDrawRangeCmds(optimized);
assertEquals(0, drawCount, "No draws should produce no DrawRangeCmds");
// But should still have the collapsed transform
long matrixCount = countMultMatrixCmds(optimized);
assertEquals(1, matrixCount,
"Transform should still be emitted even without draws");
}
@Test
void testCancellingTransformsProduceSeparateDrawRangeCmds() {
// This tests the specific bug where transforms cancel out in the command stream
// 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.
List<AccumulatedDraw> draws = new ArrayList<>();
// Draw 1: captured at identity
draws.add(createDrawWithTransform(new Matrix4f(), 0));
// Draw 2: captured at translate(0.5, 0, 0) - BEFORE the cancelling translate(-0.5)
draws.add(createDrawWithTransform(new Matrix4f().translate(0.5f, 0.0f, 0.0f), 2));
// Draw 3: captured back at identity (after translate(-0.5) cancelled out)
draws.add(createDrawWithTransform(new Matrix4f(), 4));
// Draw 1: captured at identity, gen=0
draws.add(createDrawWithTransform(new Matrix4f(), 0, 0));
// Draw 2: captured at translate(0.5, 0, 0), gen=1 (transform changed)
draws.add(createDrawWithTransform(new Matrix4f().translate(0.5f, 0.0f, 0.0f), 1, 1));
// Draw 3: captured back at identity, gen=2 (transform changed again)
draws.add(createDrawWithTransform(new Matrix4f(), 2, 2));
List<DisplayListCommand> commands = new ArrayList<>();
commands.add(new TranslateCmd(0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 0: move +0.5
commands.add(new TranslateCmd(-0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 1: move -0.5 (cancels out)
commands.add(new TranslateCmd(0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 2: move +0.5
commands.add(new TranslateCmd(-0.5, 0.0, 0.0, GL11.GL_MODELVIEW)); // index 3: move -0.5 (cancels out)
// Execute
OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(
@@ -262,9 +229,10 @@ class GLSM_DisplayList_Batching_Test {
Matrix4f commonTransform = new Matrix4f().translate(1.0f, 2.0f, 3.0f);
List<AccumulatedDraw> draws = new ArrayList<>();
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0));
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0));
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0));
// All same transform → same generation → will batch into single DrawRangeCmd
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1));
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1));
draws.add(createDrawWithTransform(new Matrix4f(commonTransform), 0, 1));
List<DisplayListCommand> commands = new ArrayList<>();
@@ -286,6 +254,44 @@ class GLSM_DisplayList_Batching_Test {
"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.
*
* Scenario: Draw1, glColor(red), Draw2, glBindTexture, Draw3
* All draws have same transform (gen=1) but different batches (0, 1, 2).
* Expected: 3 separate DrawRangeCmds (no merging across draw barriers).
*
* This test will FAIL until FormatBuffer is fixed to check stateGeneration.
*/
@Test
void testDrawsWithDifferentBatchIdDoNotMerge() {
// Setup: 3 draws with same transform generation but different batch IDs
// This simulates state commands (draw barriers) between draws
List<AccumulatedDraw> draws = new ArrayList<>();
draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 0, 1, 0)); // batch 0
draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 1, 1, 1)); // batch 1 (state cmd between)
draws.add(createDrawWithTransformAndBatch(new Matrix4f(), 2, 1, 2)); // batch 2 (state cmd between)
List<DisplayListCommand> commands = new ArrayList<>();
// Execute
OptimizedListResult result = DisplayListManager.buildOptimizedDisplayList(
commands, draws, null, 1);
DisplayListCommand[] optimized = result.commands();
// Verify: 1 shared VBO (same format)
assertEquals(1, result.ownedVbos().length,
"Draws with same format should share 1 VBO");
// Verify: 3 DrawRangeCmds (NOT merged due to different batch IDs)
// BUG: Currently this will produce 1 DrawRangeCmd because FormatBuffer
// only checks matrixGeneration, not stateGeneration
long drawCount = countDrawRangeCmds(optimized);
assertEquals(3, drawCount,
"Draws with same transform but different batch IDs (draw barriers between) must NOT merge");
}
@Test
void testInterleavedFormatsProduceSeparateVBOs() {
// Setup: A A B A A - should produce 2 VBOs (one for A, one for B)
@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
/**
* Tests for display list format optimization.
@@ -33,15 +33,16 @@ class GLSM_DisplayList_FormatOptimization_Test {
@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);
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.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();
@@ -55,16 +56,16 @@ class GLSM_DisplayList_FormatOptimization_Test {
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glTexCoord2f(1, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glTexCoord2f(1, 1);
GL11.glVertex3f(1, 1, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
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();
@@ -78,25 +79,27 @@ class GLSM_DisplayList_FormatOptimization_Test {
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GL11.glBegin(GL11.GL_QUADS);
GL11.glColor4f(1, 1, 1, 1);
GL11.glTexCoord2f(0, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glColor4f(1, 0, 0, 1);
GL11.glTexCoord2f(1, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glColor4f(0, 1, 0, 1);
GL11.glTexCoord2f(1, 1);
GL11.glVertex3f(1, 1, 0);
GL11.glColor4f(0, 0, 1, 1);
GL11.glTexCoord2f(0, 1);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
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 to ensure it doesn't crash (verifies compilation succeeded)
// 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
@@ -105,29 +108,31 @@ class GLSM_DisplayList_FormatOptimization_Test {
displayList = GL11.glGenLists(1);
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
GL11.glBegin(GL11.GL_QUADS);
GL11.glNormal3f(0, 0, 1);
GL11.glColor4f(1, 1, 1, 1);
GL11.glTexCoord2f(0, 0);
GL11.glVertex3f(0, 0, 0);
GL11.glNormal3f(0, 0, 1);
GL11.glColor4f(1, 0, 0, 1);
GL11.glTexCoord2f(1, 0);
GL11.glVertex3f(1, 0, 0);
GL11.glNormal3f(0, 0, 1);
GL11.glColor4f(0, 1, 0, 1);
GL11.glTexCoord2f(1, 1);
GL11.glVertex3f(1, 1, 0);
GL11.glNormal3f(0, 0, 1);
GL11.glColor4f(0, 0, 1, 1);
GL11.glTexCoord2f(0, 1);
GL11.glVertex3f(0, 1, 0);
GL11.glEnd();
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 to ensure it doesn't crash (verifies compilation succeeded)
// 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
@@ -137,40 +142,82 @@ class GLSM_DisplayList_FormatOptimization_Test {
GLStateManager.glNewList(displayList, GL11.GL_COMPILE);
// First draw: position only
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.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
GL11.glBegin(GL11.GL_QUADS);
GL11.glColor4f(1, 0, 0, 1);
GL11.glVertex3f(2, 0, 0);
GL11.glColor4f(0, 1, 0, 1);
GL11.glVertex3f(3, 0, 0);
GL11.glColor4f(0, 0, 1, 1);
GL11.glVertex3f(3, 1, 0);
GL11.glColor4f(1, 1, 0, 1);
GL11.glVertex3f(2, 1, 0);
GL11.glEnd();
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
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex3f(4, 0, 0);
GL11.glTexCoord2f(1, 0);
GL11.glVertex3f(5, 0, 0);
GL11.glTexCoord2f(1, 1);
GL11.glVertex3f(5, 1, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex3f(4, 1, 0);
GL11.glEnd();
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 to ensure it doesn't crash (verifies compilation succeeded)
// 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");
}
}
@@ -69,7 +69,7 @@ class GLSM_DisplayList_Primitive_Test {
// Execute: Create AccumulatedPrimitiveDraw (should deep copy)
AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw(
primitives, identity(), positionOnly(), 0);
primitives, identity(), positionOnly(), 0, 0);
// Modify original
originalLine.setX(0, 999.0f);
@@ -96,7 +96,7 @@ class GLSM_DisplayList_Primitive_Test {
// Execute: Create AccumulatedPrimitiveDraw (should deep copy)
AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw(
primitives, identity(), positionOnly(), 0);
primitives, identity(), positionOnly(), 0, 0);
// Modify original
originalTri.setX(0, 999.0f);
@@ -119,7 +119,7 @@ class GLSM_DisplayList_Primitive_Test {
// Execute
AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw(
primitives, identity(), positionOnly(), 0);
primitives, identity(), positionOnly(), 0, 0);
// Verify: All primitives copied correctly
assertEquals(4, draw.primitives.size(), "Should have 4 primitives (2 lines + 2 triangles)");
@@ -143,7 +143,7 @@ class GLSM_DisplayList_Primitive_Test {
// Execute
AccumulatedPrimitiveDraw draw = new AccumulatedPrimitiveDraw(
primitives, originalTransform, positionOnly(), 0);
primitives, originalTransform, positionOnly(), 0, 0);
// Modify original transform
originalTransform.identity();
@@ -475,11 +475,11 @@ class GLSM_DisplayList_Primitive_Test {
List<ModelPrimitiveView> lines1 = new ArrayList<>();
lines1.add(createSimpleLine());
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0));
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines1, identity(), positionOnly(), 0, 0));
List<ModelPrimitiveView> lines2 = new ArrayList<>();
lines2.add(createSimpleLine());
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1));
primitiveDraws.add(new AccumulatedPrimitiveDraw(lines2, translate(1, 0, 0), positionOnly(), 1, 1));
List<DisplayListCommand> commands = new ArrayList<>();
@@ -16,18 +16,7 @@ import java.nio.FloatBuffer;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for transform collapsing optimization in display lists.
*
* <p>The optimization collapses consecutive MODELVIEW transforms into single MultMatrix
* commands, emitting them at "barriers" (draws, CallList, exit). These tests verify:</p>
* <ul>
* <li>Consecutive transforms collapse to single MultMatrix</li>
* <li>Matrix state is correct after execution</li>
* <li>Push/Pop maintain proper stack semantics</li>
* <li>Barriers (draws, CallList) correctly flush pending transforms</li>
* </ul>
*/
/** Tests for transform collapsing optimization in display lists. */
@ExtendWith(AngelicaExtension.class)
class GLSM_DisplayList_TransformCollapsing_Test {
@@ -268,9 +257,14 @@ class GLSM_DisplayList_TransformCollapsing_Test {
GLStateManager.glEndList();
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
Int2IntMap counts = compiled.getCommandCounts();
int multMatrixCount = counts.getOrDefault(GLCommand.MULT_MATRIX, 0);
// 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");
@@ -503,7 +497,7 @@ class GLSM_DisplayList_TransformCollapsing_Test {
GLStateManager.glEndList();
// Verify the LoadMatrixCmd is present
// Verify the LOAD_MATRIX command is present
CompiledDisplayList compiled = DisplayListManager.getDisplayList(testList);
assertNotNull(compiled, "Display list should be compiled");
@@ -645,4 +639,320 @@ class GLSM_DisplayList_TransformCollapsing_Test {
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);
GL11.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
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
// Execute directly via GL to get expected results
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glTranslatef(1.0f, 0.0f, 0.0f);
GL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GL11.glScalef(2.0f, 2.0f, 2.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glTranslatef(3.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GL11.glTranslatef(5.0f, 0.0f, 0.0f);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
FloatBuffer expectedMV = BufferUtils.createFloatBuffer(16);
FloatBuffer expectedProj = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedMV);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GL11.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);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualMV);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GL11.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);
GL11.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);
GL11.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 GL
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GL11.glTranslatef(tx1, ty1, tz1);
GL11.glRotatef(angle1, 0.0f, 1.0f, 0.0f); // Y-axis rotation
GL11.glScalef(sx, sy, sz);
GL11.glRotatef(angle2, 1.0f, 0.0f, 0.0f); // X-axis rotation
GL11.glTranslatef(tx2, ty2, tz2);
FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16);
GL11.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);
GL11.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();
}
}
@@ -17,6 +17,8 @@ import org.lwjgl.opengl.GL32;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyIsEnabled;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState;
@@ -869,4 +871,307 @@ class GLSM_PushPop_UnitTest {
GLStateManager.glPopAttrib();
verifyIsEnabled(GL11.GL_BLEND, false, "Blend - After pop to depth 0");
}
// ==================== Display List + Push/Pop Interaction Tests ====================
@Test
void testDisplayListCallInsidePushPopAllAttribBits() {
// Tests the pattern:
// 1. Push ALL attrib bits
// 2. Switch to TEXTURE1, enable GL_TEXTURE_2D
// 3. Switch back to TEXTURE0
// 4. Call a display list that changes texture state
// 5. Pop attrib
// 6. Verify state restored correctly
//
// This pattern is used by mods that wrap vanilla entity rendering.
// Setup: create textures and verify initial state
final int texA = GL11.glGenTextures();
final int texB = GL11.glGenTextures();
final int texC = GL11.glGenTextures();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA);
verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "Initial binding unit 0");
verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "Initial active unit");
// Verify unit 1 starts with no texture and TEXTURE_2D disabled
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "Initial binding unit 1");
verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "Initial TEXTURE_2D state unit 1");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
// Create display list that changes texture state on multiple units
final int listId = GL11.glGenLists(1);
GLStateManager.glNewList(listId, GL11.GL_COMPILE);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texC);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glEndList();
// === Begin pattern ===
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
// Switch to TEXTURE1, enable GL_TEXTURE_2D, switch back
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "TEXTURE_2D enabled on unit 1");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
// Call display list (simulates calling vanilla model/entity display lists)
DisplayListManager.glCallList(listId);
// Verify state changed by display list
verifyState(GL11.GL_TEXTURE_BINDING_2D, texB, "After display list - unit 0 binding");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL11.GL_TEXTURE_BINDING_2D, texC, "After display list - unit 1 binding");
verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After display list - TEXTURE_2D still enabled on unit 1");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
// Pop attrib - should restore all state
GLStateManager.glPopAttrib();
// === CRITICAL VERIFICATIONS ===
// If any of these fail, we've found the bug
// Active texture unit should be restored
verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "After pop - active unit");
// Unit 0 binding should be restored to texA
verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After pop - unit 0 binding");
// Unit 1 state should be fully restored
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After pop - unit 1 binding");
verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - TEXTURE_2D disabled on unit 1");
// Cleanup - reset all state to defaults
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texA);
GLStateManager.glDeleteTextures(texB);
GLStateManager.glDeleteTextures(texC);
GLStateManager.glDeleteLists(listId, 1);
}
@Test
void testDisplayListWithNestedPushPopInsideOuterPushPop() {
// Tests nested push/pop where the display list itself contains push/pop
// Pattern:
// glPushAttrib(ALL)
// glCallList(...) // list contains: glPushAttrib, change state, glPopAttrib
// glPopAttrib()
final int texA = GL11.glGenTextures();
final int texB = GL11.glGenTextures();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA);
verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "Initial binding");
// Create display list with its own push/pop
final int listId = GL11.glGenLists(1);
GLStateManager.glNewList(listId, GL11.GL_COMPILE);
GLStateManager.glPushAttrib(GL11.GL_TEXTURE_BIT);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB);
GLStateManager.glPopAttrib();
GLStateManager.glEndList();
// Outer push
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
// Change texture
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After unbind in outer push");
// Call display list with nested push/pop
DisplayListManager.glCallList(listId);
// After display list's pop, should be back to 0 (what outer context had)
verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After display list with nested push/pop");
// Outer pop
GLStateManager.glPopAttrib();
// Should restore to original texA
verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After outer pop");
// Cleanup - reset state to defaults
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texA);
GLStateManager.glDeleteTextures(texB);
GLStateManager.glDeleteLists(listId, 1);
}
@Test
void testTextureUnitSwitchingWithDisplayListModifyingDifferentUnit() {
// Tests: outer code works on unit 1, display list modifies unit 0
// Verifies both units are correctly restored after pop
final int texA = GL11.glGenTextures();
final int texB = GL11.glGenTextures();
final int texC = GL11.glGenTextures();
// Initial state: texA on unit 0, nothing on unit 1
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texA);
// Create display list that only modifies unit 0
final int listId = GL11.glGenLists(1);
GLStateManager.glNewList(listId, GL11.GL_COMPILE);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texC);
GLStateManager.glEndList();
// Push, then work on unit 1
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texB);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
// Call display list - modifies unit 0 while we're "on" unit 1
DisplayListManager.glCallList(listId);
// Verify: unit 0 changed, unit 1 unchanged
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
verifyState(GL11.GL_TEXTURE_BINDING_2D, texC, "After list - unit 0 changed to texC");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL11.GL_TEXTURE_BINDING_2D, texB, "After list - unit 1 still texB");
verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After list - unit 1 still enabled");
// Pop
GLStateManager.glPopAttrib();
// Both units should be restored
verifyState(GL13.GL_ACTIVE_TEXTURE, GL13.GL_TEXTURE0, "After pop - active unit");
verifyState(GL11.GL_TEXTURE_BINDING_2D, texA, "After pop - unit 0 restored to texA");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyState(GL11.GL_TEXTURE_BINDING_2D, 0, "After pop - unit 1 restored to 0");
verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - unit 1 disabled");
// Cleanup - reset all state to defaults
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GLStateManager.glDeleteTextures(texA);
GLStateManager.glDeleteTextures(texB);
GLStateManager.glDeleteTextures(texC);
GLStateManager.glDeleteLists(listId, 1);
}
@Test
void testColorStateWithDisplayListInsidePushPop() {
// Tests color state restoration - white screen could indicate color issue
// Pattern: push, set color, call display list that changes color, pop
verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "Initial color white");
// Create display list that sets color to red
final int listId = GL11.glGenLists(1);
GLStateManager.glNewList(listId, GL11.GL_COMPILE);
GLStateManager.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glEndList();
// Push (note: GL_CURRENT_BIT includes color)
GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT);
// Set color to green
GLStateManager.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{0.0f, 1.0f, 0.0f, 1.0f}, "After setting green");
// Call display list - sets to red
DisplayListManager.glCallList(listId);
verifyState(GL11.GL_CURRENT_COLOR, new float[]{1.0f, 0.0f, 0.0f, 1.0f}, "After display list - red");
// Pop - should restore to white (initial state before push)
GLStateManager.glPopAttrib();
verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "After pop - restored to white");
// Cleanup - ensure color is reset to white
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GLStateManager.glDeleteLists(listId, 1);
}
@Test
void testBlendStateWithDisplayListInsidePushPop() {
// Tests blend state restoration - incorrect blend could cause visual issues
verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "color should still be white");
verifyIsEnabled(GL11.GL_BLEND, false, "Initial blend disabled");
verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "Initial blend src");
verifyState(GL11.GL_BLEND_DST, GL11.GL_ZERO, "Initial blend dst");
// Create display list that enables blend with specific function
final int listId = GL11.glGenLists(1);
GLStateManager.glNewList(listId, GL11.GL_COMPILE);
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
GLStateManager.glEndList();
// Push
GLStateManager.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT);
// Set different blend state
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
// Call display list - changes blend function
DisplayListManager.glCallList(listId);
verifyIsEnabled(GL11.GL_BLEND, true, "After list - blend enabled");
verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "After list - blend src ONE");
verifyState(GL11.GL_BLEND_DST, GL11.GL_ONE, "After list - blend dst ONE");
// Pop
GLStateManager.glPopAttrib();
verifyIsEnabled(GL11.GL_BLEND, false, "After pop - blend disabled");
verifyState(GL11.GL_BLEND_SRC, GL11.GL_ONE, "After pop - blend src restored");
verifyState(GL11.GL_BLEND_DST, GL11.GL_ZERO, "After pop - blend dst restored");
// Cleanup - ensure blend is reset to defaults
GLStateManager.disableBlend();
GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glDeleteLists(listId, 1);
// Verify GLSM cache matches actual GL state (exposes cache sync bugs)
verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "color should still be white");
}
@Test
void testTextureUnitPopAttribRestoresCorrectUnit() {
// Setup: Unit 0 ENABLED, Unit 1 disabled
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glDisable(GL11.GL_TEXTURE_2D);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "Initial - Unit 0 enabled");
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
// Modify ONLY unit 1
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glPopAttrib();
// Unit 0 should still be enabled - bug causes it to be disabled
verifyIsEnabled(GL11.GL_TEXTURE_2D, true, "After pop - Unit 0 still enabled");
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
verifyIsEnabled(GL11.GL_TEXTURE_2D, false, "After pop - Unit 1 disabled");
// Cleanup
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glDisable(GL11.GL_TEXTURE_2D);
}
}
@@ -0,0 +1,475 @@
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 sharedDrawable so makeCurrent() can detect it
GLStateManager.setSharedDrawable(sharedDrawable);
// Main thread holds DrawableGL, so enable caching for it: This sets drawableGLHolder = current thread
GLStateManager.setCachingEnabled(true);
// 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.setSharedDrawable(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
executeOnSharedDrawable(() -> {
GLStateManager.glDeleteTextures(texId);
assertFalse(GL11.glIsTexture(texId), "Texture should not exist after SharedDrawable delete");
});
assertFalse(GL11.glIsTexture(texId), "Texture should not exist on main thread after SharedDrawable delete");
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
if (GL11.glIsTexture(texId)) {
GLStateManager.glDeleteTextures(texId);
}
}
}
}
@@ -0,0 +1,53 @@
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 original = splashCompleteField.getBoolean(null);
try {
splashCompleteField.setBoolean(null, false);
GLStateManager.setCachingEnabled(false);
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, original);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
}
}
}
@@ -0,0 +1,67 @@
package net.coderbot.iris.pipeline.transform;
import org.junit.jupiter.api.Test;
import org.taumc.glsl.ShaderParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ShaderTransformerTest {
@Test
void transformIsDeterministicUnderConcurrency() throws ExecutionException, InterruptedException {
TransformPatcher.clearCache();
ShaderTransformer.clearCache();
final String vertex = "#version 120\nvoid main(){gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;}";
final String fragment = "#version 120\nvoid main(){gl_FragColor = vec4(1.0);}";
ExecutorService exec = Executors.newFixedThreadPool(8);
try {
List<Callable<Map<PatchShaderType, String>>> tasks = new ArrayList<>();
for (int i = 0; i < 64; i++) {
tasks.add(() -> TransformPatcher.patchComposite(vertex, null, fragment));
}
List<Future<Map<PatchShaderType, String>>> futures = exec.invokeAll(tasks);
Map<PatchShaderType, String> first = futures.get(0).get();
assertNotNull(first);
for (Future<Map<PatchShaderType, String>> f : futures) {
Map<PatchShaderType, String> r = f.get();
assertEquals(first, r);
}
} finally {
exec.shutdownNow();
}
}
@Test
void formattedShaderIsParseable() {
TransformPatcher.clearCache();
ShaderTransformer.clearCache();
final String vertex = "#version 120\nvoid main(){gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;}";
final String fragment = "#version 120\nvoid main(){gl_FragColor = vec4(1.0);}";
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(vertex, null, fragment);
assertNotNull(transformed);
String v = transformed.get(PatchShaderType.VERTEX);
String f = transformed.get(PatchShaderType.FRAGMENT);
assertNotNull(v);
assertNotNull(f);
ShaderParser.parseShader(v);
ShaderParser.parseShader(f);
}
}